blob: 4ac172d1cbb5a81d5320332cd98c365348595aa8 [file] [log] [blame]
Anders Carlsson55085182007-08-21 17:43:55 +00001//===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-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 Carlsson55085182007-08-21 17:43:55 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Objective-C code as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Devang Patelbcbd03a2011-01-19 01:36:36 +000014#include "CGDebugInfo.h"
Ted Kremenek2979ec72008-04-09 15:51:31 +000015#include "CGObjCRuntime.h"
Anders Carlsson55085182007-08-21 17:43:55 +000016#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
John McCallf85e1932011-06-15 23:02:42 +000018#include "TargetInfo.h"
Daniel Dunbar85c59ed2008-08-29 08:11:39 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Chris Lattner16f00492009-04-26 01:32:48 +000021#include "clang/AST/StmtObjC.h"
Daniel Dunbare66f4e32008-09-03 00:27:26 +000022#include "clang/Basic/Diagnostic.h"
Anders Carlsson3d8400d2008-08-30 19:51:14 +000023#include "llvm/ADT/STLExtras.h"
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +000024#include "llvm/Target/TargetData.h"
John McCallf85e1932011-06-15 23:02:42 +000025#include "llvm/InlineAsm.h"
Anders Carlsson55085182007-08-21 17:43:55 +000026using namespace clang;
27using namespace CodeGen;
28
John McCallf85e1932011-06-15 23:02:42 +000029typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
30static TryEmitResult
31tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
Ted Kremenekebcb57a2012-03-06 20:05:56 +000032static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
Fariborz Jahanian490a52b2012-05-29 19:56:01 +000033 QualType ET,
Ted Kremenekebcb57a2012-03-06 20:05:56 +000034 const ObjCMethodDecl *Method,
35 RValue Result);
John McCallf85e1932011-06-15 23:02:42 +000036
37/// Given the address of a variable of pointer type, find the correct
38/// null to store into it.
39static llvm::Constant *getNullForVariable(llvm::Value *addr) {
Chris Lattner2acc6e32011-07-18 04:24:23 +000040 llvm::Type *type =
John McCallf85e1932011-06-15 23:02:42 +000041 cast<llvm::PointerType>(addr->getType())->getElementType();
42 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
43}
44
Chris Lattner8fdf3282008-06-24 17:04:18 +000045/// Emits an instance of NSConstantString representing the object.
Mike Stump1eb44332009-09-09 15:08:12 +000046llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar71fcec92008-11-25 21:53:21 +000047{
David Chisnall0d13f6f2010-01-23 02:40:42 +000048 llvm::Constant *C =
49 CGM.getObjCRuntime().GenerateConstantString(E->getString());
Daniel Dunbared7c6182008-08-20 00:28:19 +000050 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Anderson3c4972d2009-07-29 18:54:39 +000051 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattner8fdf3282008-06-24 17:04:18 +000052}
53
Patrick Beardeb382ec2012-04-19 00:25:12 +000054/// EmitObjCBoxedExpr - This routine generates code to call
55/// the appropriate expression boxing method. This will either be
56/// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:].
Ted Kremenekebcb57a2012-03-06 20:05:56 +000057///
Eric Christopher16098f32012-03-29 17:31:31 +000058llvm::Value *
Patrick Beardeb382ec2012-04-19 00:25:12 +000059CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +000060 // Generate the correct selector for this literal's concrete type.
Patrick Beardeb382ec2012-04-19 00:25:12 +000061 const Expr *SubExpr = E->getSubExpr();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000062 // Get the method.
Patrick Beardeb382ec2012-04-19 00:25:12 +000063 const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
64 assert(BoxingMethod && "BoxingMethod is null");
65 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
66 Selector Sel = BoxingMethod->getSelector();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000067
68 // Generate a reference to the class pointer, which will be the receiver.
Patrick Beardeb382ec2012-04-19 00:25:12 +000069 // Assumes that the method was introduced in the class that should be
70 // messaged (avoids pulling it out of the result type).
Ted Kremenekebcb57a2012-03-06 20:05:56 +000071 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Patrick Beardeb382ec2012-04-19 00:25:12 +000072 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
73 llvm::Value *Receiver = Runtime.GetClass(Builder, ClassDecl);
74
75 const ParmVarDecl *argDecl = *BoxingMethod->param_begin();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000076 QualType ArgQT = argDecl->getType().getUnqualifiedType();
Patrick Beardeb382ec2012-04-19 00:25:12 +000077 RValue RV = EmitAnyExpr(SubExpr);
Ted Kremenekebcb57a2012-03-06 20:05:56 +000078 CallArgList Args;
79 Args.add(RV, ArgQT);
Patrick Beardeb382ec2012-04-19 00:25:12 +000080
Ted Kremenekebcb57a2012-03-06 20:05:56 +000081 RValue result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Patrick Beardeb382ec2012-04-19 00:25:12 +000082 BoxingMethod->getResultType(), Sel, Receiver, Args,
83 ClassDecl, BoxingMethod);
Ted Kremenekebcb57a2012-03-06 20:05:56 +000084 return Builder.CreateBitCast(result.getScalarVal(),
85 ConvertType(E->getType()));
86}
87
88llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
89 const ObjCMethodDecl *MethodWithObjects) {
90 ASTContext &Context = CGM.getContext();
91 const ObjCDictionaryLiteral *DLE = 0;
92 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
93 if (!ALE)
94 DLE = cast<ObjCDictionaryLiteral>(E);
95
96 // Compute the type of the array we're initializing.
97 uint64_t NumElements =
98 ALE ? ALE->getNumElements() : DLE->getNumElements();
99 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
100 NumElements);
101 QualType ElementType = Context.getObjCIdType().withConst();
102 QualType ElementArrayType
103 = Context.getConstantArrayType(ElementType, APNumElements,
104 ArrayType::Normal, /*IndexTypeQuals=*/0);
105
106 // Allocate the temporary array(s).
107 llvm::Value *Objects = CreateMemTemp(ElementArrayType, "objects");
108 llvm::Value *Keys = 0;
109 if (DLE)
110 Keys = CreateMemTemp(ElementArrayType, "keys");
111
112 // Perform the actual initialialization of the array(s).
113 for (uint64_t i = 0; i < NumElements; i++) {
114 if (ALE) {
115 // Emit the initializer.
116 const Expr *Rhs = ALE->getElement(i);
117 LValue LV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
118 ElementType,
119 Context.getTypeAlignInChars(Rhs->getType()),
120 Context);
121 EmitScalarInit(Rhs, /*D=*/0, LV, /*capturedByInit=*/false);
122 } else {
123 // Emit the key initializer.
124 const Expr *Key = DLE->getKeyValueElement(i).Key;
125 LValue KeyLV = LValue::MakeAddr(Builder.CreateStructGEP(Keys, i),
126 ElementType,
127 Context.getTypeAlignInChars(Key->getType()),
128 Context);
129 EmitScalarInit(Key, /*D=*/0, KeyLV, /*capturedByInit=*/false);
130
131 // Emit the value initializer.
132 const Expr *Value = DLE->getKeyValueElement(i).Value;
133 LValue ValueLV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
134 ElementType,
135 Context.getTypeAlignInChars(Value->getType()),
136 Context);
137 EmitScalarInit(Value, /*D=*/0, ValueLV, /*capturedByInit=*/false);
138 }
139 }
140
141 // Generate the argument list.
142 CallArgList Args;
143 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
144 const ParmVarDecl *argDecl = *PI++;
145 QualType ArgQT = argDecl->getType().getUnqualifiedType();
146 Args.add(RValue::get(Objects), ArgQT);
147 if (DLE) {
148 argDecl = *PI++;
149 ArgQT = argDecl->getType().getUnqualifiedType();
150 Args.add(RValue::get(Keys), ArgQT);
151 }
152 argDecl = *PI;
153 ArgQT = argDecl->getType().getUnqualifiedType();
154 llvm::Value *Count =
155 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
156 Args.add(RValue::get(Count), ArgQT);
157
158 // Generate a reference to the class pointer, which will be the receiver.
159 Selector Sel = MethodWithObjects->getSelector();
160 QualType ResultType = E->getType();
161 const ObjCObjectPointerType *InterfacePointerType
162 = ResultType->getAsObjCInterfacePointerType();
163 ObjCInterfaceDecl *Class
164 = InterfacePointerType->getObjectType()->getInterface();
165 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
166 llvm::Value *Receiver = Runtime.GetClass(Builder, Class);
167
168 // Generate the message send.
Eric Christopher16098f32012-03-29 17:31:31 +0000169 RValue result
170 = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
171 MethodWithObjects->getResultType(),
172 Sel,
173 Receiver, Args, Class,
174 MethodWithObjects);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000175 return Builder.CreateBitCast(result.getScalarVal(),
176 ConvertType(E->getType()));
177}
178
179llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
180 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
181}
182
183llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
184 const ObjCDictionaryLiteral *E) {
185 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
186}
187
Chris Lattner8fdf3282008-06-24 17:04:18 +0000188/// Emit a selector.
189llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
190 // Untyped selector.
191 // Note that this implementation allows for non-constant strings to be passed
192 // as arguments to @selector(). Currently, the only thing preventing this
193 // behaviour is the type checking in the front end.
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000194 return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
Chris Lattner8fdf3282008-06-24 17:04:18 +0000195}
196
Daniel Dunbared7c6182008-08-20 00:28:19 +0000197llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
198 // FIXME: This should pass the Decl not the name.
199 return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol());
200}
Chris Lattner8fdf3282008-06-24 17:04:18 +0000201
Douglas Gregor926df6c2011-06-11 01:09:30 +0000202/// \brief Adjust the type of the result of an Objective-C message send
203/// expression when the method has a related result type.
204static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000205 QualType ExpT,
Douglas Gregor926df6c2011-06-11 01:09:30 +0000206 const ObjCMethodDecl *Method,
207 RValue Result) {
208 if (!Method)
209 return Result;
John McCallf85e1932011-06-15 23:02:42 +0000210
Douglas Gregor926df6c2011-06-11 01:09:30 +0000211 if (!Method->hasRelatedResultType() ||
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000212 CGF.getContext().hasSameType(ExpT, Method->getResultType()) ||
Douglas Gregor926df6c2011-06-11 01:09:30 +0000213 !Result.isScalar())
214 return Result;
215
216 // We have applied a related result type. Cast the rvalue appropriately.
217 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000218 CGF.ConvertType(ExpT)));
Douglas Gregor926df6c2011-06-11 01:09:30 +0000219}
Chris Lattner8fdf3282008-06-24 17:04:18 +0000220
John McCalldc7c5ad2011-07-22 08:53:00 +0000221/// Decide whether to extend the lifetime of the receiver of a
222/// returns-inner-pointer message.
223static bool
224shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
225 switch (message->getReceiverKind()) {
226
227 // For a normal instance message, we should extend unless the
228 // receiver is loaded from a variable with precise lifetime.
229 case ObjCMessageExpr::Instance: {
230 const Expr *receiver = message->getInstanceReceiver();
231 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
232 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
233 receiver = ice->getSubExpr()->IgnoreParens();
234
235 // Only __strong variables.
236 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
237 return true;
238
239 // All ivars and fields have precise lifetime.
240 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
241 return false;
242
243 // Otherwise, check for variables.
244 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
245 if (!declRef) return true;
246 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
247 if (!var) return true;
248
249 // All variables have precise lifetime except local variables with
250 // automatic storage duration that aren't specially marked.
251 return (var->hasLocalStorage() &&
252 !var->hasAttr<ObjCPreciseLifetimeAttr>());
253 }
254
255 case ObjCMessageExpr::Class:
256 case ObjCMessageExpr::SuperClass:
257 // It's never necessary for class objects.
258 return false;
259
260 case ObjCMessageExpr::SuperInstance:
261 // We generally assume that 'self' lives throughout a method call.
262 return false;
263 }
264
265 llvm_unreachable("invalid receiver kind");
266}
267
John McCallef072fd2010-05-22 01:48:05 +0000268RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
269 ReturnValueSlot Return) {
Chris Lattner8fdf3282008-06-24 17:04:18 +0000270 // Only the lookup mechanism and first two arguments of the method
271 // implementation vary between runtimes. We can get the receiver and
272 // arguments in generic code.
Mike Stump1eb44332009-09-09 15:08:12 +0000273
John McCallf85e1932011-06-15 23:02:42 +0000274 bool isDelegateInit = E->isDelegateInitCall();
275
John McCalldc7c5ad2011-07-22 08:53:00 +0000276 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian4e1524b2012-01-29 20:27:13 +0000277
John McCallf85e1932011-06-15 23:02:42 +0000278 // We don't retain the receiver in delegate init calls, and this is
279 // safe because the receiver value is always loaded from 'self',
280 // which we zero out. We don't want to Block_copy block receivers,
281 // though.
282 bool retainSelf =
283 (!isDelegateInit &&
David Blaikie4e4d0842012-03-11 07:00:24 +0000284 CGM.getLangOpts().ObjCAutoRefCount &&
John McCalldc7c5ad2011-07-22 08:53:00 +0000285 method &&
286 method->hasAttr<NSConsumesSelfAttr>());
John McCallf85e1932011-06-15 23:02:42 +0000287
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000288 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000289 bool isSuperMessage = false;
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000290 bool isClassMessage = false;
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000291 ObjCInterfaceDecl *OID = 0;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000292 // Find the receiver
Douglas Gregor926df6c2011-06-11 01:09:30 +0000293 QualType ReceiverType;
Daniel Dunbar0b647a62010-04-22 03:17:06 +0000294 llvm::Value *Receiver = 0;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000295 switch (E->getReceiverKind()) {
296 case ObjCMessageExpr::Instance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000297 ReceiverType = E->getInstanceReceiver()->getType();
John McCallf85e1932011-06-15 23:02:42 +0000298 if (retainSelf) {
299 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
300 E->getInstanceReceiver());
301 Receiver = ter.getPointer();
John McCalldc7c5ad2011-07-22 08:53:00 +0000302 if (ter.getInt()) retainSelf = false;
John McCallf85e1932011-06-15 23:02:42 +0000303 } else
304 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor04badcf2010-04-21 00:45:42 +0000305 break;
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000306
Douglas Gregor04badcf2010-04-21 00:45:42 +0000307 case ObjCMessageExpr::Class: {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000308 ReceiverType = E->getClassReceiver();
309 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3031c632010-05-17 20:12:43 +0000310 assert(ObjTy && "Invalid Objective-C class message send");
311 OID = ObjTy->getInterface();
312 assert(OID && "Invalid Objective-C class message send");
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000313 Receiver = Runtime.GetClass(Builder, OID);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000314 isClassMessage = true;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000315 break;
316 }
317
318 case ObjCMessageExpr::SuperInstance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000319 ReceiverType = E->getSuperType();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000320 Receiver = LoadObjCSelf();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000321 isSuperMessage = true;
322 break;
323
324 case ObjCMessageExpr::SuperClass:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000325 ReceiverType = E->getSuperType();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000326 Receiver = LoadObjCSelf();
327 isSuperMessage = true;
328 isClassMessage = true;
329 break;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000330 }
331
John McCalldc7c5ad2011-07-22 08:53:00 +0000332 if (retainSelf)
333 Receiver = EmitARCRetainNonBlock(Receiver);
334
335 // In ARC, we sometimes want to "extend the lifetime"
336 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
337 // messages.
David Blaikie4e4d0842012-03-11 07:00:24 +0000338 if (getLangOpts().ObjCAutoRefCount && method &&
John McCalldc7c5ad2011-07-22 08:53:00 +0000339 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
340 shouldExtendReceiverForInnerPointerMessage(E))
341 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
342
John McCallf85e1932011-06-15 23:02:42 +0000343 QualType ResultType =
John McCalldc7c5ad2011-07-22 08:53:00 +0000344 method ? method->getResultType() : E->getType();
John McCallf85e1932011-06-15 23:02:42 +0000345
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000346 CallArgList Args;
John McCalldc7c5ad2011-07-22 08:53:00 +0000347 EmitCallArgs(Args, method, E->arg_begin(), E->arg_end());
Mike Stump1eb44332009-09-09 15:08:12 +0000348
John McCallf85e1932011-06-15 23:02:42 +0000349 // For delegate init calls in ARC, do an unsafe store of null into
350 // self. This represents the call taking direct ownership of that
351 // value. We have to do this after emitting the other call
352 // arguments because they might also reference self, but we don't
353 // have to worry about any of them modifying self because that would
354 // be an undefined read and write of an object in unordered
355 // expressions.
356 if (isDelegateInit) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000357 assert(getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +0000358 "delegate init calls should only be marked in ARC");
359
360 // Do an unsafe store of null into self.
361 llvm::Value *selfAddr =
362 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
363 assert(selfAddr && "no self entry for a delegate init call?");
364
365 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
366 }
Anders Carlsson7e70fb22010-06-21 20:59:55 +0000367
Douglas Gregor926df6c2011-06-11 01:09:30 +0000368 RValue result;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000369 if (isSuperMessage) {
Chris Lattner9384c762008-06-26 04:42:20 +0000370 // super is only valid in an Objective-C method
371 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000372 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor926df6c2011-06-11 01:09:30 +0000373 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
374 E->getSelector(),
375 OMD->getClassInterface(),
376 isCategoryImpl,
377 Receiver,
378 isClassMessage,
379 Args,
John McCalldc7c5ad2011-07-22 08:53:00 +0000380 method);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000381 } else {
382 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
383 E->getSelector(),
384 Receiver, Args, OID,
John McCalldc7c5ad2011-07-22 08:53:00 +0000385 method);
Chris Lattner8fdf3282008-06-24 17:04:18 +0000386 }
John McCallf85e1932011-06-15 23:02:42 +0000387
388 // For delegate init calls in ARC, implicitly store the result of
389 // the call back into self. This takes ownership of the value.
390 if (isDelegateInit) {
391 llvm::Value *selfAddr =
392 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
393 llvm::Value *newSelf = result.getScalarVal();
394
395 // The delegate return type isn't necessarily a matching type; in
396 // fact, it's quite likely to be 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000397 llvm::Type *selfTy =
John McCallf85e1932011-06-15 23:02:42 +0000398 cast<llvm::PointerType>(selfAddr->getType())->getElementType();
399 newSelf = Builder.CreateBitCast(newSelf, selfTy);
400
401 Builder.CreateStore(newSelf, selfAddr);
402 }
Fariborz Jahanian4e1524b2012-01-29 20:27:13 +0000403
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000404 return AdjustRelatedResultType(*this, E->getType(), method, result);
Anders Carlsson55085182007-08-21 17:43:55 +0000405}
406
John McCallf85e1932011-06-15 23:02:42 +0000407namespace {
408struct FinishARCDealloc : EHScopeStack::Cleanup {
John McCallad346f42011-07-12 20:27:29 +0000409 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +0000410 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCall799d34e2011-07-13 18:26:47 +0000411
412 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCallf85e1932011-06-15 23:02:42 +0000413 const ObjCInterfaceDecl *iface = impl->getClassInterface();
414 if (!iface->getSuperClass()) return;
415
John McCall799d34e2011-07-13 18:26:47 +0000416 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
417
John McCallf85e1932011-06-15 23:02:42 +0000418 // Call [super dealloc] if we have a superclass.
419 llvm::Value *self = CGF.LoadObjCSelf();
420
421 CallArgList args;
422 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
423 CGF.getContext().VoidTy,
424 method->getSelector(),
425 iface,
John McCall799d34e2011-07-13 18:26:47 +0000426 isCategory,
John McCallf85e1932011-06-15 23:02:42 +0000427 self,
428 /*is class msg*/ false,
429 args,
430 method);
431 }
432};
433}
434
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000435/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
436/// the LLVM function and sets the other context used by
437/// CodeGenFunction.
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000438void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
Devang Patel8d3f8972011-05-19 23:37:41 +0000439 const ObjCContainerDecl *CD,
440 SourceLocation StartLoc) {
John McCalld26bc762011-03-09 04:27:21 +0000441 FunctionArgList args;
Devang Patel4800ea62010-04-05 21:09:15 +0000442 // Check if we should generate debug info for this method.
Devang Patelaa112892011-03-07 18:45:56 +0000443 if (CGM.getModuleDebugInfo() && !OMD->hasAttr<NoDebugAttr>())
444 DebugInfo = CGM.getModuleDebugInfo();
Devang Patel4800ea62010-04-05 21:09:15 +0000445
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000446 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000447
John McCallde5d3c72012-02-17 03:33:10 +0000448 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000449 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner41110242008-06-17 18:05:57 +0000450
John McCalld26bc762011-03-09 04:27:21 +0000451 args.push_back(OMD->getSelfDecl());
452 args.push_back(OMD->getCmdDecl());
Chris Lattner41110242008-06-17 18:05:57 +0000453
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +0000454 for (ObjCMethodDecl::param_const_iterator PI = OMD->param_begin(),
Eric Christopher16098f32012-03-29 17:31:31 +0000455 E = OMD->param_end(); PI != E; ++PI)
John McCalld26bc762011-03-09 04:27:21 +0000456 args.push_back(*PI);
Chris Lattner41110242008-06-17 18:05:57 +0000457
Peter Collingbourne14110472011-01-13 18:57:25 +0000458 CurGD = OMD;
459
Devang Patel8d3f8972011-05-19 23:37:41 +0000460 StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc);
John McCallf85e1932011-06-15 23:02:42 +0000461
462 // In ARC, certain methods get an extra cleanup.
David Blaikie4e4d0842012-03-11 07:00:24 +0000463 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +0000464 OMD->isInstanceMethod() &&
465 OMD->getSelector().isUnarySelector()) {
466 const IdentifierInfo *ident =
467 OMD->getSelector().getIdentifierInfoForSlot(0);
468 if (ident->isStr("dealloc"))
469 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
470 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000471}
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000472
John McCallf85e1932011-06-15 23:02:42 +0000473static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
474 LValue lvalue, QualType type);
475
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000476/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump1eb44332009-09-09 15:08:12 +0000477/// its pointer, name, and types registered in the class struture.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000478void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
Devang Patel8d3f8972011-05-19 23:37:41 +0000479 StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000480 EmitStmt(OMD->getBody());
481 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000482}
483
John McCall41bdde92011-09-12 23:06:44 +0000484/// emitStructGetterCall - Call the runtime function to load a property
485/// into the return value slot.
486static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
487 bool isAtomic, bool hasStrong) {
488 ASTContext &Context = CGF.getContext();
489
490 llvm::Value *src =
491 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(),
492 ivar, 0).getAddress();
493
494 // objc_copyStruct (ReturnValue, &structIvar,
495 // sizeof (Type of Ivar), isAtomic, false);
496 CallArgList args;
497
498 llvm::Value *dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
499 args.add(RValue::get(dest), Context.VoidPtrTy);
500
501 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
502 args.add(RValue::get(src), Context.VoidPtrTy);
503
504 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
505 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
506 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
507 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
508
509 llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
John McCall0f3d0972012-07-07 06:41:13 +0000510 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(Context.VoidTy, args,
511 FunctionType::ExtInfo(),
512 RequiredArgs::All),
John McCall41bdde92011-09-12 23:06:44 +0000513 fn, ReturnValueSlot(), args);
514}
515
John McCall1e1f4872011-09-13 03:34:09 +0000516/// Determine whether the given architecture supports unaligned atomic
517/// accesses. They don't have to be fast, just faster than a function
518/// call and a mutex.
519static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedmande24d442011-09-13 20:48:30 +0000520 // FIXME: Allow unaligned atomic load/store on x86. (It is not
521 // currently supported by the backend.)
522 return 0;
John McCall1e1f4872011-09-13 03:34:09 +0000523}
524
525/// Return the maximum size that permits atomic accesses for the given
526/// architecture.
527static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
528 llvm::Triple::ArchType arch) {
529 // ARM has 8-byte atomic accesses, but it's not clear whether we
530 // want to rely on them here.
531
532 // In the default case, just assume that any size up to a pointer is
533 // fine given adequate alignment.
534 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
535}
536
537namespace {
538 class PropertyImplStrategy {
539 public:
540 enum StrategyKind {
541 /// The 'native' strategy is to use the architecture's provided
542 /// reads and writes.
543 Native,
544
545 /// Use objc_setProperty and objc_getProperty.
546 GetSetProperty,
547
548 /// Use objc_setProperty for the setter, but use expression
549 /// evaluation for the getter.
550 SetPropertyAndExpressionGet,
551
552 /// Use objc_copyStruct.
553 CopyStruct,
554
555 /// The 'expression' strategy is to emit normal assignment or
556 /// lvalue-to-rvalue expressions.
557 Expression
558 };
559
560 StrategyKind getKind() const { return StrategyKind(Kind); }
561
562 bool hasStrongMember() const { return HasStrong; }
563 bool isAtomic() const { return IsAtomic; }
564 bool isCopy() const { return IsCopy; }
565
566 CharUnits getIvarSize() const { return IvarSize; }
567 CharUnits getIvarAlignment() const { return IvarAlignment; }
568
569 PropertyImplStrategy(CodeGenModule &CGM,
570 const ObjCPropertyImplDecl *propImpl);
571
572 private:
573 unsigned Kind : 8;
574 unsigned IsAtomic : 1;
575 unsigned IsCopy : 1;
576 unsigned HasStrong : 1;
577
578 CharUnits IvarSize;
579 CharUnits IvarAlignment;
580 };
581}
582
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000583/// Pick an implementation strategy for the given property synthesis.
John McCall1e1f4872011-09-13 03:34:09 +0000584PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
585 const ObjCPropertyImplDecl *propImpl) {
586 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall265941b2011-09-13 18:31:23 +0000587 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCall1e1f4872011-09-13 03:34:09 +0000588
John McCall265941b2011-09-13 18:31:23 +0000589 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
590 IsAtomic = prop->isAtomic();
John McCall1e1f4872011-09-13 03:34:09 +0000591 HasStrong = false; // doesn't matter here.
592
593 // Evaluate the ivar's size and alignment.
594 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
595 QualType ivarType = ivar->getType();
596 llvm::tie(IvarSize, IvarAlignment)
597 = CGM.getContext().getTypeInfoInChars(ivarType);
598
599 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall265941b2011-09-13 18:31:23 +0000600 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCall1e1f4872011-09-13 03:34:09 +0000601 if (IsCopy) {
602 Kind = GetSetProperty;
603 return;
604 }
605
John McCall265941b2011-09-13 18:31:23 +0000606 // Handle retain.
607 if (setterKind == ObjCPropertyDecl::Retain) {
John McCall1e1f4872011-09-13 03:34:09 +0000608 // In GC-only, there's nothing special that needs to be done.
David Blaikie4e4d0842012-03-11 07:00:24 +0000609 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCall1e1f4872011-09-13 03:34:09 +0000610 // fallthrough
611
612 // In ARC, if the property is non-atomic, use expression emission,
613 // which translates to objc_storeStrong. This isn't required, but
614 // it's slightly nicer.
David Blaikie4e4d0842012-03-11 07:00:24 +0000615 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCall1e1f4872011-09-13 03:34:09 +0000616 Kind = Expression;
617 return;
618
619 // Otherwise, we need to at least use setProperty. However, if
620 // the property isn't atomic, we can use normal expression
621 // emission for the getter.
622 } else if (!IsAtomic) {
623 Kind = SetPropertyAndExpressionGet;
624 return;
625
626 // Otherwise, we have to use both setProperty and getProperty.
627 } else {
628 Kind = GetSetProperty;
629 return;
630 }
631 }
632
633 // If we're not atomic, just use expression accesses.
634 if (!IsAtomic) {
635 Kind = Expression;
636 return;
637 }
638
John McCall5889c602011-09-13 05:36:29 +0000639 // Properties on bitfield ivars need to be emitted using expression
640 // accesses even if they're nominally atomic.
641 if (ivar->isBitField()) {
642 Kind = Expression;
643 return;
644 }
645
John McCall1e1f4872011-09-13 03:34:09 +0000646 // GC-qualified or ARC-qualified ivars need to be emitted as
647 // expressions. This actually works out to being atomic anyway,
648 // except for ARC __strong, but that should trigger the above code.
649 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikie4e4d0842012-03-11 07:00:24 +0000650 (CGM.getLangOpts().getGC() &&
John McCall1e1f4872011-09-13 03:34:09 +0000651 CGM.getContext().getObjCGCAttrKind(ivarType))) {
652 Kind = Expression;
653 return;
654 }
655
656 // Compute whether the ivar has strong members.
David Blaikie4e4d0842012-03-11 07:00:24 +0000657 if (CGM.getLangOpts().getGC())
John McCall1e1f4872011-09-13 03:34:09 +0000658 if (const RecordType *recordType = ivarType->getAs<RecordType>())
659 HasStrong = recordType->getDecl()->hasObjectMember();
660
661 // We can never access structs with object members with a native
662 // access, because we need to use write barriers. This is what
663 // objc_copyStruct is for.
664 if (HasStrong) {
665 Kind = CopyStruct;
666 return;
667 }
668
669 // Otherwise, this is target-dependent and based on the size and
670 // alignment of the ivar.
John McCallc5d9a902011-09-13 07:33:34 +0000671
672 // If the size of the ivar is not a power of two, give up. We don't
673 // want to get into the business of doing compare-and-swaps.
674 if (!IvarSize.isPowerOfTwo()) {
675 Kind = CopyStruct;
676 return;
677 }
678
John McCall1e1f4872011-09-13 03:34:09 +0000679 llvm::Triple::ArchType arch =
680 CGM.getContext().getTargetInfo().getTriple().getArch();
681
682 // Most architectures require memory to fit within a single cache
683 // line, so the alignment has to be at least the size of the access.
684 // Otherwise we have to grab a lock.
685 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
686 Kind = CopyStruct;
687 return;
688 }
689
690 // If the ivar's size exceeds the architecture's maximum atomic
691 // access size, we have to use CopyStruct.
692 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
693 Kind = CopyStruct;
694 return;
695 }
696
697 // Otherwise, we can use native loads and stores.
698 Kind = Native;
699}
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000700
James Dennett2ee5ba32012-06-15 22:10:14 +0000701/// \brief Generate an Objective-C property getter function.
702///
703/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff489034c2009-01-10 22:55:25 +0000704/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000705void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
706 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000707 llvm::Constant *AtomicHelperFn =
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000708 GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000709 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
710 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
711 assert(OMD && "Invalid call to generate getter (empty method)");
Eric Christopherea320472012-04-03 00:44:15 +0000712 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +0000713
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000714 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCall1e1f4872011-09-13 03:34:09 +0000715
716 FinishFunction();
717}
718
John McCall6c11f0b2011-09-13 06:00:03 +0000719static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
720 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCall1e1f4872011-09-13 03:34:09 +0000721 if (!getter) return true;
722
723 // Sema only makes only of these when the ivar has a C++ class type,
724 // so the form is pretty constrained.
725
John McCall6c11f0b2011-09-13 06:00:03 +0000726 // If the property has a reference type, we might just be binding a
727 // reference, in which case the result will be a gl-value. We should
728 // treat this as a non-trivial operation.
729 if (getter->isGLValue())
730 return false;
731
John McCall1e1f4872011-09-13 03:34:09 +0000732 // If we selected a trivial copy-constructor, we're okay.
733 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
734 return (construct->getConstructor()->isTrivial());
735
736 // The constructor might require cleanups (in which case it's never
737 // trivial).
738 assert(isa<ExprWithCleanups>(getter));
739 return false;
740}
741
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000742/// emitCPPObjectAtomicGetterCall - Call the runtime function to
743/// copy the ivar into the resturn slot.
744static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
745 llvm::Value *returnAddr,
746 ObjCIvarDecl *ivar,
747 llvm::Constant *AtomicHelperFn) {
748 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
749 // AtomicHelperFn);
750 CallArgList args;
751
752 // The 1st argument is the return Slot.
753 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
754
755 // The 2nd argument is the address of the ivar.
756 llvm::Value *ivarAddr =
757 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
758 CGF.LoadObjCSelf(), ivar, 0).getAddress();
759 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
760 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
761
762 // Third argument is the helper function.
763 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
764
765 llvm::Value *copyCppAtomicObjectFn =
766 CGF.CGM.getObjCRuntime().GetCppAtomicObjectFunction();
John McCall0f3d0972012-07-07 06:41:13 +0000767 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
768 args,
769 FunctionType::ExtInfo(),
770 RequiredArgs::All),
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000771 copyCppAtomicObjectFn, ReturnValueSlot(), args);
772}
773
John McCall1e1f4872011-09-13 03:34:09 +0000774void
775CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000776 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000777 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000778 llvm::Constant *AtomicHelperFn) {
John McCall1e1f4872011-09-13 03:34:09 +0000779 // If there's a non-trivial 'get' expression, we just have to emit that.
780 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000781 if (!AtomicHelperFn) {
782 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
783 /*nrvo*/ 0);
784 EmitReturnStmt(ret);
785 }
786 else {
787 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
788 emitCPPObjectAtomicGetterCall(*this, ReturnValue,
789 ivar, AtomicHelperFn);
790 }
John McCall1e1f4872011-09-13 03:34:09 +0000791 return;
792 }
793
794 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
795 QualType propType = prop->getType();
796 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
797
798 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
799
800 // Pick an implementation strategy.
801 PropertyImplStrategy strategy(CGM, propImpl);
802 switch (strategy.getKind()) {
803 case PropertyImplStrategy::Native: {
804 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
805
806 // Currently, all atomic accesses have to be through integer
807 // types, so there's no point in trying to pick a prettier type.
808 llvm::Type *bitcastType =
809 llvm::Type::getIntNTy(getLLVMContext(),
810 getContext().toBits(strategy.getIvarSize()));
811 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
812
813 // Perform an atomic load. This does not impose ordering constraints.
814 llvm::Value *ivarAddr = LV.getAddress();
815 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
816 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
817 load->setAlignment(strategy.getIvarAlignment().getQuantity());
818 load->setAtomic(llvm::Unordered);
819
820 // Store that value into the return address. Doing this with a
821 // bitcast is likely to produce some pretty ugly IR, but it's not
822 // the *most* terrible thing in the world.
823 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
824
825 // Make sure we don't do an autorelease.
826 AutoreleaseResult = false;
827 return;
828 }
829
830 case PropertyImplStrategy::GetSetProperty: {
831 llvm::Value *getPropertyFn =
832 CGM.getObjCRuntime().GetPropertyGetFunction();
833 if (!getPropertyFn) {
834 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000835 return;
836 }
837
838 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
839 // FIXME: Can't this be simpler? This might even be worse than the
840 // corresponding gcc code.
John McCall1e1f4872011-09-13 03:34:09 +0000841 llvm::Value *cmd =
842 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
843 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
844 llvm::Value *ivarOffset =
845 EmitIvarOffset(classImpl->getClassInterface(), ivar);
846
847 CallArgList args;
848 args.add(RValue::get(self), getContext().getObjCIdType());
849 args.add(RValue::get(cmd), getContext().getObjCSelType());
850 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall265941b2011-09-13 18:31:23 +0000851 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
852 getContext().BoolTy);
John McCall1e1f4872011-09-13 03:34:09 +0000853
Daniel Dunbare4be5a62009-02-03 23:43:59 +0000854 // FIXME: We shouldn't need to get the function info here, the
855 // runtime already should have computed it to build the function.
John McCall0f3d0972012-07-07 06:41:13 +0000856 RValue RV = EmitCall(getTypes().arrangeFreeFunctionCall(propType, args,
857 FunctionType::ExtInfo(),
858 RequiredArgs::All),
John McCall1e1f4872011-09-13 03:34:09 +0000859 getPropertyFn, ReturnValueSlot(), args);
860
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000861 // We need to fix the type here. Ivars with copy & retain are
862 // always objects so we don't need to worry about complex or
863 // aggregates.
Mike Stump1eb44332009-09-09 15:08:12 +0000864 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
Fariborz Jahanian52c18b02012-04-26 21:33:14 +0000865 getTypes().ConvertType(getterMethod->getResultType())));
John McCall1e1f4872011-09-13 03:34:09 +0000866
867 EmitReturnOfRValue(RV, propType);
John McCallf85e1932011-06-15 23:02:42 +0000868
869 // objc_getProperty does an autorelease, so we should suppress ours.
870 AutoreleaseResult = false;
John McCallf85e1932011-06-15 23:02:42 +0000871
John McCall1e1f4872011-09-13 03:34:09 +0000872 return;
873 }
874
875 case PropertyImplStrategy::CopyStruct:
876 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
877 strategy.hasStrongMember());
878 return;
879
880 case PropertyImplStrategy::Expression:
881 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
882 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
883
884 QualType ivarType = ivar->getType();
885 if (ivarType->isAnyComplexType()) {
886 ComplexPairTy pair = LoadComplexFromAddr(LV.getAddress(),
887 LV.isVolatileQualified());
888 StoreComplexToAddr(pair, ReturnValue, LV.isVolatileQualified());
889 } else if (hasAggregateLLVMType(ivarType)) {
890 // The return value slot is guaranteed to not be aliased, but
891 // that's not necessarily the same as "on the stack", so
892 // we still potentially need objc_memmove_collectable.
Chad Rosier649b4a12012-03-29 17:37:10 +0000893 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
John McCall1e1f4872011-09-13 03:34:09 +0000894 } else {
John McCallba3dd902011-07-22 05:23:13 +0000895 llvm::Value *value;
896 if (propType->isReferenceType()) {
897 value = LV.getAddress();
898 } else {
899 // We want to load and autoreleaseReturnValue ARC __weak ivars.
900 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall1e1f4872011-09-13 03:34:09 +0000901 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
John McCallba3dd902011-07-22 05:23:13 +0000902
903 // Otherwise we want to do a simple load, suppressing the
904 // final autorelease.
John McCallf85e1932011-06-15 23:02:42 +0000905 } else {
John McCallba3dd902011-07-22 05:23:13 +0000906 value = EmitLoadOfLValue(LV).getScalarVal();
907 AutoreleaseResult = false;
Fariborz Jahanian14086762011-03-28 23:47:18 +0000908 }
John McCallf85e1932011-06-15 23:02:42 +0000909
John McCallba3dd902011-07-22 05:23:13 +0000910 value = Builder.CreateBitCast(value, ConvertType(propType));
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000911 value = Builder.CreateBitCast(value,
912 ConvertType(GetterMethodDecl->getResultType()));
John McCallba3dd902011-07-22 05:23:13 +0000913 }
914
915 EmitReturnOfRValue(RValue::get(value), propType);
Fariborz Jahanianed1d29d2009-03-03 18:49:40 +0000916 }
John McCall1e1f4872011-09-13 03:34:09 +0000917 return;
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000918 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000919
John McCall1e1f4872011-09-13 03:34:09 +0000920 }
921 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000922}
923
John McCall41bdde92011-09-12 23:06:44 +0000924/// emitStructSetterCall - Call the runtime function to store the value
925/// from the first formal parameter into the given ivar.
926static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
927 ObjCIvarDecl *ivar) {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000928 // objc_copyStruct (&structIvar, &Arg,
929 // sizeof (struct something), true, false);
John McCallbbb253c2011-09-10 09:30:49 +0000930 CallArgList args;
931
932 // The first argument is the address of the ivar.
John McCall41bdde92011-09-12 23:06:44 +0000933 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
934 CGF.LoadObjCSelf(), ivar, 0)
935 .getAddress();
936 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
937 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000938
939 // The second argument is the address of the parameter variable.
John McCall41bdde92011-09-12 23:06:44 +0000940 ParmVarDecl *argVar = *OMD->param_begin();
John McCallf4b88a42012-03-10 09:33:50 +0000941 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanianc3953aa2012-01-05 00:10:16 +0000942 VK_LValue, SourceLocation());
John McCall41bdde92011-09-12 23:06:44 +0000943 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
944 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
945 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000946
947 // The third argument is the sizeof the type.
948 llvm::Value *size =
John McCall41bdde92011-09-12 23:06:44 +0000949 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
950 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCallbbb253c2011-09-10 09:30:49 +0000951
John McCall41bdde92011-09-12 23:06:44 +0000952 // The fourth argument is the 'isAtomic' flag.
953 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCallbbb253c2011-09-10 09:30:49 +0000954
John McCall41bdde92011-09-12 23:06:44 +0000955 // The fifth argument is the 'hasStrong' flag.
956 // FIXME: should this really always be false?
957 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
958
959 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCall0f3d0972012-07-07 06:41:13 +0000960 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
961 args,
962 FunctionType::ExtInfo(),
963 RequiredArgs::All),
John McCall41bdde92011-09-12 23:06:44 +0000964 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000965}
966
Fariborz Jahaniancd93b962012-01-06 22:33:54 +0000967/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
968/// the value from the first formal parameter into the given ivar, using
969/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
970static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
971 ObjCMethodDecl *OMD,
972 ObjCIvarDecl *ivar,
973 llvm::Constant *AtomicHelperFn) {
974 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
975 // AtomicHelperFn);
976 CallArgList args;
977
978 // The first argument is the address of the ivar.
979 llvm::Value *ivarAddr =
980 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
981 CGF.LoadObjCSelf(), ivar, 0).getAddress();
982 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
983 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
984
985 // The second argument is the address of the parameter variable.
986 ParmVarDecl *argVar = *OMD->param_begin();
John McCallf4b88a42012-03-10 09:33:50 +0000987 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahaniancd93b962012-01-06 22:33:54 +0000988 VK_LValue, SourceLocation());
989 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
990 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
991 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
992
993 // Third argument is the helper function.
994 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
995
996 llvm::Value *copyCppAtomicObjectFn =
997 CGF.CGM.getObjCRuntime().GetCppAtomicObjectFunction();
John McCall0f3d0972012-07-07 06:41:13 +0000998 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
999 args,
1000 FunctionType::ExtInfo(),
1001 RequiredArgs::All),
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001002 copyCppAtomicObjectFn, ReturnValueSlot(), args);
1003
1004
1005}
1006
Fariborz Jahanian20abee62012-01-10 00:37:01 +00001007
John McCall1e1f4872011-09-13 03:34:09 +00001008static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1009 Expr *setter = PID->getSetterCXXAssignment();
1010 if (!setter) return true;
1011
1012 // Sema only makes only of these when the ivar has a C++ class type,
1013 // so the form is pretty constrained.
John McCall71c758d2011-09-10 09:17:20 +00001014
1015 // An operator call is trivial if the function it calls is trivial.
John McCall1e1f4872011-09-13 03:34:09 +00001016 // This also implies that there's nothing non-trivial going on with
1017 // the arguments, because operator= can only be trivial if it's a
1018 // synthesized assignment operator and therefore both parameters are
1019 // references.
1020 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall71c758d2011-09-10 09:17:20 +00001021 if (const FunctionDecl *callee
1022 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1023 if (callee->isTrivial())
1024 return true;
1025 return false;
Fariborz Jahanian01cb3072011-04-06 16:05:26 +00001026 }
John McCall71c758d2011-09-10 09:17:20 +00001027
John McCall1e1f4872011-09-13 03:34:09 +00001028 assert(isa<ExprWithCleanups>(setter));
John McCall71c758d2011-09-10 09:17:20 +00001029 return false;
1030}
1031
Benjamin Kramer4e494cf2012-03-10 20:38:56 +00001032static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001033 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001034 return false;
1035 const TargetInfo &Target = CGM.getContext().getTargetInfo();
Benjamin Kramer4e494cf2012-03-10 20:38:56 +00001036
1037 if (Target.getPlatformName() != "macosx")
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001038 return false;
Benjamin Kramer4e494cf2012-03-10 20:38:56 +00001039
1040 return Target.getPlatformMinVersion() >= VersionTuple(10, 8);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001041}
1042
John McCall71c758d2011-09-10 09:17:20 +00001043void
1044CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001045 const ObjCPropertyImplDecl *propImpl,
1046 llvm::Constant *AtomicHelperFn) {
John McCall71c758d2011-09-10 09:17:20 +00001047 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian84e49862012-01-06 00:29:35 +00001048 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall71c758d2011-09-10 09:17:20 +00001049 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001050
1051 // Just use the setter expression if Sema gave us one and it's
1052 // non-trivial.
1053 if (!hasTrivialSetExpr(propImpl)) {
1054 if (!AtomicHelperFn)
1055 // If non-atomic, assignment is called directly.
1056 EmitStmt(propImpl->getSetterCXXAssignment());
1057 else
1058 // If atomic, assignment is called via a locking api.
1059 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1060 AtomicHelperFn);
1061 return;
1062 }
John McCall71c758d2011-09-10 09:17:20 +00001063
John McCall1e1f4872011-09-13 03:34:09 +00001064 PropertyImplStrategy strategy(CGM, propImpl);
1065 switch (strategy.getKind()) {
1066 case PropertyImplStrategy::Native: {
1067 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
John McCall71c758d2011-09-10 09:17:20 +00001068
John McCall1e1f4872011-09-13 03:34:09 +00001069 LValue ivarLValue =
1070 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1071 llvm::Value *ivarAddr = ivarLValue.getAddress();
John McCall71c758d2011-09-10 09:17:20 +00001072
John McCall1e1f4872011-09-13 03:34:09 +00001073 // Currently, all atomic accesses have to be through integer
1074 // types, so there's no point in trying to pick a prettier type.
1075 llvm::Type *bitcastType =
1076 llvm::Type::getIntNTy(getLLVMContext(),
1077 getContext().toBits(strategy.getIvarSize()));
1078 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1079
1080 // Cast both arguments to the chosen operation type.
1081 argAddr = Builder.CreateBitCast(argAddr, bitcastType);
1082 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1083
1084 // This bitcast load is likely to cause some nasty IR.
1085 llvm::Value *load = Builder.CreateLoad(argAddr);
1086
1087 // Perform an atomic store. There are no memory ordering requirements.
1088 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1089 store->setAlignment(strategy.getIvarAlignment().getQuantity());
1090 store->setAtomic(llvm::Unordered);
1091 return;
1092 }
1093
1094 case PropertyImplStrategy::GetSetProperty:
1095 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001096
1097 llvm::Value *setOptimizedPropertyFn = 0;
1098 llvm::Value *setPropertyFn = 0;
1099 if (UseOptimizedSetter(CGM)) {
1100 // 10.8 code and GC is off
1101 setOptimizedPropertyFn =
Eric Christopher16098f32012-03-29 17:31:31 +00001102 CGM.getObjCRuntime()
1103 .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1104 strategy.isCopy());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001105 if (!setOptimizedPropertyFn) {
1106 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1107 return;
1108 }
John McCall71c758d2011-09-10 09:17:20 +00001109 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001110 else {
1111 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1112 if (!setPropertyFn) {
1113 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1114 return;
1115 }
1116 }
1117
John McCall71c758d2011-09-10 09:17:20 +00001118 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1119 // <is-atomic>, <is-copy>).
1120 llvm::Value *cmd =
1121 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
1122 llvm::Value *self =
1123 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1124 llvm::Value *ivarOffset =
1125 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1126 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
1127 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
1128
1129 CallArgList args;
1130 args.add(RValue::get(self), getContext().getObjCIdType());
1131 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001132 if (setOptimizedPropertyFn) {
1133 args.add(RValue::get(arg), getContext().getObjCIdType());
1134 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall0f3d0972012-07-07 06:41:13 +00001135 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1136 FunctionType::ExtInfo(),
1137 RequiredArgs::All),
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001138 setOptimizedPropertyFn, ReturnValueSlot(), args);
1139 } else {
1140 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1141 args.add(RValue::get(arg), getContext().getObjCIdType());
1142 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1143 getContext().BoolTy);
1144 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1145 getContext().BoolTy);
1146 // FIXME: We shouldn't need to get the function info here, the runtime
1147 // already should have computed it to build the function.
John McCall0f3d0972012-07-07 06:41:13 +00001148 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1149 FunctionType::ExtInfo(),
1150 RequiredArgs::All),
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001151 setPropertyFn, ReturnValueSlot(), args);
1152 }
1153
John McCall71c758d2011-09-10 09:17:20 +00001154 return;
1155 }
1156
John McCall1e1f4872011-09-13 03:34:09 +00001157 case PropertyImplStrategy::CopyStruct:
John McCall41bdde92011-09-12 23:06:44 +00001158 emitStructSetterCall(*this, setterMethod, ivar);
John McCall71c758d2011-09-10 09:17:20 +00001159 return;
John McCall1e1f4872011-09-13 03:34:09 +00001160
1161 case PropertyImplStrategy::Expression:
1162 break;
John McCall71c758d2011-09-10 09:17:20 +00001163 }
1164
1165 // Otherwise, fake up some ASTs and emit a normal assignment.
1166 ValueDecl *selfDecl = setterMethod->getSelfDecl();
John McCallf4b88a42012-03-10 09:33:50 +00001167 DeclRefExpr self(selfDecl, false, selfDecl->getType(),
1168 VK_LValue, SourceLocation());
John McCall71c758d2011-09-10 09:17:20 +00001169 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1170 selfDecl->getType(), CK_LValueToRValue, &self,
1171 VK_RValue);
1172 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
1173 SourceLocation(), &selfLoad, true, true);
1174
1175 ParmVarDecl *argDecl = *setterMethod->param_begin();
1176 QualType argType = argDecl->getType().getNonReferenceType();
John McCallf4b88a42012-03-10 09:33:50 +00001177 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
John McCall71c758d2011-09-10 09:17:20 +00001178 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1179 argType.getUnqualifiedType(), CK_LValueToRValue,
1180 &arg, VK_RValue);
1181
1182 // The property type can differ from the ivar type in some situations with
1183 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1184 // The following absurdity is just to ensure well-formed IR.
1185 CastKind argCK = CK_NoOp;
1186 if (ivarRef.getType()->isObjCObjectPointerType()) {
1187 if (argLoad.getType()->isObjCObjectPointerType())
1188 argCK = CK_BitCast;
1189 else if (argLoad.getType()->isBlockPointerType())
1190 argCK = CK_BlockPointerToObjCPointerCast;
1191 else
1192 argCK = CK_CPointerToObjCPointerCast;
1193 } else if (ivarRef.getType()->isBlockPointerType()) {
1194 if (argLoad.getType()->isBlockPointerType())
1195 argCK = CK_BitCast;
1196 else
1197 argCK = CK_AnyPointerToBlockPointerCast;
1198 } else if (ivarRef.getType()->isPointerType()) {
1199 argCK = CK_BitCast;
1200 }
1201 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1202 ivarRef.getType(), argCK, &argLoad,
1203 VK_RValue);
1204 Expr *finalArg = &argLoad;
1205 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1206 argLoad.getType()))
1207 finalArg = &argCast;
1208
1209
1210 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1211 ivarRef.getType(), VK_RValue, OK_Ordinary,
1212 SourceLocation());
1213 EmitStmt(&assign);
Fariborz Jahanian01cb3072011-04-06 16:05:26 +00001214}
1215
James Dennett2ee5ba32012-06-15 22:10:14 +00001216/// \brief Generate an Objective-C property setter function.
1217///
1218/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff489034c2009-01-10 22:55:25 +00001219/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001220void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1221 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +00001222 llvm::Constant *AtomicHelperFn =
Fariborz Jahanian20abee62012-01-10 00:37:01 +00001223 GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001224 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1225 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1226 assert(OMD && "Invalid call to generate setter (empty method)");
Eric Christopherea320472012-04-03 00:44:15 +00001227 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
Daniel Dunbar86957eb2008-09-24 06:32:09 +00001228
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001229 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001230
1231 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +00001232}
1233
John McCalle81ac692011-03-22 07:05:39 +00001234namespace {
John McCall9928c482011-07-12 16:41:08 +00001235 struct DestroyIvar : EHScopeStack::Cleanup {
1236 private:
1237 llvm::Value *addr;
John McCalle81ac692011-03-22 07:05:39 +00001238 const ObjCIvarDecl *ivar;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001239 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +00001240 bool useEHCleanupForArray;
1241 public:
1242 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1243 CodeGenFunction::Destroyer *destroyer,
1244 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001245 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +00001246 useEHCleanupForArray(useEHCleanupForArray) {}
John McCalle81ac692011-03-22 07:05:39 +00001247
John McCallad346f42011-07-12 20:27:29 +00001248 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +00001249 LValue lvalue
1250 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1251 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +00001252 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCalle81ac692011-03-22 07:05:39 +00001253 }
1254 };
1255}
1256
John McCall9928c482011-07-12 16:41:08 +00001257/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1258static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1259 llvm::Value *addr,
1260 QualType type) {
1261 llvm::Value *null = getNullForVariable(addr);
1262 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1263}
John McCallf85e1932011-06-15 23:02:42 +00001264
John McCalle81ac692011-03-22 07:05:39 +00001265static void emitCXXDestructMethod(CodeGenFunction &CGF,
1266 ObjCImplementationDecl *impl) {
1267 CodeGenFunction::RunCleanupsScope scope(CGF);
1268
1269 llvm::Value *self = CGF.LoadObjCSelf();
1270
Jordy Rosedb8264e2011-07-22 02:08:32 +00001271 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1272 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +00001273 ivar; ivar = ivar->getNextIvar()) {
1274 QualType type = ivar->getType();
1275
John McCalle81ac692011-03-22 07:05:39 +00001276 // Check whether the ivar is a destructible type.
John McCall9928c482011-07-12 16:41:08 +00001277 QualType::DestructionKind dtorKind = type.isDestructedType();
1278 if (!dtorKind) continue;
John McCalle81ac692011-03-22 07:05:39 +00001279
John McCall9928c482011-07-12 16:41:08 +00001280 CodeGenFunction::Destroyer *destroyer = 0;
John McCalle81ac692011-03-22 07:05:39 +00001281
John McCall9928c482011-07-12 16:41:08 +00001282 // Use a call to objc_storeStrong to destroy strong ivars, for the
1283 // general benefit of the tools.
1284 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001285 destroyer = destroyARCStrongWithStore;
John McCallf85e1932011-06-15 23:02:42 +00001286
John McCall9928c482011-07-12 16:41:08 +00001287 // Otherwise use the default for the destruction kind.
1288 } else {
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001289 destroyer = CGF.getDestroyer(dtorKind);
John McCalle81ac692011-03-22 07:05:39 +00001290 }
John McCall9928c482011-07-12 16:41:08 +00001291
1292 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1293
1294 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1295 cleanupKind & EHCleanup);
John McCalle81ac692011-03-22 07:05:39 +00001296 }
1297
1298 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1299}
1300
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001301void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1302 ObjCMethodDecl *MD,
1303 bool ctor) {
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001304 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Devang Patel8d3f8972011-05-19 23:37:41 +00001305 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
John McCalle81ac692011-03-22 07:05:39 +00001306
1307 // Emit .cxx_construct.
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001308 if (ctor) {
John McCallf85e1932011-06-15 23:02:42 +00001309 // Suppress the final autorelease in ARC.
1310 AutoreleaseResult = false;
1311
Chris Lattner5f9e2722011-07-23 10:55:15 +00001312 SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
John McCalle81ac692011-03-22 07:05:39 +00001313 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
1314 E = IMP->init_end(); B != E; ++B) {
1315 CXXCtorInitializer *IvarInit = (*B);
Francois Pichet00eb3f92010-12-04 09:14:42 +00001316 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001317 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian9b4d4fc2010-04-28 22:30:33 +00001318 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1319 LoadObjCSelf(), Ivar, 0);
John McCall7c2349b2011-08-25 20:40:09 +00001320 EmitAggExpr(IvarInit->getInit(),
1321 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001322 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001323 AggValueSlot::IsNotAliased));
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001324 }
1325 // constructor returns 'self'.
1326 CodeGenTypes &Types = CGM.getTypes();
1327 QualType IdTy(CGM.getContext().getObjCIdType());
1328 llvm::Value *SelfAsId =
1329 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1330 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCalle81ac692011-03-22 07:05:39 +00001331
1332 // Emit .cxx_destruct.
Chandler Carruthbc397cf2010-05-06 00:20:39 +00001333 } else {
John McCalle81ac692011-03-22 07:05:39 +00001334 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001335 }
1336 FinishFunction();
1337}
1338
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +00001339bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1340 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1341 it++; it++;
1342 const ABIArgInfo &AI = it->info;
1343 // FIXME. Is this sufficient check?
1344 return (AI.getKind() == ABIArgInfo::Indirect);
1345}
1346
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001347bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001348 if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001349 return false;
1350 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1351 return FDTTy->getDecl()->hasObjectMember();
1352 return false;
1353}
1354
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001355llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001356 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1357 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner41110242008-06-17 18:05:57 +00001358}
1359
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001360QualType CodeGenFunction::TypeOfSelfObject() {
1361 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1362 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff14108da2009-07-10 23:34:53 +00001363 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1364 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001365 return PTy->getPointeeType();
1366}
1367
Chris Lattner74391b42009-03-22 21:03:39 +00001368void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump1eb44332009-09-09 15:08:12 +00001369 llvm::Constant *EnumerationMutationFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001370 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +00001371
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001372 if (!EnumerationMutationFn) {
1373 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1374 return;
1375 }
1376
Devang Patelbcbd03a2011-01-19 01:36:36 +00001377 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00001378 if (DI)
1379 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001380
Devang Patel9d99f2d2011-06-13 23:15:32 +00001381 // The local variable comes into scope immediately.
1382 AutoVarEmission variable = AutoVarEmission::invalid();
1383 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1384 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1385
John McCalld88687f2011-01-07 01:49:06 +00001386 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump1eb44332009-09-09 15:08:12 +00001387
Anders Carlssonf484c312008-08-31 02:33:12 +00001388 // Fast enumeration state.
Douglas Gregor0815b572011-08-09 17:23:49 +00001389 QualType StateTy = CGM.getObjCFastEnumerationStateType();
Daniel Dunbar195337d2010-02-09 02:48:28 +00001390 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlsson1884eb02010-05-22 17:35:42 +00001391 EmitNullInitialization(StatePtr, StateTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001392
Anders Carlssonf484c312008-08-31 02:33:12 +00001393 // Number of elements in the items array.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001394 static const unsigned NumItems = 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001395
John McCalld88687f2011-01-07 01:49:06 +00001396 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramerad468862010-03-30 11:36:44 +00001397 IdentifierInfo *II[] = {
1398 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1399 &CGM.getContext().Idents.get("objects"),
1400 &CGM.getContext().Idents.get("count")
1401 };
1402 Selector FastEnumSel =
1403 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlssonf484c312008-08-31 02:33:12 +00001404
1405 QualType ItemsTy =
1406 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +00001407 llvm::APInt(32, NumItems),
Anders Carlssonf484c312008-08-31 02:33:12 +00001408 ArrayType::Normal, 0);
Daniel Dunbar195337d2010-02-09 02:48:28 +00001409 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001410
John McCall990567c2011-07-27 01:07:15 +00001411 // Emit the collection pointer. In ARC, we do a retain.
1412 llvm::Value *Collection;
David Blaikie4e4d0842012-03-11 07:00:24 +00001413 if (getLangOpts().ObjCAutoRefCount) {
John McCall990567c2011-07-27 01:07:15 +00001414 Collection = EmitARCRetainScalarExpr(S.getCollection());
1415
1416 // Enter a cleanup to do the release.
1417 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1418 } else {
1419 Collection = EmitScalarExpr(S.getCollection());
1420 }
Mike Stump1eb44332009-09-09 15:08:12 +00001421
John McCall4b302d32011-08-05 00:14:38 +00001422 // The 'continue' label needs to appear within the cleanup for the
1423 // collection object.
1424 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1425
John McCalld88687f2011-01-07 01:49:06 +00001426 // Send it our message:
Anders Carlssonf484c312008-08-31 02:33:12 +00001427 CallArgList Args;
John McCalld88687f2011-01-07 01:49:06 +00001428
1429 // The first argument is a temporary of the enumeration-state type.
Eli Friedman04c9a492011-05-02 17:57:46 +00001430 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001431
John McCalld88687f2011-01-07 01:49:06 +00001432 // The second argument is a temporary array with space for NumItems
1433 // pointers. We'll actually be loading elements from the array
1434 // pointer written into the control state; this buffer is so that
1435 // collections that *aren't* backed by arrays can still queue up
1436 // batches of elements.
Eli Friedman04c9a492011-05-02 17:57:46 +00001437 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001438
John McCalld88687f2011-01-07 01:49:06 +00001439 // The third argument is the capacity of that temporary array.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001440 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001441 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman04c9a492011-05-02 17:57:46 +00001442 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001443
John McCalld88687f2011-01-07 01:49:06 +00001444 // Start the enumeration.
Mike Stump1eb44332009-09-09 15:08:12 +00001445 RValue CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001446 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001447 getContext().UnsignedLongTy,
1448 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001449 Collection, Args);
Anders Carlssonf484c312008-08-31 02:33:12 +00001450
John McCalld88687f2011-01-07 01:49:06 +00001451 // The initial number of objects that were returned in the buffer.
1452 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump1eb44332009-09-09 15:08:12 +00001453
John McCalld88687f2011-01-07 01:49:06 +00001454 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1455 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump1eb44332009-09-09 15:08:12 +00001456
John McCalld88687f2011-01-07 01:49:06 +00001457 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlssonf484c312008-08-31 02:33:12 +00001458
John McCalld88687f2011-01-07 01:49:06 +00001459 // If the limit pointer was zero to begin with, the collection is
1460 // empty; skip all this.
1461 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1462 EmptyBB, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001463
John McCalld88687f2011-01-07 01:49:06 +00001464 // Otherwise, initialize the loop.
1465 EmitBlock(LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001466
John McCalld88687f2011-01-07 01:49:06 +00001467 // Save the initial mutations value. This is the value at an
1468 // address that was written into the state object by
1469 // countByEnumeratingWithState:objects:count:.
Mike Stump1eb44332009-09-09 15:08:12 +00001470 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001471 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001472 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001473 "mutationsptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001474
John McCalld88687f2011-01-07 01:49:06 +00001475 llvm::Value *initialMutations =
1476 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump1eb44332009-09-09 15:08:12 +00001477
John McCalld88687f2011-01-07 01:49:06 +00001478 // Start looping. This is the point we return to whenever we have a
1479 // fresh, non-empty batch of objects.
1480 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1481 EmitBlock(LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001482
John McCalld88687f2011-01-07 01:49:06 +00001483 // The current index into the buffer.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001484 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCalld88687f2011-01-07 01:49:06 +00001485 index->addIncoming(zero, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001486
John McCalld88687f2011-01-07 01:49:06 +00001487 // The current buffer size.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001488 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCalld88687f2011-01-07 01:49:06 +00001489 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001490
John McCalld88687f2011-01-07 01:49:06 +00001491 // Check whether the mutations value has changed from where it was
1492 // at start. StateMutationsPtr should actually be invariant between
1493 // refreshes.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001494 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCalld88687f2011-01-07 01:49:06 +00001495 llvm::Value *currentMutations
1496 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001497
John McCalld88687f2011-01-07 01:49:06 +00001498 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman361cf982011-03-02 22:39:34 +00001499 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump1eb44332009-09-09 15:08:12 +00001500
John McCalld88687f2011-01-07 01:49:06 +00001501 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1502 WasNotMutatedBB, WasMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001503
John McCalld88687f2011-01-07 01:49:06 +00001504 // If so, call the enumeration-mutation function.
1505 EmitBlock(WasMutatedBB);
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001506 llvm::Value *V =
Mike Stump1eb44332009-09-09 15:08:12 +00001507 Builder.CreateBitCast(Collection,
Benjamin Kramer578faa82011-09-27 21:06:10 +00001508 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar2b2105e2009-02-03 23:55:40 +00001509 CallArgList Args2;
Eli Friedman04c9a492011-05-02 17:57:46 +00001510 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stumpf5408fe2009-05-16 07:57:57 +00001511 // FIXME: We shouldn't need to get the function info here, the runtime already
1512 // should have computed it to build the function.
John McCall0f3d0972012-07-07 06:41:13 +00001513 EmitCall(CGM.getTypes().arrangeFreeFunctionCall(getContext().VoidTy, Args2,
1514 FunctionType::ExtInfo(),
1515 RequiredArgs::All),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001516 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump1eb44332009-09-09 15:08:12 +00001517
John McCalld88687f2011-01-07 01:49:06 +00001518 // Otherwise, or if the mutation function returns, just continue.
1519 EmitBlock(WasNotMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001520
John McCalld88687f2011-01-07 01:49:06 +00001521 // Initialize the element variable.
1522 RunCleanupsScope elementVariableScope(*this);
John McCall57b3b6a2011-02-22 07:16:58 +00001523 bool elementIsVariable;
John McCalld88687f2011-01-07 01:49:06 +00001524 LValue elementLValue;
1525 QualType elementType;
1526 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall57b3b6a2011-02-22 07:16:58 +00001527 // Initialize the variable, in case it's a __block variable or something.
1528 EmitAutoVarInit(variable);
John McCalld88687f2011-01-07 01:49:06 +00001529
John McCall57b3b6a2011-02-22 07:16:58 +00001530 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCallf4b88a42012-03-10 09:33:50 +00001531 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
John McCalld88687f2011-01-07 01:49:06 +00001532 VK_LValue, SourceLocation());
1533 elementLValue = EmitLValue(&tempDRE);
1534 elementType = D->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001535 elementIsVariable = true;
John McCall7acddac2011-06-17 06:42:21 +00001536
1537 if (D->isARCPseudoStrong())
1538 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCalld88687f2011-01-07 01:49:06 +00001539 } else {
1540 elementLValue = LValue(); // suppress warning
1541 elementType = cast<Expr>(S.getElement())->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001542 elementIsVariable = false;
John McCalld88687f2011-01-07 01:49:06 +00001543 }
Chris Lattner2acc6e32011-07-18 04:24:23 +00001544 llvm::Type *convertedElementType = ConvertType(elementType);
John McCalld88687f2011-01-07 01:49:06 +00001545
1546 // Fetch the buffer out of the enumeration state.
1547 // TODO: this pointer should actually be invariant between
1548 // refreshes, which would help us do certain loop optimizations.
Mike Stump1eb44332009-09-09 15:08:12 +00001549 llvm::Value *StateItemsPtr =
Anders Carlssonf484c312008-08-31 02:33:12 +00001550 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCalld88687f2011-01-07 01:49:06 +00001551 llvm::Value *EnumStateItems =
1552 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlssonf484c312008-08-31 02:33:12 +00001553
John McCalld88687f2011-01-07 01:49:06 +00001554 // Fetch the value at the current index from the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001555 llvm::Value *CurrentItemPtr =
John McCalld88687f2011-01-07 01:49:06 +00001556 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1557 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001558
John McCalld88687f2011-01-07 01:49:06 +00001559 // Cast that value to the right type.
1560 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1561 "currentitem");
Mike Stump1eb44332009-09-09 15:08:12 +00001562
John McCalld88687f2011-01-07 01:49:06 +00001563 // Make sure we have an l-value. Yes, this gets evaluated every
1564 // time through the loop.
John McCall7acddac2011-06-17 06:42:21 +00001565 if (!elementIsVariable) {
John McCalld88687f2011-01-07 01:49:06 +00001566 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001567 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCall7acddac2011-06-17 06:42:21 +00001568 } else {
1569 EmitScalarInit(CurrentItem, elementLValue);
1570 }
Mike Stump1eb44332009-09-09 15:08:12 +00001571
John McCall57b3b6a2011-02-22 07:16:58 +00001572 // If we do have an element variable, this assignment is the end of
1573 // its initialization.
1574 if (elementIsVariable)
1575 EmitAutoVarCleanups(variable);
1576
John McCalld88687f2011-01-07 01:49:06 +00001577 // Perform the loop body, setting up break and continue labels.
Anders Carlssone4b6d342009-02-10 05:52:02 +00001578 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCalld88687f2011-01-07 01:49:06 +00001579 {
1580 RunCleanupsScope Scope(*this);
1581 EmitStmt(S.getBody());
1582 }
Anders Carlssonf484c312008-08-31 02:33:12 +00001583 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001584
John McCalld88687f2011-01-07 01:49:06 +00001585 // Destroy the element variable now.
1586 elementVariableScope.ForceCleanup();
1587
1588 // Check whether there are more elements.
John McCallff8e1152010-07-23 21:56:41 +00001589 EmitBlock(AfterBody.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001590
John McCalld88687f2011-01-07 01:49:06 +00001591 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanianf0906c42009-01-06 18:56:31 +00001592
John McCalld88687f2011-01-07 01:49:06 +00001593 // First we check in the local buffer.
1594 llvm::Value *indexPlusOne
1595 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlssonf484c312008-08-31 02:33:12 +00001596
John McCalld88687f2011-01-07 01:49:06 +00001597 // If we haven't overrun the buffer yet, we can continue.
1598 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1599 LoopBodyBB, FetchMoreBB);
1600
1601 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1602 count->addIncoming(count, AfterBody.getBlock());
1603
1604 // Otherwise, we have to fetch more elements.
1605 EmitBlock(FetchMoreBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001606
1607 CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001608 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001609 getContext().UnsignedLongTy,
Mike Stump1eb44332009-09-09 15:08:12 +00001610 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001611 Collection, Args);
Mike Stump1eb44332009-09-09 15:08:12 +00001612
John McCalld88687f2011-01-07 01:49:06 +00001613 // If we got a zero count, we're done.
1614 llvm::Value *refetchCount = CountRV.getScalarVal();
1615
1616 // (note that the message send might split FetchMoreBB)
1617 index->addIncoming(zero, Builder.GetInsertBlock());
1618 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1619
1620 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1621 EmptyBB, LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001622
Anders Carlssonf484c312008-08-31 02:33:12 +00001623 // No more elements.
John McCalld88687f2011-01-07 01:49:06 +00001624 EmitBlock(EmptyBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001625
John McCall57b3b6a2011-02-22 07:16:58 +00001626 if (!elementIsVariable) {
Anders Carlssonf484c312008-08-31 02:33:12 +00001627 // If the element was not a declaration, set it to be null.
1628
John McCalld88687f2011-01-07 01:49:06 +00001629 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1630 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001631 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlssonf484c312008-08-31 02:33:12 +00001632 }
1633
Eric Christopher73fb3502011-10-13 21:45:18 +00001634 if (DI)
1635 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001636
John McCall990567c2011-07-27 01:07:15 +00001637 // Leave the cleanup we entered in ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00001638 if (getLangOpts().ObjCAutoRefCount)
John McCall990567c2011-07-27 01:07:15 +00001639 PopCleanupBlock();
1640
John McCallff8e1152010-07-23 21:56:41 +00001641 EmitBlock(LoopEnd.getBlock());
Anders Carlsson3d8400d2008-08-30 19:51:14 +00001642}
1643
Mike Stump1eb44332009-09-09 15:08:12 +00001644void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001645 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001646}
1647
Mike Stump1eb44332009-09-09 15:08:12 +00001648void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001649 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1650}
1651
Chris Lattner10cac6f2008-11-15 21:26:17 +00001652void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump1eb44332009-09-09 15:08:12 +00001653 const ObjCAtSynchronizedStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001654 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +00001655}
1656
John McCall33e56f32011-09-10 06:18:15 +00001657/// Produce the code for a CK_ARCProduceObject. Just does a
John McCallf85e1932011-06-15 23:02:42 +00001658/// primitive retain.
1659llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1660 llvm::Value *value) {
1661 return EmitARCRetain(type, value);
1662}
1663
1664namespace {
1665 struct CallObjCRelease : EHScopeStack::Cleanup {
John McCallbddfd872011-08-03 22:24:24 +00001666 CallObjCRelease(llvm::Value *object) : object(object) {}
1667 llvm::Value *object;
John McCallf85e1932011-06-15 23:02:42 +00001668
John McCallad346f42011-07-12 20:27:29 +00001669 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001670 CGF.EmitARCRelease(object, /*precise*/ true);
John McCallf85e1932011-06-15 23:02:42 +00001671 }
1672 };
1673}
1674
John McCall33e56f32011-09-10 06:18:15 +00001675/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCallf85e1932011-06-15 23:02:42 +00001676/// release at the end of the full-expression.
1677llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1678 llvm::Value *object) {
1679 // If we're in a conditional branch, we need to make the cleanup
John McCallbddfd872011-08-03 22:24:24 +00001680 // conditional.
1681 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCallf85e1932011-06-15 23:02:42 +00001682 return object;
1683}
1684
1685llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1686 llvm::Value *value) {
1687 return EmitARCRetainAutorelease(type, value);
1688}
1689
1690
1691static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001692 llvm::FunctionType *type,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001693 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001694 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1695
John McCall260611a2012-06-20 06:18:46 +00001696 // If the target runtime doesn't naturally support ARC, emit weak
1697 // references to the runtime support library. We don't really
1698 // permit this to fail, but we need a particular relocation style.
Fariborz Jahanianc343dd82012-08-07 21:30:31 +00001699 if (llvm::Function *f = dyn_cast<llvm::Function>(fn)) {
1700 if (!CGM.getLangOpts().ObjCRuntime.hasARC())
John McCallf85e1932011-06-15 23:02:42 +00001701 f->setLinkage(llvm::Function::ExternalWeakLinkage);
Fariborz Jahanianc343dd82012-08-07 21:30:31 +00001702 // set nonlazybind attribute for these APIs for performance.
1703 if (fnName == "objc_retain" || fnName == "objc_release")
1704 f->addFnAttr(llvm::Attribute::NonLazyBind);
1705 }
John McCallf85e1932011-06-15 23:02:42 +00001706
1707 return fn;
1708}
1709
1710/// Perform an operation having the signature
1711/// i8* (i8*)
1712/// where a null input causes a no-op and returns null.
1713static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1714 llvm::Value *value,
1715 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001716 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001717 if (isa<llvm::ConstantPointerNull>(value)) return value;
1718
1719 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001720 std::vector<llvm::Type*> args(1, CGF.Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001721 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001722 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1723 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1724 }
1725
1726 // Cast the argument to 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001727 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001728 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1729
1730 // Call the function.
1731 llvm::CallInst *call = CGF.Builder.CreateCall(fn, value);
1732 call->setDoesNotThrow();
1733
1734 // Cast the result back to the original type.
1735 return CGF.Builder.CreateBitCast(call, origType);
1736}
1737
1738/// Perform an operation having the following signature:
1739/// i8* (i8**)
1740static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1741 llvm::Value *addr,
1742 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001743 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001744 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001745 std::vector<llvm::Type*> args(1, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001746 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001747 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1748 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1749 }
1750
1751 // Cast the argument to 'id*'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001752 llvm::Type *origType = addr->getType();
John McCallf85e1932011-06-15 23:02:42 +00001753 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1754
1755 // Call the function.
1756 llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr);
1757 call->setDoesNotThrow();
1758
1759 // Cast the result back to a dereference of the original type.
1760 llvm::Value *result = call;
1761 if (origType != CGF.Int8PtrPtrTy)
1762 result = CGF.Builder.CreateBitCast(result,
1763 cast<llvm::PointerType>(origType)->getElementType());
1764
1765 return result;
1766}
1767
1768/// Perform an operation having the following signature:
1769/// i8* (i8**, i8*)
1770static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1771 llvm::Value *addr,
1772 llvm::Value *value,
1773 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001774 StringRef fnName,
John McCallf85e1932011-06-15 23:02:42 +00001775 bool ignored) {
1776 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1777 == value->getType());
1778
1779 if (!fn) {
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00001780 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
John McCallf85e1932011-06-15 23:02:42 +00001781
Chris Lattner2acc6e32011-07-18 04:24:23 +00001782 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001783 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1784 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1785 }
1786
Chris Lattner2acc6e32011-07-18 04:24:23 +00001787 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001788
1789 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1790 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1791
1792 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value);
1793 result->setDoesNotThrow();
1794
1795 if (ignored) return 0;
1796
1797 return CGF.Builder.CreateBitCast(result, origType);
1798}
1799
1800/// Perform an operation having the following signature:
1801/// void (i8**, i8**)
1802static void emitARCCopyOperation(CodeGenFunction &CGF,
1803 llvm::Value *dst,
1804 llvm::Value *src,
1805 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001806 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001807 assert(dst->getType() == src->getType());
1808
1809 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001810 std::vector<llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001811 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001812 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1813 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1814 }
1815
1816 dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy);
1817 src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy);
1818
1819 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src);
1820 result->setDoesNotThrow();
1821}
1822
1823/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett9d96e9c2012-06-22 05:41:30 +00001824/// call i8* \@objc_retain(i8* %value)
1825/// call i8* \@objc_retainBlock(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001826llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1827 if (type->isBlockPointerType())
John McCall348f16f2011-10-04 06:23:45 +00001828 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallf85e1932011-06-15 23:02:42 +00001829 else
1830 return EmitARCRetainNonBlock(value);
1831}
1832
1833/// Retain the given object, with normal retain semantics.
James Dennett9d96e9c2012-06-22 05:41:30 +00001834/// call i8* \@objc_retain(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001835llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1836 return emitARCValueOperation(*this, value,
1837 CGM.getARCEntrypoints().objc_retain,
1838 "objc_retain");
1839}
1840
1841/// Retain the given block, with _Block_copy semantics.
James Dennett9d96e9c2012-06-22 05:41:30 +00001842/// call i8* \@objc_retainBlock(i8* %value)
John McCall348f16f2011-10-04 06:23:45 +00001843///
1844/// \param mandatory - If false, emit the call with metadata
1845/// indicating that it's okay for the optimizer to eliminate this call
1846/// if it can prove that the block never escapes except down the stack.
1847llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1848 bool mandatory) {
1849 llvm::Value *result
1850 = emitARCValueOperation(*this, value,
1851 CGM.getARCEntrypoints().objc_retainBlock,
1852 "objc_retainBlock");
1853
1854 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1855 // tell the optimizer that it doesn't need to do this copy if the
1856 // block doesn't escape, where being passed as an argument doesn't
1857 // count as escaping.
1858 if (!mandatory && isa<llvm::Instruction>(result)) {
1859 llvm::CallInst *call
1860 = cast<llvm::CallInst>(result->stripPointerCasts());
1861 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
1862
1863 SmallVector<llvm::Value*,1> args;
1864 call->setMetadata("clang.arc.copy_on_escape",
1865 llvm::MDNode::get(Builder.getContext(), args));
1866 }
1867
1868 return result;
John McCallf85e1932011-06-15 23:02:42 +00001869}
1870
1871/// Retain the given object which is the result of a function call.
James Dennett9d96e9c2012-06-22 05:41:30 +00001872/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001873///
1874/// Yes, this function name is one character away from a different
1875/// call with completely different semantics.
1876llvm::Value *
1877CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1878 // Fetch the void(void) inline asm which marks that we're going to
1879 // retain the autoreleased return value.
1880 llvm::InlineAsm *&marker
1881 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1882 if (!marker) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001883 StringRef assembly
John McCallf85e1932011-06-15 23:02:42 +00001884 = CGM.getTargetCodeGenInfo()
1885 .getARCRetainAutoreleasedReturnValueMarker();
1886
1887 // If we have an empty assembly string, there's nothing to do.
1888 if (assembly.empty()) {
1889
1890 // Otherwise, at -O0, build an inline asm that we're going to call
1891 // in a moment.
1892 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1893 llvm::FunctionType *type =
Chris Lattner8b418682012-02-07 00:39:47 +00001894 llvm::FunctionType::get(VoidTy, /*variadic*/false);
John McCallf85e1932011-06-15 23:02:42 +00001895
1896 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1897
1898 // If we're at -O1 and above, we don't want to litter the code
1899 // with this marker yet, so leave a breadcrumb for the ARC
1900 // optimizer to pick up.
1901 } else {
1902 llvm::NamedMDNode *metadata =
1903 CGM.getModule().getOrInsertNamedMetadata(
1904 "clang.arc.retainAutoreleasedReturnValueMarker");
1905 assert(metadata->getNumOperands() <= 1);
1906 if (metadata->getNumOperands() == 0) {
1907 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
Jay Foadda549e82011-07-29 13:56:53 +00001908 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
John McCallf85e1932011-06-15 23:02:42 +00001909 }
1910 }
1911 }
1912
1913 // Call the marker asm if we made one, which we do only at -O0.
1914 if (marker) Builder.CreateCall(marker);
1915
1916 return emitARCValueOperation(*this, value,
1917 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1918 "objc_retainAutoreleasedReturnValue");
1919}
1920
1921/// Release the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00001922/// call void \@objc_release(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001923void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) {
1924 if (isa<llvm::ConstantPointerNull>(value)) return;
1925
1926 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1927 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001928 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001929 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001930 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1931 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1932 }
1933
1934 // Cast the argument to 'id'.
1935 value = Builder.CreateBitCast(value, Int8PtrTy);
1936
1937 // Call objc_release.
1938 llvm::CallInst *call = Builder.CreateCall(fn, value);
1939 call->setDoesNotThrow();
1940
1941 if (!precise) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001942 SmallVector<llvm::Value*,1> args;
John McCallf85e1932011-06-15 23:02:42 +00001943 call->setMetadata("clang.imprecise_release",
1944 llvm::MDNode::get(Builder.getContext(), args));
1945 }
1946}
1947
1948/// Store into a strong object. Always calls this:
James Dennett9d96e9c2012-06-22 05:41:30 +00001949/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001950llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
1951 llvm::Value *value,
1952 bool ignored) {
1953 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1954 == value->getType());
1955
1956 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
1957 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001958 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2acc6e32011-07-18 04:24:23 +00001959 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001960 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
1961 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
1962 }
1963
1964 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1965 llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy);
1966
1967 Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow();
1968
1969 if (ignored) return 0;
1970 return value;
1971}
1972
1973/// Store into a strong object. Sometimes calls this:
James Dennett9d96e9c2012-06-22 05:41:30 +00001974/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001975/// Other times, breaks it down into components.
John McCall545d9962011-06-25 02:11:03 +00001976llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCallf85e1932011-06-15 23:02:42 +00001977 llvm::Value *newValue,
1978 bool ignored) {
John McCall545d9962011-06-25 02:11:03 +00001979 QualType type = dst.getType();
John McCallf85e1932011-06-15 23:02:42 +00001980 bool isBlock = type->isBlockPointerType();
1981
1982 // Use a store barrier at -O0 unless this is a block type or the
1983 // lvalue is inadequately aligned.
1984 if (shouldUseFusedARCCalls() &&
1985 !isBlock &&
Eli Friedman6da2c712011-12-03 04:14:32 +00001986 (dst.getAlignment().isZero() ||
1987 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCallf85e1932011-06-15 23:02:42 +00001988 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
1989 }
1990
1991 // Otherwise, split it out.
1992
1993 // Retain the new value.
1994 newValue = EmitARCRetain(type, newValue);
1995
1996 // Read the old value.
John McCall545d9962011-06-25 02:11:03 +00001997 llvm::Value *oldValue = EmitLoadOfScalar(dst);
John McCallf85e1932011-06-15 23:02:42 +00001998
1999 // Store. We do this before the release so that any deallocs won't
2000 // see the old value.
John McCall545d9962011-06-25 02:11:03 +00002001 EmitStoreOfScalar(newValue, dst);
John McCallf85e1932011-06-15 23:02:42 +00002002
2003 // Finally, release the old value.
2004 EmitARCRelease(oldValue, /*precise*/ false);
2005
2006 return newValue;
2007}
2008
2009/// Autorelease the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002010/// call i8* \@objc_autorelease(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002011llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2012 return emitARCValueOperation(*this, value,
2013 CGM.getARCEntrypoints().objc_autorelease,
2014 "objc_autorelease");
2015}
2016
2017/// Autorelease the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002018/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002019llvm::Value *
2020CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2021 return emitARCValueOperation(*this, value,
2022 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
2023 "objc_autoreleaseReturnValue");
2024}
2025
2026/// Do a fused retain/autorelease of the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002027/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002028llvm::Value *
2029CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2030 return emitARCValueOperation(*this, value,
2031 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
2032 "objc_retainAutoreleaseReturnValue");
2033}
2034
2035/// Do a fused retain/autorelease of the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002036/// call i8* \@objc_retainAutorelease(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002037/// or
James Dennett9d96e9c2012-06-22 05:41:30 +00002038/// %retain = call i8* \@objc_retainBlock(i8* %value)
2039/// call i8* \@objc_autorelease(i8* %retain)
John McCallf85e1932011-06-15 23:02:42 +00002040llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2041 llvm::Value *value) {
2042 if (!type->isBlockPointerType())
2043 return EmitARCRetainAutoreleaseNonBlock(value);
2044
2045 if (isa<llvm::ConstantPointerNull>(value)) return value;
2046
Chris Lattner2acc6e32011-07-18 04:24:23 +00002047 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00002048 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCall348f16f2011-10-04 06:23:45 +00002049 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCallf85e1932011-06-15 23:02:42 +00002050 value = EmitARCAutorelease(value);
2051 return Builder.CreateBitCast(value, origType);
2052}
2053
2054/// Do a fused retain/autorelease of the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002055/// call i8* \@objc_retainAutorelease(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002056llvm::Value *
2057CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2058 return emitARCValueOperation(*this, value,
2059 CGM.getARCEntrypoints().objc_retainAutorelease,
2060 "objc_retainAutorelease");
2061}
2062
James Dennett9d96e9c2012-06-22 05:41:30 +00002063/// i8* \@objc_loadWeak(i8** %addr)
John McCallf85e1932011-06-15 23:02:42 +00002064/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2065llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
2066 return emitARCLoadOperation(*this, addr,
2067 CGM.getARCEntrypoints().objc_loadWeak,
2068 "objc_loadWeak");
2069}
2070
James Dennett9d96e9c2012-06-22 05:41:30 +00002071/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCallf85e1932011-06-15 23:02:42 +00002072llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
2073 return emitARCLoadOperation(*this, addr,
2074 CGM.getARCEntrypoints().objc_loadWeakRetained,
2075 "objc_loadWeakRetained");
2076}
2077
James Dennett9d96e9c2012-06-22 05:41:30 +00002078/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002079/// Returns %value.
2080llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
2081 llvm::Value *value,
2082 bool ignored) {
2083 return emitARCStoreOperation(*this, addr, value,
2084 CGM.getARCEntrypoints().objc_storeWeak,
2085 "objc_storeWeak", ignored);
2086}
2087
James Dennett9d96e9c2012-06-22 05:41:30 +00002088/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002089/// Returns %value. %addr is known to not have a current weak entry.
2090/// Essentially equivalent to:
2091/// *addr = nil; objc_storeWeak(addr, value);
2092void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
2093 // If we're initializing to null, just write null to memory; no need
2094 // to get the runtime involved. But don't do this if optimization
2095 // is enabled, because accounting for this would make the optimizer
2096 // much more complicated.
2097 if (isa<llvm::ConstantPointerNull>(value) &&
2098 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2099 Builder.CreateStore(value, addr);
2100 return;
2101 }
2102
2103 emitARCStoreOperation(*this, addr, value,
2104 CGM.getARCEntrypoints().objc_initWeak,
2105 "objc_initWeak", /*ignored*/ true);
2106}
2107
James Dennett9d96e9c2012-06-22 05:41:30 +00002108/// void \@objc_destroyWeak(i8** %addr)
John McCallf85e1932011-06-15 23:02:42 +00002109/// Essentially objc_storeWeak(addr, nil).
2110void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
2111 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
2112 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002113 std::vector<llvm::Type*> args(1, Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00002114 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00002115 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
2116 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
2117 }
2118
2119 // Cast the argument to 'id*'.
2120 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2121
2122 llvm::CallInst *call = Builder.CreateCall(fn, addr);
2123 call->setDoesNotThrow();
2124}
2125
James Dennett9d96e9c2012-06-22 05:41:30 +00002126/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCallf85e1932011-06-15 23:02:42 +00002127/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2128/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
2129void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
2130 emitARCCopyOperation(*this, dst, src,
2131 CGM.getARCEntrypoints().objc_moveWeak,
2132 "objc_moveWeak");
2133}
2134
James Dennett9d96e9c2012-06-22 05:41:30 +00002135/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCallf85e1932011-06-15 23:02:42 +00002136/// Disregards the current value in %dest. Essentially
2137/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
2138void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
2139 emitARCCopyOperation(*this, dst, src,
2140 CGM.getARCEntrypoints().objc_copyWeak,
2141 "objc_copyWeak");
2142}
2143
2144/// Produce the code to do a objc_autoreleasepool_push.
James Dennett9d96e9c2012-06-22 05:41:30 +00002145/// call i8* \@objc_autoreleasePoolPush(void)
John McCallf85e1932011-06-15 23:02:42 +00002146llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2147 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
2148 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002149 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00002150 llvm::FunctionType::get(Int8PtrTy, false);
2151 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
2152 }
2153
2154 llvm::CallInst *call = Builder.CreateCall(fn);
2155 call->setDoesNotThrow();
2156
2157 return call;
2158}
2159
2160/// Produce the code to do a primitive release.
James Dennett9d96e9c2012-06-22 05:41:30 +00002161/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCallf85e1932011-06-15 23:02:42 +00002162void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2163 assert(value->getType() == Int8PtrTy);
2164
2165 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
2166 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002167 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00002168 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00002169 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
2170
2171 // We don't want to use a weak import here; instead we should not
2172 // fall into this path.
2173 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
2174 }
2175
2176 llvm::CallInst *call = Builder.CreateCall(fn, value);
2177 call->setDoesNotThrow();
2178}
2179
2180/// Produce the code to do an MRR version objc_autoreleasepool_push.
2181/// Which is: [[NSAutoreleasePool alloc] init];
2182/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2183/// init is declared as: - (id) init; in its NSObject super class.
2184///
2185llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2186 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2187 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder);
2188 // [NSAutoreleasePool alloc]
2189 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2190 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2191 CallArgList Args;
2192 RValue AllocRV =
2193 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2194 getContext().getObjCIdType(),
2195 AllocSel, Receiver, Args);
2196
2197 // [Receiver init]
2198 Receiver = AllocRV.getScalarVal();
2199 II = &CGM.getContext().Idents.get("init");
2200 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2201 RValue InitRV =
2202 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2203 getContext().getObjCIdType(),
2204 InitSel, Receiver, Args);
2205 return InitRV.getScalarVal();
2206}
2207
2208/// Produce the code to do a primitive release.
2209/// [tmp drain];
2210void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2211 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2212 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2213 CallArgList Args;
2214 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2215 getContext().VoidTy, DrainSel, Arg, Args);
2216}
2217
John McCallbdc4d802011-07-09 01:37:26 +00002218void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2219 llvm::Value *addr,
2220 QualType type) {
2221 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2222 CGF.EmitARCRelease(ptr, /*precise*/ true);
2223}
2224
2225void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2226 llvm::Value *addr,
2227 QualType type) {
2228 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2229 CGF.EmitARCRelease(ptr, /*precise*/ false);
2230}
2231
2232void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2233 llvm::Value *addr,
2234 QualType type) {
2235 CGF.EmitARCDestroyWeak(addr);
2236}
2237
John McCallf85e1932011-06-15 23:02:42 +00002238namespace {
John McCallf85e1932011-06-15 23:02:42 +00002239 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2240 llvm::Value *Token;
2241
2242 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2243
John McCallad346f42011-07-12 20:27:29 +00002244 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002245 CGF.EmitObjCAutoreleasePoolPop(Token);
2246 }
2247 };
2248 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2249 llvm::Value *Token;
2250
2251 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2252
John McCallad346f42011-07-12 20:27:29 +00002253 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002254 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2255 }
2256 };
2257}
2258
2259void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002260 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +00002261 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2262 else
2263 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2264}
2265
John McCallf85e1932011-06-15 23:02:42 +00002266static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2267 LValue lvalue,
2268 QualType type) {
2269 switch (type.getObjCLifetime()) {
2270 case Qualifiers::OCL_None:
2271 case Qualifiers::OCL_ExplicitNone:
2272 case Qualifiers::OCL_Strong:
2273 case Qualifiers::OCL_Autoreleasing:
John McCall545d9962011-06-25 02:11:03 +00002274 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(),
John McCallf85e1932011-06-15 23:02:42 +00002275 false);
2276
2277 case Qualifiers::OCL_Weak:
2278 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2279 true);
2280 }
2281
2282 llvm_unreachable("impossible lifetime!");
John McCallf85e1932011-06-15 23:02:42 +00002283}
2284
2285static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2286 const Expr *e) {
2287 e = e->IgnoreParens();
2288 QualType type = e->getType();
2289
John McCall21480112011-08-30 00:57:29 +00002290 // If we're loading retained from a __strong xvalue, we can avoid
2291 // an extra retain/release pair by zeroing out the source of this
2292 // "move" operation.
2293 if (e->isXValue() &&
2294 !type.isConstQualified() &&
2295 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2296 // Emit the lvalue.
2297 LValue lv = CGF.EmitLValue(e);
2298
2299 // Load the object pointer.
2300 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal();
2301
2302 // Set the source pointer to NULL.
2303 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2304
2305 return TryEmitResult(result, true);
2306 }
2307
John McCallf85e1932011-06-15 23:02:42 +00002308 // As a very special optimization, in ARC++, if the l-value is the
2309 // result of a non-volatile assignment, do a simple retain of the
2310 // result of the call to objc_storeWeak instead of reloading.
David Blaikie4e4d0842012-03-11 07:00:24 +00002311 if (CGF.getLangOpts().CPlusPlus &&
John McCallf85e1932011-06-15 23:02:42 +00002312 !type.isVolatileQualified() &&
2313 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2314 isa<BinaryOperator>(e) &&
2315 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2316 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2317
2318 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2319}
2320
2321static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2322 llvm::Value *value);
2323
2324/// Given that the given expression is some sort of call (which does
2325/// not return retained), emit a retain following it.
2326static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2327 llvm::Value *value = CGF.EmitScalarExpr(e);
2328 return emitARCRetainAfterCall(CGF, value);
2329}
2330
2331static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2332 llvm::Value *value) {
2333 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2334 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2335
2336 // Place the retain immediately following the call.
2337 CGF.Builder.SetInsertPoint(call->getParent(),
2338 ++llvm::BasicBlock::iterator(call));
2339 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2340
2341 CGF.Builder.restoreIP(ip);
2342 return value;
2343 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2344 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2345
2346 // Place the retain at the beginning of the normal destination block.
2347 llvm::BasicBlock *BB = invoke->getNormalDest();
2348 CGF.Builder.SetInsertPoint(BB, BB->begin());
2349 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2350
2351 CGF.Builder.restoreIP(ip);
2352 return value;
2353
2354 // Bitcasts can arise because of related-result returns. Rewrite
2355 // the operand.
2356 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2357 llvm::Value *operand = bitcast->getOperand(0);
2358 operand = emitARCRetainAfterCall(CGF, operand);
2359 bitcast->setOperand(0, operand);
2360 return bitcast;
2361
2362 // Generic fall-back case.
2363 } else {
2364 // Retain using the non-block variant: we never need to do a copy
2365 // of a block that's been returned to us.
2366 return CGF.EmitARCRetainNonBlock(value);
2367 }
2368}
2369
John McCalldc05b112011-09-10 01:16:55 +00002370/// Determine whether it might be important to emit a separate
2371/// objc_retain_block on the result of the given expression, or
2372/// whether it's okay to just emit it in a +1 context.
2373static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2374 assert(e->getType()->isBlockPointerType());
2375 e = e->IgnoreParens();
2376
2377 // For future goodness, emit block expressions directly in +1
2378 // contexts if we can.
2379 if (isa<BlockExpr>(e))
2380 return false;
2381
2382 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2383 switch (cast->getCastKind()) {
2384 // Emitting these operations in +1 contexts is goodness.
2385 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00002386 case CK_ARCReclaimReturnedObject:
2387 case CK_ARCConsumeObject:
2388 case CK_ARCProduceObject:
John McCalldc05b112011-09-10 01:16:55 +00002389 return false;
2390
2391 // These operations preserve a block type.
2392 case CK_NoOp:
2393 case CK_BitCast:
2394 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2395
2396 // These operations are known to be bad (or haven't been considered).
2397 case CK_AnyPointerToBlockPointerCast:
2398 default:
2399 return true;
2400 }
2401 }
2402
2403 return true;
2404}
2405
John McCall4b9c2d22011-11-06 09:01:30 +00002406/// Try to emit a PseudoObjectExpr at +1.
2407///
2408/// This massively duplicates emitPseudoObjectRValue.
2409static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
2410 const PseudoObjectExpr *E) {
2411 llvm::SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
2412
2413 // Find the result expression.
2414 const Expr *resultExpr = E->getResultExpr();
2415 assert(resultExpr);
2416 TryEmitResult result;
2417
2418 for (PseudoObjectExpr::const_semantics_iterator
2419 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2420 const Expr *semantic = *i;
2421
2422 // If this semantic expression is an opaque value, bind it
2423 // to the result of its source expression.
2424 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2425 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2426 OVMA opaqueData;
2427
2428 // If this semantic is the result of the pseudo-object
2429 // expression, try to evaluate the source as +1.
2430 if (ov == resultExpr) {
2431 assert(!OVMA::shouldBindAsLValue(ov));
2432 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
2433 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
2434
2435 // Otherwise, just bind it.
2436 } else {
2437 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2438 }
2439 opaques.push_back(opaqueData);
2440
2441 // Otherwise, if the expression is the result, evaluate it
2442 // and remember the result.
2443 } else if (semantic == resultExpr) {
2444 result = tryEmitARCRetainScalarExpr(CGF, semantic);
2445
2446 // Otherwise, evaluate the expression in an ignored context.
2447 } else {
2448 CGF.EmitIgnoredExpr(semantic);
2449 }
2450 }
2451
2452 // Unbind all the opaques now.
2453 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2454 opaques[i].unbind(CGF);
2455
2456 return result;
2457}
2458
John McCallf85e1932011-06-15 23:02:42 +00002459static TryEmitResult
2460tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCall990567c2011-07-27 01:07:15 +00002461 // Look through cleanups.
2462 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
John McCall1a343eb2011-11-10 08:15:53 +00002463 CGF.enterFullExpression(cleanups);
John McCall990567c2011-07-27 01:07:15 +00002464 CodeGenFunction::RunCleanupsScope scope(CGF);
2465 return tryEmitARCRetainScalarExpr(CGF, cleanups->getSubExpr());
2466 }
2467
John McCallf85e1932011-06-15 23:02:42 +00002468 // The desired result type, if it differs from the type of the
2469 // ultimate opaque expression.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002470 llvm::Type *resultType = 0;
John McCallf85e1932011-06-15 23:02:42 +00002471
2472 while (true) {
2473 e = e->IgnoreParens();
2474
2475 // There's a break at the end of this if-chain; anything
2476 // that wants to keep looping has to explicitly continue.
2477 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2478 switch (ce->getCastKind()) {
2479 // No-op casts don't change the type, so we just ignore them.
2480 case CK_NoOp:
2481 e = ce->getSubExpr();
2482 continue;
2483
2484 case CK_LValueToRValue: {
2485 TryEmitResult loadResult
2486 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2487 if (resultType) {
2488 llvm::Value *value = loadResult.getPointer();
2489 value = CGF.Builder.CreateBitCast(value, resultType);
2490 loadResult.setPointer(value);
2491 }
2492 return loadResult;
2493 }
2494
2495 // These casts can change the type, so remember that and
2496 // soldier on. We only need to remember the outermost such
2497 // cast, though.
John McCall1d9b3b22011-09-09 05:25:32 +00002498 case CK_CPointerToObjCPointerCast:
2499 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00002500 case CK_AnyPointerToBlockPointerCast:
2501 case CK_BitCast:
2502 if (!resultType)
2503 resultType = CGF.ConvertType(ce->getType());
2504 e = ce->getSubExpr();
2505 assert(e->getType()->hasPointerRepresentation());
2506 continue;
2507
2508 // For consumptions, just emit the subexpression and thus elide
2509 // the retain/release pair.
John McCall33e56f32011-09-10 06:18:15 +00002510 case CK_ARCConsumeObject: {
John McCallf85e1932011-06-15 23:02:42 +00002511 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2512 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2513 return TryEmitResult(result, true);
2514 }
2515
John McCalldc05b112011-09-10 01:16:55 +00002516 // Block extends are net +0. Naively, we could just recurse on
2517 // the subexpression, but actually we need to ensure that the
2518 // value is copied as a block, so there's a little filter here.
John McCall33e56f32011-09-10 06:18:15 +00002519 case CK_ARCExtendBlockObject: {
John McCalldc05b112011-09-10 01:16:55 +00002520 llvm::Value *result; // will be a +0 value
2521
2522 // If we can't safely assume the sub-expression will produce a
2523 // block-copied value, emit the sub-expression at +0.
2524 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2525 result = CGF.EmitScalarExpr(ce->getSubExpr());
2526
2527 // Otherwise, try to emit the sub-expression at +1 recursively.
2528 } else {
2529 TryEmitResult subresult
2530 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2531 result = subresult.getPointer();
2532
2533 // If that produced a retained value, just use that,
2534 // possibly casting down.
2535 if (subresult.getInt()) {
2536 if (resultType)
2537 result = CGF.Builder.CreateBitCast(result, resultType);
2538 return TryEmitResult(result, true);
2539 }
2540
2541 // Otherwise it's +0.
2542 }
2543
2544 // Retain the object as a block, then cast down.
John McCall348f16f2011-10-04 06:23:45 +00002545 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
John McCalldc05b112011-09-10 01:16:55 +00002546 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2547 return TryEmitResult(result, true);
2548 }
2549
John McCall7e5e5f42011-07-07 06:58:02 +00002550 // For reclaims, emit the subexpression as a retained call and
2551 // skip the consumption.
John McCall33e56f32011-09-10 06:18:15 +00002552 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00002553 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2554 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2555 return TryEmitResult(result, true);
2556 }
2557
John McCallf85e1932011-06-15 23:02:42 +00002558 default:
2559 break;
2560 }
2561
2562 // Skip __extension__.
2563 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2564 if (op->getOpcode() == UO_Extension) {
2565 e = op->getSubExpr();
2566 continue;
2567 }
2568
2569 // For calls and message sends, use the retained-call logic.
2570 // Delegate inits are a special case in that they're the only
2571 // returns-retained expression that *isn't* surrounded by
2572 // a consume.
2573 } else if (isa<CallExpr>(e) ||
2574 (isa<ObjCMessageExpr>(e) &&
2575 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2576 llvm::Value *result = emitARCRetainCall(CGF, e);
2577 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2578 return TryEmitResult(result, true);
John McCall4b9c2d22011-11-06 09:01:30 +00002579
2580 // Look through pseudo-object expressions.
2581 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2582 TryEmitResult result
2583 = tryEmitARCRetainPseudoObject(CGF, pseudo);
2584 if (resultType) {
2585 llvm::Value *value = result.getPointer();
2586 value = CGF.Builder.CreateBitCast(value, resultType);
2587 result.setPointer(value);
2588 }
2589 return result;
John McCallf85e1932011-06-15 23:02:42 +00002590 }
2591
2592 // Conservatively halt the search at any other expression kind.
2593 break;
2594 }
2595
2596 // We didn't find an obvious production, so emit what we've got and
2597 // tell the caller that we didn't manage to retain.
2598 llvm::Value *result = CGF.EmitScalarExpr(e);
2599 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2600 return TryEmitResult(result, false);
2601}
2602
2603static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2604 LValue lvalue,
2605 QualType type) {
2606 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2607 llvm::Value *value = result.getPointer();
2608 if (!result.getInt())
2609 value = CGF.EmitARCRetain(type, value);
2610 return value;
2611}
2612
2613/// EmitARCRetainScalarExpr - Semantically equivalent to
2614/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2615/// best-effort attempt to peephole expressions that naturally produce
2616/// retained objects.
2617llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
2618 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2619 llvm::Value *value = result.getPointer();
2620 if (!result.getInt())
2621 value = EmitARCRetain(e->getType(), value);
2622 return value;
2623}
2624
2625llvm::Value *
2626CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
2627 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2628 llvm::Value *value = result.getPointer();
2629 if (result.getInt())
2630 value = EmitARCAutorelease(value);
2631 else
2632 value = EmitARCRetainAutorelease(e->getType(), value);
2633 return value;
2634}
2635
John McCall348f16f2011-10-04 06:23:45 +00002636llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2637 llvm::Value *result;
2638 bool doRetain;
2639
2640 if (shouldEmitSeparateBlockRetain(e)) {
2641 result = EmitScalarExpr(e);
2642 doRetain = true;
2643 } else {
2644 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2645 result = subresult.getPointer();
2646 doRetain = !subresult.getInt();
2647 }
2648
2649 if (doRetain)
2650 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2651 return EmitObjCConsumeObject(e->getType(), result);
2652}
2653
John McCall2b014d62011-10-01 10:32:24 +00002654llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2655 // In ARC, retain and autorelease the expression.
David Blaikie4e4d0842012-03-11 07:00:24 +00002656 if (getLangOpts().ObjCAutoRefCount) {
John McCall2b014d62011-10-01 10:32:24 +00002657 // Do so before running any cleanups for the full-expression.
2658 // tryEmitARCRetainScalarExpr does make an effort to do things
2659 // inside cleanups, but there are crazy cases like
2660 // @throw A().foo;
2661 // where a full retain+autorelease is required and would
2662 // otherwise happen after the destructor for the temporary.
John McCall1a343eb2011-11-10 08:15:53 +00002663 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(expr)) {
2664 enterFullExpression(ewc);
John McCall2b014d62011-10-01 10:32:24 +00002665 expr = ewc->getSubExpr();
John McCall1a343eb2011-11-10 08:15:53 +00002666 }
John McCall2b014d62011-10-01 10:32:24 +00002667
John McCall1a343eb2011-11-10 08:15:53 +00002668 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall2b014d62011-10-01 10:32:24 +00002669 return EmitARCRetainAutoreleaseScalarExpr(expr);
2670 }
2671
2672 // Otherwise, use the normal scalar-expression emission. The
2673 // exception machinery doesn't do anything special with the
2674 // exception like retaining it, so there's no safety associated with
2675 // only running cleanups after the throw has started, and when it
2676 // matters it tends to be substantially inferior code.
2677 return EmitScalarExpr(expr);
2678}
2679
John McCallf85e1932011-06-15 23:02:42 +00002680std::pair<LValue,llvm::Value*>
2681CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2682 bool ignored) {
2683 // Evaluate the RHS first.
2684 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2685 llvm::Value *value = result.getPointer();
2686
John McCallfb720812011-07-28 07:23:35 +00002687 bool hasImmediateRetain = result.getInt();
2688
2689 // If we didn't emit a retained object, and the l-value is of block
2690 // type, then we need to emit the block-retain immediately in case
2691 // it invalidates the l-value.
2692 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCall348f16f2011-10-04 06:23:45 +00002693 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallfb720812011-07-28 07:23:35 +00002694 hasImmediateRetain = true;
2695 }
2696
John McCallf85e1932011-06-15 23:02:42 +00002697 LValue lvalue = EmitLValue(e->getLHS());
2698
2699 // If the RHS was emitted retained, expand this.
John McCallfb720812011-07-28 07:23:35 +00002700 if (hasImmediateRetain) {
John McCallf85e1932011-06-15 23:02:42 +00002701 llvm::Value *oldValue =
Eli Friedman6da2c712011-12-03 04:14:32 +00002702 EmitLoadOfScalar(lvalue);
2703 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +00002704 EmitARCRelease(oldValue, /*precise*/ false);
2705 } else {
John McCall545d9962011-06-25 02:11:03 +00002706 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCallf85e1932011-06-15 23:02:42 +00002707 }
2708
2709 return std::pair<LValue,llvm::Value*>(lvalue, value);
2710}
2711
2712std::pair<LValue,llvm::Value*>
2713CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2714 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2715 LValue lvalue = EmitLValue(e->getLHS());
2716
Eli Friedman6da2c712011-12-03 04:14:32 +00002717 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +00002718
2719 return std::pair<LValue,llvm::Value*>(lvalue, value);
2720}
2721
2722void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher16098f32012-03-29 17:31:31 +00002723 const ObjCAutoreleasePoolStmt &ARPS) {
John McCallf85e1932011-06-15 23:02:42 +00002724 const Stmt *subStmt = ARPS.getSubStmt();
2725 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2726
2727 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00002728 if (DI)
2729 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002730
2731 // Keep track of the current cleanup stack depth.
2732 RunCleanupsScope Scope(*this);
John McCall260611a2012-06-20 06:18:46 +00002733 if (CGM.getLangOpts().ObjCRuntime.hasARC()) {
John McCallf85e1932011-06-15 23:02:42 +00002734 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2735 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2736 } else {
2737 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2738 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2739 }
2740
2741 for (CompoundStmt::const_body_iterator I = S.body_begin(),
2742 E = S.body_end(); I != E; ++I)
2743 EmitStmt(*I);
2744
Eric Christopher73fb3502011-10-13 21:45:18 +00002745 if (DI)
2746 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002747}
John McCall0c24c802011-06-24 23:21:27 +00002748
2749/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2750/// make sure it survives garbage collection until this point.
2751void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2752 // We just use an inline assembly.
John McCall0c24c802011-06-24 23:21:27 +00002753 llvm::FunctionType *extenderType
John McCallde5d3c72012-02-17 03:33:10 +00002754 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
John McCall0c24c802011-06-24 23:21:27 +00002755 llvm::Value *extender
2756 = llvm::InlineAsm::get(extenderType,
2757 /* assembly */ "",
2758 /* constraints */ "r",
2759 /* side effects */ true);
2760
2761 object = Builder.CreateBitCast(object, VoidPtrTy);
2762 Builder.CreateCall(extender, object)->setDoesNotThrow();
2763}
2764
John McCall260611a2012-06-20 06:18:46 +00002765static bool hasAtomicCopyHelperAPI(const ObjCRuntime &runtime) {
2766 // For now, only NeXT has these APIs.
2767 return runtime.isNeXTFamily();
2768}
2769
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002770/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002771/// non-trivial copy assignment function, produce following helper function.
2772/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
2773///
2774llvm::Constant *
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002775CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
2776 const ObjCPropertyImplDecl *PID) {
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002777 // FIXME. This api is for NeXt runtime only for now.
John McCall260611a2012-06-20 06:18:46 +00002778 if (!getLangOpts().CPlusPlus ||
2779 !hasAtomicCopyHelperAPI(getLangOpts().ObjCRuntime))
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002780 return 0;
2781 QualType Ty = PID->getPropertyIvarDecl()->getType();
2782 if (!Ty->isRecordType())
2783 return 0;
2784 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002785 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002786 return 0;
Fariborz Jahanianb08cfb32012-01-08 19:13:23 +00002787 llvm::Constant * HelperFn = 0;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002788 if (hasTrivialSetExpr(PID))
2789 return 0;
2790 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
2791 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
2792 return HelperFn;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002793
2794 ASTContext &C = getContext();
2795 IdentifierInfo *II
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002796 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002797 FunctionDecl *FD = FunctionDecl::Create(C,
2798 C.getTranslationUnitDecl(),
2799 SourceLocation(),
2800 SourceLocation(), II, C.VoidTy, 0,
2801 SC_Static,
2802 SC_None,
2803 false,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00002804 false);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002805
2806 QualType DestTy = C.getPointerType(Ty);
2807 QualType SrcTy = Ty;
2808 SrcTy.addConst();
2809 SrcTy = C.getPointerType(SrcTy);
2810
2811 FunctionArgList args;
2812 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2813 args.push_back(&dstDecl);
2814 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2815 args.push_back(&srcDecl);
2816
2817 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00002818 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
2819 FunctionType::ExtInfo(),
2820 RequiredArgs::All);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002821
John McCallde5d3c72012-02-17 03:33:10 +00002822 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002823
2824 llvm::Function *Fn =
2825 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher16098f32012-03-29 17:31:31 +00002826 "__assign_helper_atomic_property_",
2827 &CGM.getModule());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002828
2829 if (CGM.getModuleDebugInfo())
2830 DebugInfo = CGM.getModuleDebugInfo();
2831
2832
2833 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2834
John McCallf4b88a42012-03-10 09:33:50 +00002835 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2836 VK_RValue, SourceLocation());
2837 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
2838 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002839
John McCallf4b88a42012-03-10 09:33:50 +00002840 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
2841 VK_RValue, SourceLocation());
2842 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2843 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002844
John McCallf4b88a42012-03-10 09:33:50 +00002845 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002846 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
John McCallf4b88a42012-03-10 09:33:50 +00002847 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
2848 Args, 2, DestTy->getPointeeType(),
2849 VK_LValue, SourceLocation());
2850
2851 EmitStmt(&TheCall);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002852
2853 FinishFunction();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002854 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002855 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002856 return HelperFn;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002857}
2858
2859llvm::Constant *
2860CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
2861 const ObjCPropertyImplDecl *PID) {
2862 // FIXME. This api is for NeXt runtime only for now.
John McCall260611a2012-06-20 06:18:46 +00002863 if (!getLangOpts().CPlusPlus ||
2864 !hasAtomicCopyHelperAPI(getLangOpts().ObjCRuntime))
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002865 return 0;
2866 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2867 QualType Ty = PD->getType();
2868 if (!Ty->isRecordType())
2869 return 0;
2870 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
2871 return 0;
2872 llvm::Constant * HelperFn = 0;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002873
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002874 if (hasTrivialGetExpr(PID))
2875 return 0;
2876 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
2877 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
2878 return HelperFn;
2879
2880
2881 ASTContext &C = getContext();
2882 IdentifierInfo *II
2883 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
2884 FunctionDecl *FD = FunctionDecl::Create(C,
2885 C.getTranslationUnitDecl(),
2886 SourceLocation(),
2887 SourceLocation(), II, C.VoidTy, 0,
2888 SC_Static,
2889 SC_None,
2890 false,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00002891 false);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002892
2893 QualType DestTy = C.getPointerType(Ty);
2894 QualType SrcTy = Ty;
2895 SrcTy.addConst();
2896 SrcTy = C.getPointerType(SrcTy);
2897
2898 FunctionArgList args;
2899 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2900 args.push_back(&dstDecl);
2901 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2902 args.push_back(&srcDecl);
2903
2904 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00002905 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
2906 FunctionType::ExtInfo(),
2907 RequiredArgs::All);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002908
John McCallde5d3c72012-02-17 03:33:10 +00002909 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002910
2911 llvm::Function *Fn =
2912 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2913 "__copy_helper_atomic_property_", &CGM.getModule());
2914
2915 if (CGM.getModuleDebugInfo())
2916 DebugInfo = CGM.getModuleDebugInfo();
2917
2918
2919 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2920
John McCallf4b88a42012-03-10 09:33:50 +00002921 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002922 VK_RValue, SourceLocation());
2923
John McCallf4b88a42012-03-10 09:33:50 +00002924 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2925 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002926
2927 CXXConstructExpr *CXXConstExpr =
2928 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
2929
2930 SmallVector<Expr*, 4> ConstructorArgs;
John McCallf4b88a42012-03-10 09:33:50 +00002931 ConstructorArgs.push_back(&SRC);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002932 CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin();
2933 ++A;
2934
2935 for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end();
2936 A != AEnd; ++A)
2937 ConstructorArgs.push_back(*A);
2938
2939 CXXConstructExpr *TheCXXConstructExpr =
2940 CXXConstructExpr::Create(C, Ty, SourceLocation(),
2941 CXXConstExpr->getConstructor(),
2942 CXXConstExpr->isElidable(),
2943 &ConstructorArgs[0], ConstructorArgs.size(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002944 CXXConstExpr->hadMultipleCandidates(),
2945 CXXConstExpr->isListInitialization(),
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002946 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher16098f32012-03-29 17:31:31 +00002947 CXXConstExpr->getConstructionKind(),
2948 SourceRange());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002949
John McCallf4b88a42012-03-10 09:33:50 +00002950 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2951 VK_RValue, SourceLocation());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002952
John McCallf4b88a42012-03-10 09:33:50 +00002953 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher16098f32012-03-29 17:31:31 +00002954 CharUnits Alignment
2955 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002956 EmitAggExpr(TheCXXConstructExpr,
2957 AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifiers(),
2958 AggValueSlot::IsDestructed,
2959 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00002960 AggValueSlot::IsNotAliased));
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002961
2962 FinishFunction();
2963 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2964 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
2965 return HelperFn;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002966}
2967
Eli Friedmancae40c42012-02-28 01:08:45 +00002968llvm::Value *
2969CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
2970 // Get selectors for retain/autorelease.
Eli Friedman8c72a7d2012-03-01 22:52:28 +00002971 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
2972 Selector CopySelector =
2973 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmancae40c42012-02-28 01:08:45 +00002974 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
2975 Selector AutoreleaseSelector =
2976 getContext().Selectors.getNullarySelector(AutoreleaseID);
2977
2978 // Emit calls to retain/autorelease.
2979 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2980 llvm::Value *Val = Block;
2981 RValue Result;
2982 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedman8c72a7d2012-03-01 22:52:28 +00002983 Ty, CopySelector,
Eli Friedmancae40c42012-02-28 01:08:45 +00002984 Val, CallArgList(), 0, 0);
2985 Val = Result.getScalarVal();
2986 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2987 Ty, AutoreleaseSelector,
2988 Val, CallArgList(), 0, 0);
2989 Val = Result.getScalarVal();
2990 return Val;
2991}
2992
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002993
Ted Kremenek2979ec72008-04-09 15:51:31 +00002994CGObjCRuntime::~CGObjCRuntime() {}