blob: 0592601446877300d211f995d578eb102b66e96c [file] [log] [blame]
Anders Carlsson76f4a902007-08-21 17:43:55 +00001//===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Anders Carlsson76f4a902007-08-21 17:43:55 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Objective-C code as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Devang Pateld2d66652011-01-19 01:36:36 +000014#include "CGDebugInfo.h"
Ted Kremenek43e06332008-04-09 15:51:31 +000015#include "CGObjCRuntime.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000016#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
John McCall31168b02011-06-15 23:02:42 +000018#include "TargetInfo.h"
Daniel Dunbar9e22c0d2008-08-29 08:11:39 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000021#include "clang/AST/StmtObjC.h"
Daniel Dunbarc5d33042008-09-03 00:27:26 +000022#include "clang/Basic/Diagnostic.h"
Anders Carlsson2e744e82008-08-30 19:51:14 +000023#include "llvm/ADT/STLExtras.h"
Daniel Dunbara08dff12008-09-24 04:04:31 +000024#include "llvm/Target/TargetData.h"
John McCall31168b02011-06-15 23:02:42 +000025#include "llvm/InlineAsm.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000026using namespace clang;
27using namespace CodeGen;
28
John McCall31168b02011-06-15 23:02:42 +000029typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
30static TryEmitResult
31tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
Ted Kremeneke65b0862012-03-06 20:05:56 +000032static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
33 const Expr *E,
34 const ObjCMethodDecl *Method,
35 RValue Result);
John McCall31168b02011-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 Lattner2192fe52011-07-18 04:24:23 +000040 llvm::Type *type =
John McCall31168b02011-06-15 23:02:42 +000041 cast<llvm::PointerType>(addr->getType())->getElementType();
42 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
43}
44
Chris Lattnerb1d329d2008-06-24 17:04:18 +000045/// Emits an instance of NSConstantString representing the object.
Mike Stump11289f42009-09-09 15:08:12 +000046llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar44b58a22008-11-25 21:53:21 +000047{
David Chisnall481e3a82010-01-23 02:40:42 +000048 llvm::Constant *C =
49 CGM.getObjCRuntime().GenerateConstantString(E->getString());
Daniel Dunbar66912a12008-08-20 00:28:19 +000050 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Andersonade90fd2009-07-29 18:54:39 +000051 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattnerb1d329d2008-06-24 17:04:18 +000052}
53
Ted Kremeneke65b0862012-03-06 20:05:56 +000054/// EmitObjCNumericLiteral - This routine generates code for
55/// the appropriate +[NSNumber numberWith<Type>:] method.
56///
57llvm::Value *CodeGenFunction::EmitObjCNumericLiteral(const ObjCNumericLiteral *E) {
58 // Generate the correct selector for this literal's concrete type.
59 const Expr *NL = E->getNumber();
60 // Get the method.
61 const ObjCMethodDecl *Method = E->getObjCNumericLiteralMethod();
62 assert(Method && "NSNumber method is null");
63 Selector Sel = Method->getSelector();
64
65 // Generate a reference to the class pointer, which will be the receiver.
66 QualType ResultType = E->getType(); // should be NSNumber *
67 const ObjCObjectPointerType *InterfacePointerType =
68 ResultType->getAsObjCInterfacePointerType();
69 ObjCInterfaceDecl *NSNumberDecl =
70 InterfacePointerType->getObjectType()->getInterface();
71 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
72 llvm::Value *Receiver = Runtime.GetClass(Builder, NSNumberDecl);
73
74 const ParmVarDecl *argDecl = *Method->param_begin();
75 QualType ArgQT = argDecl->getType().getUnqualifiedType();
76 RValue RV = EmitAnyExpr(NL);
77 CallArgList Args;
78 Args.add(RV, ArgQT);
79
80 RValue result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
81 ResultType, Sel, Receiver, Args,
82 NSNumberDecl, Method);
83 return Builder.CreateBitCast(result.getScalarVal(),
84 ConvertType(E->getType()));
85}
86
87llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
88 const ObjCMethodDecl *MethodWithObjects) {
89 ASTContext &Context = CGM.getContext();
90 const ObjCDictionaryLiteral *DLE = 0;
91 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
92 if (!ALE)
93 DLE = cast<ObjCDictionaryLiteral>(E);
94
95 // Compute the type of the array we're initializing.
96 uint64_t NumElements =
97 ALE ? ALE->getNumElements() : DLE->getNumElements();
98 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
99 NumElements);
100 QualType ElementType = Context.getObjCIdType().withConst();
101 QualType ElementArrayType
102 = Context.getConstantArrayType(ElementType, APNumElements,
103 ArrayType::Normal, /*IndexTypeQuals=*/0);
104
105 // Allocate the temporary array(s).
106 llvm::Value *Objects = CreateMemTemp(ElementArrayType, "objects");
107 llvm::Value *Keys = 0;
108 if (DLE)
109 Keys = CreateMemTemp(ElementArrayType, "keys");
110
111 // Perform the actual initialialization of the array(s).
112 for (uint64_t i = 0; i < NumElements; i++) {
113 if (ALE) {
114 // Emit the initializer.
115 const Expr *Rhs = ALE->getElement(i);
116 LValue LV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
117 ElementType,
118 Context.getTypeAlignInChars(Rhs->getType()),
119 Context);
120 EmitScalarInit(Rhs, /*D=*/0, LV, /*capturedByInit=*/false);
121 } else {
122 // Emit the key initializer.
123 const Expr *Key = DLE->getKeyValueElement(i).Key;
124 LValue KeyLV = LValue::MakeAddr(Builder.CreateStructGEP(Keys, i),
125 ElementType,
126 Context.getTypeAlignInChars(Key->getType()),
127 Context);
128 EmitScalarInit(Key, /*D=*/0, KeyLV, /*capturedByInit=*/false);
129
130 // Emit the value initializer.
131 const Expr *Value = DLE->getKeyValueElement(i).Value;
132 LValue ValueLV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
133 ElementType,
134 Context.getTypeAlignInChars(Value->getType()),
135 Context);
136 EmitScalarInit(Value, /*D=*/0, ValueLV, /*capturedByInit=*/false);
137 }
138 }
139
140 // Generate the argument list.
141 CallArgList Args;
142 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
143 const ParmVarDecl *argDecl = *PI++;
144 QualType ArgQT = argDecl->getType().getUnqualifiedType();
145 Args.add(RValue::get(Objects), ArgQT);
146 if (DLE) {
147 argDecl = *PI++;
148 ArgQT = argDecl->getType().getUnqualifiedType();
149 Args.add(RValue::get(Keys), ArgQT);
150 }
151 argDecl = *PI;
152 ArgQT = argDecl->getType().getUnqualifiedType();
153 llvm::Value *Count =
154 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
155 Args.add(RValue::get(Count), ArgQT);
156
157 // Generate a reference to the class pointer, which will be the receiver.
158 Selector Sel = MethodWithObjects->getSelector();
159 QualType ResultType = E->getType();
160 const ObjCObjectPointerType *InterfacePointerType
161 = ResultType->getAsObjCInterfacePointerType();
162 ObjCInterfaceDecl *Class
163 = InterfacePointerType->getObjectType()->getInterface();
164 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
165 llvm::Value *Receiver = Runtime.GetClass(Builder, Class);
166
167 // Generate the message send.
168 RValue result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
169 MethodWithObjects->getResultType(),
170 Sel,
171 Receiver, Args, Class,
172 MethodWithObjects);
173 return Builder.CreateBitCast(result.getScalarVal(),
174 ConvertType(E->getType()));
175}
176
177llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
178 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
179}
180
181llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
182 const ObjCDictionaryLiteral *E) {
183 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
184}
185
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000186/// Emit a selector.
187llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
188 // Untyped selector.
189 // Note that this implementation allows for non-constant strings to be passed
190 // as arguments to @selector(). Currently, the only thing preventing this
191 // behaviour is the type checking in the front end.
Daniel Dunbar45858d22010-02-03 20:11:42 +0000192 return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000193}
194
Daniel Dunbar66912a12008-08-20 00:28:19 +0000195llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
196 // FIXME: This should pass the Decl not the name.
197 return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol());
198}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000199
Douglas Gregor33823722011-06-11 01:09:30 +0000200/// \brief Adjust the type of the result of an Objective-C message send
201/// expression when the method has a related result type.
202static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
203 const Expr *E,
204 const ObjCMethodDecl *Method,
205 RValue Result) {
206 if (!Method)
207 return Result;
John McCall31168b02011-06-15 23:02:42 +0000208
Douglas Gregor33823722011-06-11 01:09:30 +0000209 if (!Method->hasRelatedResultType() ||
210 CGF.getContext().hasSameType(E->getType(), Method->getResultType()) ||
211 !Result.isScalar())
212 return Result;
213
214 // We have applied a related result type. Cast the rvalue appropriately.
215 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
216 CGF.ConvertType(E->getType())));
217}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000218
John McCallcf166702011-07-22 08:53:00 +0000219/// Decide whether to extend the lifetime of the receiver of a
220/// returns-inner-pointer message.
221static bool
222shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
223 switch (message->getReceiverKind()) {
224
225 // For a normal instance message, we should extend unless the
226 // receiver is loaded from a variable with precise lifetime.
227 case ObjCMessageExpr::Instance: {
228 const Expr *receiver = message->getInstanceReceiver();
229 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
230 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
231 receiver = ice->getSubExpr()->IgnoreParens();
232
233 // Only __strong variables.
234 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
235 return true;
236
237 // All ivars and fields have precise lifetime.
238 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
239 return false;
240
241 // Otherwise, check for variables.
242 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
243 if (!declRef) return true;
244 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
245 if (!var) return true;
246
247 // All variables have precise lifetime except local variables with
248 // automatic storage duration that aren't specially marked.
249 return (var->hasLocalStorage() &&
250 !var->hasAttr<ObjCPreciseLifetimeAttr>());
251 }
252
253 case ObjCMessageExpr::Class:
254 case ObjCMessageExpr::SuperClass:
255 // It's never necessary for class objects.
256 return false;
257
258 case ObjCMessageExpr::SuperInstance:
259 // We generally assume that 'self' lives throughout a method call.
260 return false;
261 }
262
263 llvm_unreachable("invalid receiver kind");
264}
265
John McCall78a15112010-05-22 01:48:05 +0000266RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
267 ReturnValueSlot Return) {
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000268 // Only the lookup mechanism and first two arguments of the method
269 // implementation vary between runtimes. We can get the receiver and
270 // arguments in generic code.
Mike Stump11289f42009-09-09 15:08:12 +0000271
John McCall31168b02011-06-15 23:02:42 +0000272 bool isDelegateInit = E->isDelegateInitCall();
273
John McCallcf166702011-07-22 08:53:00 +0000274 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000275
John McCall31168b02011-06-15 23:02:42 +0000276 // We don't retain the receiver in delegate init calls, and this is
277 // safe because the receiver value is always loaded from 'self',
278 // which we zero out. We don't want to Block_copy block receivers,
279 // though.
280 bool retainSelf =
281 (!isDelegateInit &&
282 CGM.getLangOptions().ObjCAutoRefCount &&
John McCallcf166702011-07-22 08:53:00 +0000283 method &&
284 method->hasAttr<NSConsumesSelfAttr>());
John McCall31168b02011-06-15 23:02:42 +0000285
Daniel Dunbar8d480592008-08-11 18:12:00 +0000286 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000287 bool isSuperMessage = false;
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000288 bool isClassMessage = false;
David Chisnall01aa4672010-04-28 19:33:36 +0000289 ObjCInterfaceDecl *OID = 0;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000290 // Find the receiver
Douglas Gregor33823722011-06-11 01:09:30 +0000291 QualType ReceiverType;
Daniel Dunbarb2197802010-04-22 03:17:06 +0000292 llvm::Value *Receiver = 0;
Douglas Gregor9a129192010-04-21 00:45:42 +0000293 switch (E->getReceiverKind()) {
294 case ObjCMessageExpr::Instance:
Douglas Gregor33823722011-06-11 01:09:30 +0000295 ReceiverType = E->getInstanceReceiver()->getType();
John McCall31168b02011-06-15 23:02:42 +0000296 if (retainSelf) {
297 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
298 E->getInstanceReceiver());
299 Receiver = ter.getPointer();
John McCallcf166702011-07-22 08:53:00 +0000300 if (ter.getInt()) retainSelf = false;
John McCall31168b02011-06-15 23:02:42 +0000301 } else
302 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor9a129192010-04-21 00:45:42 +0000303 break;
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000304
Douglas Gregor9a129192010-04-21 00:45:42 +0000305 case ObjCMessageExpr::Class: {
Douglas Gregor33823722011-06-11 01:09:30 +0000306 ReceiverType = E->getClassReceiver();
307 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3e294922010-05-17 20:12:43 +0000308 assert(ObjTy && "Invalid Objective-C class message send");
309 OID = ObjTy->getInterface();
310 assert(OID && "Invalid Objective-C class message send");
David Chisnall01aa4672010-04-28 19:33:36 +0000311 Receiver = Runtime.GetClass(Builder, OID);
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000312 isClassMessage = true;
Douglas Gregor9a129192010-04-21 00:45:42 +0000313 break;
314 }
315
316 case ObjCMessageExpr::SuperInstance:
Douglas Gregor33823722011-06-11 01:09:30 +0000317 ReceiverType = E->getSuperType();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000318 Receiver = LoadObjCSelf();
Douglas Gregor9a129192010-04-21 00:45:42 +0000319 isSuperMessage = true;
320 break;
321
322 case ObjCMessageExpr::SuperClass:
Douglas Gregor33823722011-06-11 01:09:30 +0000323 ReceiverType = E->getSuperType();
Douglas Gregor9a129192010-04-21 00:45:42 +0000324 Receiver = LoadObjCSelf();
325 isSuperMessage = true;
326 isClassMessage = true;
327 break;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000328 }
329
John McCallcf166702011-07-22 08:53:00 +0000330 if (retainSelf)
331 Receiver = EmitARCRetainNonBlock(Receiver);
332
333 // In ARC, we sometimes want to "extend the lifetime"
334 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
335 // messages.
336 if (getLangOptions().ObjCAutoRefCount && method &&
337 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
338 shouldExtendReceiverForInnerPointerMessage(E))
339 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
340
John McCall31168b02011-06-15 23:02:42 +0000341 QualType ResultType =
John McCallcf166702011-07-22 08:53:00 +0000342 method ? method->getResultType() : E->getType();
John McCall31168b02011-06-15 23:02:42 +0000343
Daniel Dunbarc722b852008-08-30 03:02:31 +0000344 CallArgList Args;
John McCallcf166702011-07-22 08:53:00 +0000345 EmitCallArgs(Args, method, E->arg_begin(), E->arg_end());
Mike Stump11289f42009-09-09 15:08:12 +0000346
John McCall31168b02011-06-15 23:02:42 +0000347 // For delegate init calls in ARC, do an unsafe store of null into
348 // self. This represents the call taking direct ownership of that
349 // value. We have to do this after emitting the other call
350 // arguments because they might also reference self, but we don't
351 // have to worry about any of them modifying self because that would
352 // be an undefined read and write of an object in unordered
353 // expressions.
354 if (isDelegateInit) {
355 assert(getLangOptions().ObjCAutoRefCount &&
356 "delegate init calls should only be marked in ARC");
357
358 // Do an unsafe store of null into self.
359 llvm::Value *selfAddr =
360 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
361 assert(selfAddr && "no self entry for a delegate init call?");
362
363 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
364 }
Anders Carlsson280e61f12010-06-21 20:59:55 +0000365
Douglas Gregor33823722011-06-11 01:09:30 +0000366 RValue result;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000367 if (isSuperMessage) {
Chris Lattner6cfec782008-06-26 04:42:20 +0000368 // super is only valid in an Objective-C method
369 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000370 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor33823722011-06-11 01:09:30 +0000371 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
372 E->getSelector(),
373 OMD->getClassInterface(),
374 isCategoryImpl,
375 Receiver,
376 isClassMessage,
377 Args,
John McCallcf166702011-07-22 08:53:00 +0000378 method);
Douglas Gregor33823722011-06-11 01:09:30 +0000379 } else {
380 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
381 E->getSelector(),
382 Receiver, Args, OID,
John McCallcf166702011-07-22 08:53:00 +0000383 method);
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000384 }
John McCall31168b02011-06-15 23:02:42 +0000385
386 // For delegate init calls in ARC, implicitly store the result of
387 // the call back into self. This takes ownership of the value.
388 if (isDelegateInit) {
389 llvm::Value *selfAddr =
390 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
391 llvm::Value *newSelf = result.getScalarVal();
392
393 // The delegate return type isn't necessarily a matching type; in
394 // fact, it's quite likely to be 'id'.
Chris Lattner2192fe52011-07-18 04:24:23 +0000395 llvm::Type *selfTy =
John McCall31168b02011-06-15 23:02:42 +0000396 cast<llvm::PointerType>(selfAddr->getType())->getElementType();
397 newSelf = Builder.CreateBitCast(newSelf, selfTy);
398
399 Builder.CreateStore(newSelf, selfAddr);
400 }
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000401
402 return AdjustRelatedResultType(*this, E, method, result);
Anders Carlsson76f4a902007-08-21 17:43:55 +0000403}
404
John McCall31168b02011-06-15 23:02:42 +0000405namespace {
406struct FinishARCDealloc : EHScopeStack::Cleanup {
John McCall30317fd2011-07-12 20:27:29 +0000407 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall31168b02011-06-15 23:02:42 +0000408 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCalldffafde2011-07-13 18:26:47 +0000409
410 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCall31168b02011-06-15 23:02:42 +0000411 const ObjCInterfaceDecl *iface = impl->getClassInterface();
412 if (!iface->getSuperClass()) return;
413
John McCalldffafde2011-07-13 18:26:47 +0000414 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
415
John McCall31168b02011-06-15 23:02:42 +0000416 // Call [super dealloc] if we have a superclass.
417 llvm::Value *self = CGF.LoadObjCSelf();
418
419 CallArgList args;
420 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
421 CGF.getContext().VoidTy,
422 method->getSelector(),
423 iface,
John McCalldffafde2011-07-13 18:26:47 +0000424 isCategory,
John McCall31168b02011-06-15 23:02:42 +0000425 self,
426 /*is class msg*/ false,
427 args,
428 method);
429 }
430};
431}
432
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000433/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
434/// the LLVM function and sets the other context used by
435/// CodeGenFunction.
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000436void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
Devang Patele7ce5402011-05-19 23:37:41 +0000437 const ObjCContainerDecl *CD,
438 SourceLocation StartLoc) {
John McCalla738c252011-03-09 04:27:21 +0000439 FunctionArgList args;
Devang Patela2c048e2010-04-05 21:09:15 +0000440 // Check if we should generate debug info for this method.
Devang Pateld6ffebb2011-03-07 18:45:56 +0000441 if (CGM.getModuleDebugInfo() && !OMD->hasAttr<NoDebugAttr>())
442 DebugInfo = CGM.getModuleDebugInfo();
Devang Patela2c048e2010-04-05 21:09:15 +0000443
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000444 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000445
John McCalla729c622012-02-17 03:33:10 +0000446 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000447 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000448
John McCalla738c252011-03-09 04:27:21 +0000449 args.push_back(OMD->getSelfDecl());
450 args.push_back(OMD->getCmdDecl());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000451
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +0000452 for (ObjCMethodDecl::param_const_iterator PI = OMD->param_begin(),
Chris Lattnera4997152009-02-20 18:43:26 +0000453 E = OMD->param_end(); PI != E; ++PI)
John McCalla738c252011-03-09 04:27:21 +0000454 args.push_back(*PI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000455
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000456 CurGD = OMD;
457
Devang Patele7ce5402011-05-19 23:37:41 +0000458 StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc);
John McCall31168b02011-06-15 23:02:42 +0000459
460 // In ARC, certain methods get an extra cleanup.
461 if (CGM.getLangOptions().ObjCAutoRefCount &&
462 OMD->isInstanceMethod() &&
463 OMD->getSelector().isUnarySelector()) {
464 const IdentifierInfo *ident =
465 OMD->getSelector().getIdentifierInfoForSlot(0);
466 if (ident->isStr("dealloc"))
467 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
468 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000469}
Daniel Dunbara94ecd22008-08-16 03:19:19 +0000470
John McCall31168b02011-06-15 23:02:42 +0000471static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
472 LValue lvalue, QualType type);
473
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000474/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump11289f42009-09-09 15:08:12 +0000475/// its pointer, name, and types registered in the class struture.
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000476void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
Devang Patele7ce5402011-05-19 23:37:41 +0000477 StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000478 EmitStmt(OMD->getBody());
479 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000480}
481
John McCallb923ece2011-09-12 23:06:44 +0000482/// emitStructGetterCall - Call the runtime function to load a property
483/// into the return value slot.
484static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
485 bool isAtomic, bool hasStrong) {
486 ASTContext &Context = CGF.getContext();
487
488 llvm::Value *src =
489 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(),
490 ivar, 0).getAddress();
491
492 // objc_copyStruct (ReturnValue, &structIvar,
493 // sizeof (Type of Ivar), isAtomic, false);
494 CallArgList args;
495
496 llvm::Value *dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
497 args.add(RValue::get(dest), Context.VoidPtrTy);
498
499 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
500 args.add(RValue::get(src), Context.VoidPtrTy);
501
502 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
503 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
504 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
505 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
506
507 llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
John McCalla729c622012-02-17 03:33:10 +0000508 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(Context.VoidTy, args,
509 FunctionType::ExtInfo(),
510 RequiredArgs::All),
John McCallb923ece2011-09-12 23:06:44 +0000511 fn, ReturnValueSlot(), args);
512}
513
John McCallf4528ae2011-09-13 03:34:09 +0000514/// Determine whether the given architecture supports unaligned atomic
515/// accesses. They don't have to be fast, just faster than a function
516/// call and a mutex.
517static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedman5be3e6a2011-09-13 20:48:30 +0000518 // FIXME: Allow unaligned atomic load/store on x86. (It is not
519 // currently supported by the backend.)
520 return 0;
John McCallf4528ae2011-09-13 03:34:09 +0000521}
522
523/// Return the maximum size that permits atomic accesses for the given
524/// architecture.
525static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
526 llvm::Triple::ArchType arch) {
527 // ARM has 8-byte atomic accesses, but it's not clear whether we
528 // want to rely on them here.
529
530 // In the default case, just assume that any size up to a pointer is
531 // fine given adequate alignment.
532 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
533}
534
535namespace {
536 class PropertyImplStrategy {
537 public:
538 enum StrategyKind {
539 /// The 'native' strategy is to use the architecture's provided
540 /// reads and writes.
541 Native,
542
543 /// Use objc_setProperty and objc_getProperty.
544 GetSetProperty,
545
546 /// Use objc_setProperty for the setter, but use expression
547 /// evaluation for the getter.
548 SetPropertyAndExpressionGet,
549
550 /// Use objc_copyStruct.
551 CopyStruct,
552
553 /// The 'expression' strategy is to emit normal assignment or
554 /// lvalue-to-rvalue expressions.
555 Expression
556 };
557
558 StrategyKind getKind() const { return StrategyKind(Kind); }
559
560 bool hasStrongMember() const { return HasStrong; }
561 bool isAtomic() const { return IsAtomic; }
562 bool isCopy() const { return IsCopy; }
563
564 CharUnits getIvarSize() const { return IvarSize; }
565 CharUnits getIvarAlignment() const { return IvarAlignment; }
566
567 PropertyImplStrategy(CodeGenModule &CGM,
568 const ObjCPropertyImplDecl *propImpl);
569
570 private:
571 unsigned Kind : 8;
572 unsigned IsAtomic : 1;
573 unsigned IsCopy : 1;
574 unsigned HasStrong : 1;
575
576 CharUnits IvarSize;
577 CharUnits IvarAlignment;
578 };
579}
580
581/// Pick an implementation strategy for the the given property synthesis.
582PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
583 const ObjCPropertyImplDecl *propImpl) {
584 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall43192862011-09-13 18:31:23 +0000585 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCallf4528ae2011-09-13 03:34:09 +0000586
John McCall43192862011-09-13 18:31:23 +0000587 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
588 IsAtomic = prop->isAtomic();
John McCallf4528ae2011-09-13 03:34:09 +0000589 HasStrong = false; // doesn't matter here.
590
591 // Evaluate the ivar's size and alignment.
592 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
593 QualType ivarType = ivar->getType();
594 llvm::tie(IvarSize, IvarAlignment)
595 = CGM.getContext().getTypeInfoInChars(ivarType);
596
597 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall43192862011-09-13 18:31:23 +0000598 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCallf4528ae2011-09-13 03:34:09 +0000599 if (IsCopy) {
600 Kind = GetSetProperty;
601 return;
602 }
603
John McCall43192862011-09-13 18:31:23 +0000604 // Handle retain.
605 if (setterKind == ObjCPropertyDecl::Retain) {
John McCallf4528ae2011-09-13 03:34:09 +0000606 // In GC-only, there's nothing special that needs to be done.
Douglas Gregor79a91412011-09-13 17:21:33 +0000607 if (CGM.getLangOptions().getGC() == LangOptions::GCOnly) {
John McCallf4528ae2011-09-13 03:34:09 +0000608 // fallthrough
609
610 // In ARC, if the property is non-atomic, use expression emission,
611 // which translates to objc_storeStrong. This isn't required, but
612 // it's slightly nicer.
613 } else if (CGM.getLangOptions().ObjCAutoRefCount && !IsAtomic) {
614 Kind = Expression;
615 return;
616
617 // Otherwise, we need to at least use setProperty. However, if
618 // the property isn't atomic, we can use normal expression
619 // emission for the getter.
620 } else if (!IsAtomic) {
621 Kind = SetPropertyAndExpressionGet;
622 return;
623
624 // Otherwise, we have to use both setProperty and getProperty.
625 } else {
626 Kind = GetSetProperty;
627 return;
628 }
629 }
630
631 // If we're not atomic, just use expression accesses.
632 if (!IsAtomic) {
633 Kind = Expression;
634 return;
635 }
636
John McCall0e5c0862011-09-13 05:36:29 +0000637 // Properties on bitfield ivars need to be emitted using expression
638 // accesses even if they're nominally atomic.
639 if (ivar->isBitField()) {
640 Kind = Expression;
641 return;
642 }
643
John McCallf4528ae2011-09-13 03:34:09 +0000644 // GC-qualified or ARC-qualified ivars need to be emitted as
645 // expressions. This actually works out to being atomic anyway,
646 // except for ARC __strong, but that should trigger the above code.
647 if (ivarType.hasNonTrivialObjCLifetime() ||
Douglas Gregor79a91412011-09-13 17:21:33 +0000648 (CGM.getLangOptions().getGC() &&
John McCallf4528ae2011-09-13 03:34:09 +0000649 CGM.getContext().getObjCGCAttrKind(ivarType))) {
650 Kind = Expression;
651 return;
652 }
653
654 // Compute whether the ivar has strong members.
Douglas Gregor79a91412011-09-13 17:21:33 +0000655 if (CGM.getLangOptions().getGC())
John McCallf4528ae2011-09-13 03:34:09 +0000656 if (const RecordType *recordType = ivarType->getAs<RecordType>())
657 HasStrong = recordType->getDecl()->hasObjectMember();
658
659 // We can never access structs with object members with a native
660 // access, because we need to use write barriers. This is what
661 // objc_copyStruct is for.
662 if (HasStrong) {
663 Kind = CopyStruct;
664 return;
665 }
666
667 // Otherwise, this is target-dependent and based on the size and
668 // alignment of the ivar.
John McCall0bef0ba2011-09-13 07:33:34 +0000669
670 // If the size of the ivar is not a power of two, give up. We don't
671 // want to get into the business of doing compare-and-swaps.
672 if (!IvarSize.isPowerOfTwo()) {
673 Kind = CopyStruct;
674 return;
675 }
676
John McCallf4528ae2011-09-13 03:34:09 +0000677 llvm::Triple::ArchType arch =
678 CGM.getContext().getTargetInfo().getTriple().getArch();
679
680 // Most architectures require memory to fit within a single cache
681 // line, so the alignment has to be at least the size of the access.
682 // Otherwise we have to grab a lock.
683 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
684 Kind = CopyStruct;
685 return;
686 }
687
688 // If the ivar's size exceeds the architecture's maximum atomic
689 // access size, we have to use CopyStruct.
690 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
691 Kind = CopyStruct;
692 return;
693 }
694
695 // Otherwise, we can use native loads and stores.
696 Kind = Native;
697}
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000698
699/// GenerateObjCGetter - Generate an Objective-C property getter
Steve Naroff5a7dd782009-01-10 22:55:25 +0000700/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
701/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000702void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
703 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000704 llvm::Constant *AtomicHelperFn =
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000705 GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000706 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
707 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
708 assert(OMD && "Invalid call to generate getter (empty method)");
Devang Patele7ce5402011-05-19 23:37:41 +0000709 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +0000710
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000711 generateObjCGetterBody(IMP, PID, AtomicHelperFn);
John McCallf4528ae2011-09-13 03:34:09 +0000712
713 FinishFunction();
714}
715
John McCallbdd81852011-09-13 06:00:03 +0000716static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
717 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCallf4528ae2011-09-13 03:34:09 +0000718 if (!getter) return true;
719
720 // Sema only makes only of these when the ivar has a C++ class type,
721 // so the form is pretty constrained.
722
John McCallbdd81852011-09-13 06:00:03 +0000723 // If the property has a reference type, we might just be binding a
724 // reference, in which case the result will be a gl-value. We should
725 // treat this as a non-trivial operation.
726 if (getter->isGLValue())
727 return false;
728
John McCallf4528ae2011-09-13 03:34:09 +0000729 // If we selected a trivial copy-constructor, we're okay.
730 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
731 return (construct->getConstructor()->isTrivial());
732
733 // The constructor might require cleanups (in which case it's never
734 // trivial).
735 assert(isa<ExprWithCleanups>(getter));
736 return false;
737}
738
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000739/// emitCPPObjectAtomicGetterCall - Call the runtime function to
740/// copy the ivar into the resturn slot.
741static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
742 llvm::Value *returnAddr,
743 ObjCIvarDecl *ivar,
744 llvm::Constant *AtomicHelperFn) {
745 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
746 // AtomicHelperFn);
747 CallArgList args;
748
749 // The 1st argument is the return Slot.
750 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
751
752 // The 2nd argument is the address of the ivar.
753 llvm::Value *ivarAddr =
754 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
755 CGF.LoadObjCSelf(), ivar, 0).getAddress();
756 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
757 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
758
759 // Third argument is the helper function.
760 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
761
762 llvm::Value *copyCppAtomicObjectFn =
763 CGF.CGM.getObjCRuntime().GetCppAtomicObjectFunction();
John McCalla729c622012-02-17 03:33:10 +0000764 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy, args,
765 FunctionType::ExtInfo(),
766 RequiredArgs::All),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000767 copyCppAtomicObjectFn, ReturnValueSlot(), args);
768}
769
John McCallf4528ae2011-09-13 03:34:09 +0000770void
771CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000772 const ObjCPropertyImplDecl *propImpl,
773 llvm::Constant *AtomicHelperFn) {
John McCallf4528ae2011-09-13 03:34:09 +0000774 // If there's a non-trivial 'get' expression, we just have to emit that.
775 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000776 if (!AtomicHelperFn) {
777 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
778 /*nrvo*/ 0);
779 EmitReturnStmt(ret);
780 }
781 else {
782 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
783 emitCPPObjectAtomicGetterCall(*this, ReturnValue,
784 ivar, AtomicHelperFn);
785 }
John McCallf4528ae2011-09-13 03:34:09 +0000786 return;
787 }
788
789 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
790 QualType propType = prop->getType();
791 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
792
793 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
794
795 // Pick an implementation strategy.
796 PropertyImplStrategy strategy(CGM, propImpl);
797 switch (strategy.getKind()) {
798 case PropertyImplStrategy::Native: {
799 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
800
801 // Currently, all atomic accesses have to be through integer
802 // types, so there's no point in trying to pick a prettier type.
803 llvm::Type *bitcastType =
804 llvm::Type::getIntNTy(getLLVMContext(),
805 getContext().toBits(strategy.getIvarSize()));
806 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
807
808 // Perform an atomic load. This does not impose ordering constraints.
809 llvm::Value *ivarAddr = LV.getAddress();
810 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
811 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
812 load->setAlignment(strategy.getIvarAlignment().getQuantity());
813 load->setAtomic(llvm::Unordered);
814
815 // Store that value into the return address. Doing this with a
816 // bitcast is likely to produce some pretty ugly IR, but it's not
817 // the *most* terrible thing in the world.
818 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
819
820 // Make sure we don't do an autorelease.
821 AutoreleaseResult = false;
822 return;
823 }
824
825 case PropertyImplStrategy::GetSetProperty: {
826 llvm::Value *getPropertyFn =
827 CGM.getObjCRuntime().GetPropertyGetFunction();
828 if (!getPropertyFn) {
829 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbara08dff12008-09-24 04:04:31 +0000830 return;
831 }
832
833 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
834 // FIXME: Can't this be simpler? This might even be worse than the
835 // corresponding gcc code.
John McCallf4528ae2011-09-13 03:34:09 +0000836 llvm::Value *cmd =
837 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
838 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
839 llvm::Value *ivarOffset =
840 EmitIvarOffset(classImpl->getClassInterface(), ivar);
841
842 CallArgList args;
843 args.add(RValue::get(self), getContext().getObjCIdType());
844 args.add(RValue::get(cmd), getContext().getObjCSelType());
845 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall43192862011-09-13 18:31:23 +0000846 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
847 getContext().BoolTy);
John McCallf4528ae2011-09-13 03:34:09 +0000848
Daniel Dunbar1ef73732009-02-03 23:43:59 +0000849 // FIXME: We shouldn't need to get the function info here, the
850 // runtime already should have computed it to build the function.
John McCalla729c622012-02-17 03:33:10 +0000851 RValue RV = EmitCall(getTypes().arrangeFunctionCall(propType, args,
852 FunctionType::ExtInfo(),
853 RequiredArgs::All),
John McCallf4528ae2011-09-13 03:34:09 +0000854 getPropertyFn, ReturnValueSlot(), args);
855
Daniel Dunbara08dff12008-09-24 04:04:31 +0000856 // We need to fix the type here. Ivars with copy & retain are
857 // always objects so we don't need to worry about complex or
858 // aggregates.
Mike Stump11289f42009-09-09 15:08:12 +0000859 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
John McCallf4528ae2011-09-13 03:34:09 +0000860 getTypes().ConvertType(propType)));
861
862 EmitReturnOfRValue(RV, propType);
John McCall31168b02011-06-15 23:02:42 +0000863
864 // objc_getProperty does an autorelease, so we should suppress ours.
865 AutoreleaseResult = false;
John McCall31168b02011-06-15 23:02:42 +0000866
John McCallf4528ae2011-09-13 03:34:09 +0000867 return;
868 }
869
870 case PropertyImplStrategy::CopyStruct:
871 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
872 strategy.hasStrongMember());
873 return;
874
875 case PropertyImplStrategy::Expression:
876 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
877 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
878
879 QualType ivarType = ivar->getType();
880 if (ivarType->isAnyComplexType()) {
881 ComplexPairTy pair = LoadComplexFromAddr(LV.getAddress(),
882 LV.isVolatileQualified());
883 StoreComplexToAddr(pair, ReturnValue, LV.isVolatileQualified());
884 } else if (hasAggregateLLVMType(ivarType)) {
885 // The return value slot is guaranteed to not be aliased, but
886 // that's not necessarily the same as "on the stack", so
887 // we still potentially need objc_memmove_collectable.
888 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
889 } else {
John McCall24fada12011-07-22 05:23:13 +0000890 llvm::Value *value;
891 if (propType->isReferenceType()) {
892 value = LV.getAddress();
893 } else {
894 // We want to load and autoreleaseReturnValue ARC __weak ivars.
895 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCallf4528ae2011-09-13 03:34:09 +0000896 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
John McCall24fada12011-07-22 05:23:13 +0000897
898 // Otherwise we want to do a simple load, suppressing the
899 // final autorelease.
John McCall31168b02011-06-15 23:02:42 +0000900 } else {
John McCall24fada12011-07-22 05:23:13 +0000901 value = EmitLoadOfLValue(LV).getScalarVal();
902 AutoreleaseResult = false;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +0000903 }
John McCall31168b02011-06-15 23:02:42 +0000904
John McCall24fada12011-07-22 05:23:13 +0000905 value = Builder.CreateBitCast(value, ConvertType(propType));
906 }
907
908 EmitReturnOfRValue(RValue::get(value), propType);
Fariborz Jahanianeab5ecd2009-03-03 18:49:40 +0000909 }
John McCallf4528ae2011-09-13 03:34:09 +0000910 return;
Daniel Dunbara08dff12008-09-24 04:04:31 +0000911 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000912
John McCallf4528ae2011-09-13 03:34:09 +0000913 }
914 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000915}
916
John McCallb923ece2011-09-12 23:06:44 +0000917/// emitStructSetterCall - Call the runtime function to store the value
918/// from the first formal parameter into the given ivar.
919static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
920 ObjCIvarDecl *ivar) {
Fariborz Jahanian302a3d42011-02-18 19:15:13 +0000921 // objc_copyStruct (&structIvar, &Arg,
922 // sizeof (struct something), true, false);
John McCall6acaef92011-09-10 09:30:49 +0000923 CallArgList args;
924
925 // The first argument is the address of the ivar.
John McCallb923ece2011-09-12 23:06:44 +0000926 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
927 CGF.LoadObjCSelf(), ivar, 0)
928 .getAddress();
929 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
930 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +0000931
932 // The second argument is the address of the parameter variable.
John McCallb923ece2011-09-12 23:06:44 +0000933 ParmVarDecl *argVar = *OMD->param_begin();
John McCall113bee02012-03-10 09:33:50 +0000934 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanian088f1bc2012-01-05 00:10:16 +0000935 VK_LValue, SourceLocation());
John McCallb923ece2011-09-12 23:06:44 +0000936 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
937 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
938 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +0000939
940 // The third argument is the sizeof the type.
941 llvm::Value *size =
John McCallb923ece2011-09-12 23:06:44 +0000942 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
943 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCall6acaef92011-09-10 09:30:49 +0000944
John McCallb923ece2011-09-12 23:06:44 +0000945 // The fourth argument is the 'isAtomic' flag.
946 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCall6acaef92011-09-10 09:30:49 +0000947
John McCallb923ece2011-09-12 23:06:44 +0000948 // The fifth argument is the 'hasStrong' flag.
949 // FIXME: should this really always be false?
950 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
951
952 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCalla729c622012-02-17 03:33:10 +0000953 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy, args,
954 FunctionType::ExtInfo(),
955 RequiredArgs::All),
John McCallb923ece2011-09-12 23:06:44 +0000956 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian302a3d42011-02-18 19:15:13 +0000957}
958
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +0000959/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
960/// the value from the first formal parameter into the given ivar, using
961/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
962static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
963 ObjCMethodDecl *OMD,
964 ObjCIvarDecl *ivar,
965 llvm::Constant *AtomicHelperFn) {
966 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
967 // AtomicHelperFn);
968 CallArgList args;
969
970 // The first argument is the address of the ivar.
971 llvm::Value *ivarAddr =
972 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
973 CGF.LoadObjCSelf(), ivar, 0).getAddress();
974 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
975 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
976
977 // The second argument is the address of the parameter variable.
978 ParmVarDecl *argVar = *OMD->param_begin();
John McCall113bee02012-03-10 09:33:50 +0000979 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +0000980 VK_LValue, SourceLocation());
981 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
982 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
983 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
984
985 // Third argument is the helper function.
986 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
987
988 llvm::Value *copyCppAtomicObjectFn =
989 CGF.CGM.getObjCRuntime().GetCppAtomicObjectFunction();
John McCalla729c622012-02-17 03:33:10 +0000990 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy, args,
991 FunctionType::ExtInfo(),
992 RequiredArgs::All),
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +0000993 copyCppAtomicObjectFn, ReturnValueSlot(), args);
994
995
996}
997
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000998
John McCallf4528ae2011-09-13 03:34:09 +0000999static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1000 Expr *setter = PID->getSetterCXXAssignment();
1001 if (!setter) return true;
1002
1003 // Sema only makes only of these when the ivar has a C++ class type,
1004 // so the form is pretty constrained.
John McCall7f16c422011-09-10 09:17:20 +00001005
1006 // An operator call is trivial if the function it calls is trivial.
John McCallf4528ae2011-09-13 03:34:09 +00001007 // This also implies that there's nothing non-trivial going on with
1008 // the arguments, because operator= can only be trivial if it's a
1009 // synthesized assignment operator and therefore both parameters are
1010 // references.
1011 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall7f16c422011-09-10 09:17:20 +00001012 if (const FunctionDecl *callee
1013 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1014 if (callee->isTrivial())
1015 return true;
1016 return false;
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001017 }
John McCall7f16c422011-09-10 09:17:20 +00001018
John McCallf4528ae2011-09-13 03:34:09 +00001019 assert(isa<ExprWithCleanups>(setter));
John McCall7f16c422011-09-10 09:17:20 +00001020 return false;
1021}
1022
Ted Kremeneke65b0862012-03-06 20:05:56 +00001023bool UseOptimizedSetter(CodeGenModule &CGM) {
1024 if (CGM.getLangOptions().getGC() != LangOptions::NonGC)
1025 return false;
1026 const TargetInfo &Target = CGM.getContext().getTargetInfo();
1027 StringRef TargetPlatform = Target.getPlatformName();
1028 if (TargetPlatform.empty())
1029 return false;
1030 VersionTuple TargetMinVersion = Target.getPlatformMinVersion();
1031
1032 if (TargetPlatform.compare("macosx") ||
1033 TargetMinVersion.getMajor() <= 9)
1034 return false;
1035
1036 unsigned minor = 0;
1037 if (llvm::Optional<unsigned> Minor = TargetMinVersion.getMinor())
1038 minor = *Minor;
1039
1040 return (minor >= 8);
1041}
1042
John McCall7f16c422011-09-10 09:17:20 +00001043void
1044CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001045 const ObjCPropertyImplDecl *propImpl,
1046 llvm::Constant *AtomicHelperFn) {
John McCall7f16c422011-09-10 09:17:20 +00001047 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00001048 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall7f16c422011-09-10 09:17:20 +00001049 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fariborz Jahanian7ff610b2012-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 McCall7f16c422011-09-10 09:17:20 +00001063
John McCallf4528ae2011-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 McCall7f16c422011-09-10 09:17:20 +00001068
John McCallf4528ae2011-09-13 03:34:09 +00001069 LValue ivarLValue =
1070 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1071 llvm::Value *ivarAddr = ivarLValue.getAddress();
John McCall7f16c422011-09-10 09:17:20 +00001072
John McCallf4528ae2011-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 Kremeneke65b0862012-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 =
1102 CGM.getObjCRuntime().GetOptimizedPropertySetFunction(strategy.isAtomic(),
1103 strategy.isCopy());
1104 if (!setOptimizedPropertyFn) {
1105 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1106 return;
1107 }
John McCall7f16c422011-09-10 09:17:20 +00001108 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001109 else {
1110 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1111 if (!setPropertyFn) {
1112 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1113 return;
1114 }
1115 }
1116
John McCall7f16c422011-09-10 09:17:20 +00001117 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1118 // <is-atomic>, <is-copy>).
1119 llvm::Value *cmd =
1120 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
1121 llvm::Value *self =
1122 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1123 llvm::Value *ivarOffset =
1124 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1125 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
1126 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
1127
1128 CallArgList args;
1129 args.add(RValue::get(self), getContext().getObjCIdType());
1130 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001131 if (setOptimizedPropertyFn) {
1132 args.add(RValue::get(arg), getContext().getObjCIdType());
1133 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1134 EmitCall(getTypes().arrangeFunctionCall(getContext().VoidTy, args,
1135 FunctionType::ExtInfo(),
1136 RequiredArgs::All),
1137 setOptimizedPropertyFn, ReturnValueSlot(), args);
1138 } else {
1139 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1140 args.add(RValue::get(arg), getContext().getObjCIdType());
1141 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1142 getContext().BoolTy);
1143 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1144 getContext().BoolTy);
1145 // FIXME: We shouldn't need to get the function info here, the runtime
1146 // already should have computed it to build the function.
1147 EmitCall(getTypes().arrangeFunctionCall(getContext().VoidTy, args,
1148 FunctionType::ExtInfo(),
1149 RequiredArgs::All),
1150 setPropertyFn, ReturnValueSlot(), args);
1151 }
1152
John McCall7f16c422011-09-10 09:17:20 +00001153 return;
1154 }
1155
John McCallf4528ae2011-09-13 03:34:09 +00001156 case PropertyImplStrategy::CopyStruct:
John McCallb923ece2011-09-12 23:06:44 +00001157 emitStructSetterCall(*this, setterMethod, ivar);
John McCall7f16c422011-09-10 09:17:20 +00001158 return;
John McCallf4528ae2011-09-13 03:34:09 +00001159
1160 case PropertyImplStrategy::Expression:
1161 break;
John McCall7f16c422011-09-10 09:17:20 +00001162 }
1163
1164 // Otherwise, fake up some ASTs and emit a normal assignment.
1165 ValueDecl *selfDecl = setterMethod->getSelfDecl();
John McCall113bee02012-03-10 09:33:50 +00001166 DeclRefExpr self(selfDecl, false, selfDecl->getType(),
1167 VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001168 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1169 selfDecl->getType(), CK_LValueToRValue, &self,
1170 VK_RValue);
1171 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
1172 SourceLocation(), &selfLoad, true, true);
1173
1174 ParmVarDecl *argDecl = *setterMethod->param_begin();
1175 QualType argType = argDecl->getType().getNonReferenceType();
John McCall113bee02012-03-10 09:33:50 +00001176 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001177 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1178 argType.getUnqualifiedType(), CK_LValueToRValue,
1179 &arg, VK_RValue);
1180
1181 // The property type can differ from the ivar type in some situations with
1182 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1183 // The following absurdity is just to ensure well-formed IR.
1184 CastKind argCK = CK_NoOp;
1185 if (ivarRef.getType()->isObjCObjectPointerType()) {
1186 if (argLoad.getType()->isObjCObjectPointerType())
1187 argCK = CK_BitCast;
1188 else if (argLoad.getType()->isBlockPointerType())
1189 argCK = CK_BlockPointerToObjCPointerCast;
1190 else
1191 argCK = CK_CPointerToObjCPointerCast;
1192 } else if (ivarRef.getType()->isBlockPointerType()) {
1193 if (argLoad.getType()->isBlockPointerType())
1194 argCK = CK_BitCast;
1195 else
1196 argCK = CK_AnyPointerToBlockPointerCast;
1197 } else if (ivarRef.getType()->isPointerType()) {
1198 argCK = CK_BitCast;
1199 }
1200 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1201 ivarRef.getType(), argCK, &argLoad,
1202 VK_RValue);
1203 Expr *finalArg = &argLoad;
1204 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1205 argLoad.getType()))
1206 finalArg = &argCast;
1207
1208
1209 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1210 ivarRef.getType(), VK_RValue, OK_Ordinary,
1211 SourceLocation());
1212 EmitStmt(&assign);
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001213}
1214
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001215/// GenerateObjCSetter - Generate an Objective-C property setter
Steve Naroff5a7dd782009-01-10 22:55:25 +00001216/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
1217/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001218void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1219 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanian4b501a22012-01-07 18:56:22 +00001220 llvm::Constant *AtomicHelperFn =
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001221 GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001222 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1223 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1224 assert(OMD && "Invalid call to generate setter (empty method)");
Devang Patele7ce5402011-05-19 23:37:41 +00001225 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Daniel Dunbar5449ce52008-09-24 06:32:09 +00001226
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001227 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001228
1229 FinishFunction();
Chris Lattner5696e7b2008-06-17 18:05:57 +00001230}
1231
John McCall6a4fa522011-03-22 07:05:39 +00001232namespace {
John McCall4bd0fb12011-07-12 16:41:08 +00001233 struct DestroyIvar : EHScopeStack::Cleanup {
1234 private:
1235 llvm::Value *addr;
John McCall6a4fa522011-03-22 07:05:39 +00001236 const ObjCIvarDecl *ivar;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001237 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001238 bool useEHCleanupForArray;
1239 public:
1240 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1241 CodeGenFunction::Destroyer *destroyer,
1242 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001243 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001244 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall6a4fa522011-03-22 07:05:39 +00001245
John McCall30317fd2011-07-12 20:27:29 +00001246 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall4bd0fb12011-07-12 16:41:08 +00001247 LValue lvalue
1248 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1249 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001250 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall6a4fa522011-03-22 07:05:39 +00001251 }
1252 };
1253}
1254
John McCall4bd0fb12011-07-12 16:41:08 +00001255/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1256static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1257 llvm::Value *addr,
1258 QualType type) {
1259 llvm::Value *null = getNullForVariable(addr);
1260 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1261}
John McCall31168b02011-06-15 23:02:42 +00001262
John McCall6a4fa522011-03-22 07:05:39 +00001263static void emitCXXDestructMethod(CodeGenFunction &CGF,
1264 ObjCImplementationDecl *impl) {
1265 CodeGenFunction::RunCleanupsScope scope(CGF);
1266
1267 llvm::Value *self = CGF.LoadObjCSelf();
1268
Jordy Rosea91768e2011-07-22 02:08:32 +00001269 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1270 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00001271 ivar; ivar = ivar->getNextIvar()) {
1272 QualType type = ivar->getType();
1273
John McCall6a4fa522011-03-22 07:05:39 +00001274 // Check whether the ivar is a destructible type.
John McCall4bd0fb12011-07-12 16:41:08 +00001275 QualType::DestructionKind dtorKind = type.isDestructedType();
1276 if (!dtorKind) continue;
John McCall6a4fa522011-03-22 07:05:39 +00001277
John McCall4bd0fb12011-07-12 16:41:08 +00001278 CodeGenFunction::Destroyer *destroyer = 0;
John McCall6a4fa522011-03-22 07:05:39 +00001279
John McCall4bd0fb12011-07-12 16:41:08 +00001280 // Use a call to objc_storeStrong to destroy strong ivars, for the
1281 // general benefit of the tools.
1282 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001283 destroyer = destroyARCStrongWithStore;
John McCall31168b02011-06-15 23:02:42 +00001284
John McCall4bd0fb12011-07-12 16:41:08 +00001285 // Otherwise use the default for the destruction kind.
1286 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001287 destroyer = CGF.getDestroyer(dtorKind);
John McCall6a4fa522011-03-22 07:05:39 +00001288 }
John McCall4bd0fb12011-07-12 16:41:08 +00001289
1290 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1291
1292 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1293 cleanupKind & EHCleanup);
John McCall6a4fa522011-03-22 07:05:39 +00001294 }
1295
1296 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1297}
1298
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001299void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1300 ObjCMethodDecl *MD,
1301 bool ctor) {
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001302 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Devang Patele7ce5402011-05-19 23:37:41 +00001303 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
John McCall6a4fa522011-03-22 07:05:39 +00001304
1305 // Emit .cxx_construct.
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001306 if (ctor) {
John McCall31168b02011-06-15 23:02:42 +00001307 // Suppress the final autorelease in ARC.
1308 AutoreleaseResult = false;
1309
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001310 SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
John McCall6a4fa522011-03-22 07:05:39 +00001311 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
1312 E = IMP->init_end(); B != E; ++B) {
1313 CXXCtorInitializer *IvarInit = (*B);
Francois Pichetd583da02010-12-04 09:14:42 +00001314 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001315 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian499b9022010-04-28 22:30:33 +00001316 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1317 LoadObjCSelf(), Ivar, 0);
John McCall8d6fc952011-08-25 20:40:09 +00001318 EmitAggExpr(IvarInit->getInit(),
1319 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001320 AggValueSlot::DoesNotNeedGCBarriers,
1321 AggValueSlot::IsNotAliased));
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001322 }
1323 // constructor returns 'self'.
1324 CodeGenTypes &Types = CGM.getTypes();
1325 QualType IdTy(CGM.getContext().getObjCIdType());
1326 llvm::Value *SelfAsId =
1327 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1328 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCall6a4fa522011-03-22 07:05:39 +00001329
1330 // Emit .cxx_destruct.
Chandler Carruthf3983652010-05-06 00:20:39 +00001331 } else {
John McCall6a4fa522011-03-22 07:05:39 +00001332 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001333 }
1334 FinishFunction();
1335}
1336
Fariborz Jahanian08b0f662010-04-13 00:38:05 +00001337bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1338 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1339 it++; it++;
1340 const ABIArgInfo &AI = it->info;
1341 // FIXME. Is this sufficient check?
1342 return (AI.getKind() == ABIArgInfo::Indirect);
1343}
1344
Fariborz Jahanian7e9d52a2010-04-13 18:32:24 +00001345bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
Douglas Gregor79a91412011-09-13 17:21:33 +00001346 if (CGM.getLangOptions().getGC() == LangOptions::NonGC)
Fariborz Jahanian7e9d52a2010-04-13 18:32:24 +00001347 return false;
1348 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1349 return FDTTy->getDecl()->hasObjectMember();
1350 return false;
1351}
1352
Daniel Dunbara08dff12008-09-24 04:04:31 +00001353llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001354 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1355 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner5696e7b2008-06-17 18:05:57 +00001356}
1357
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001358QualType CodeGenFunction::TypeOfSelfObject() {
1359 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1360 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001361 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1362 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001363 return PTy->getPointeeType();
1364}
1365
Chris Lattnerd4808922009-03-22 21:03:39 +00001366void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump11289f42009-09-09 15:08:12 +00001367 llvm::Constant *EnumerationMutationFn =
Daniel Dunbara08dff12008-09-24 04:04:31 +00001368 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001369
Daniel Dunbara08dff12008-09-24 04:04:31 +00001370 if (!EnumerationMutationFn) {
1371 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1372 return;
1373 }
1374
Devang Pateld2d66652011-01-19 01:36:36 +00001375 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001376 if (DI)
1377 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Pateld2d66652011-01-19 01:36:36 +00001378
Devang Patel297207f2011-06-13 23:15:32 +00001379 // The local variable comes into scope immediately.
1380 AutoVarEmission variable = AutoVarEmission::invalid();
1381 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1382 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1383
John McCall1c926b72011-01-07 01:49:06 +00001384 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump11289f42009-09-09 15:08:12 +00001385
Anders Carlsson75658592008-08-31 02:33:12 +00001386 // Fast enumeration state.
Douglas Gregor636e2002011-08-09 17:23:49 +00001387 QualType StateTy = CGM.getObjCFastEnumerationStateType();
Daniel Dunbara7566f12010-02-09 02:48:28 +00001388 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlssonc0964b62010-05-22 17:35:42 +00001389 EmitNullInitialization(StatePtr, StateTy);
Mike Stump11289f42009-09-09 15:08:12 +00001390
Anders Carlsson75658592008-08-31 02:33:12 +00001391 // Number of elements in the items array.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001392 static const unsigned NumItems = 16;
Mike Stump11289f42009-09-09 15:08:12 +00001393
John McCall1c926b72011-01-07 01:49:06 +00001394 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramer9e649c32010-03-30 11:36:44 +00001395 IdentifierInfo *II[] = {
1396 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1397 &CGM.getContext().Idents.get("objects"),
1398 &CGM.getContext().Idents.get("count")
1399 };
1400 Selector FastEnumSel =
1401 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlsson75658592008-08-31 02:33:12 +00001402
1403 QualType ItemsTy =
1404 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00001405 llvm::APInt(32, NumItems),
Anders Carlsson75658592008-08-31 02:33:12 +00001406 ArrayType::Normal, 0);
Daniel Dunbara7566f12010-02-09 02:48:28 +00001407 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001408
John McCall53848232011-07-27 01:07:15 +00001409 // Emit the collection pointer. In ARC, we do a retain.
1410 llvm::Value *Collection;
1411 if (getLangOptions().ObjCAutoRefCount) {
1412 Collection = EmitARCRetainScalarExpr(S.getCollection());
1413
1414 // Enter a cleanup to do the release.
1415 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1416 } else {
1417 Collection = EmitScalarExpr(S.getCollection());
1418 }
Mike Stump11289f42009-09-09 15:08:12 +00001419
John McCall91e82dd2011-08-05 00:14:38 +00001420 // The 'continue' label needs to appear within the cleanup for the
1421 // collection object.
1422 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1423
John McCall1c926b72011-01-07 01:49:06 +00001424 // Send it our message:
Anders Carlsson75658592008-08-31 02:33:12 +00001425 CallArgList Args;
John McCall1c926b72011-01-07 01:49:06 +00001426
1427 // The first argument is a temporary of the enumeration-state type.
Eli Friedman43dca6a2011-05-02 17:57:46 +00001428 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump11289f42009-09-09 15:08:12 +00001429
John McCall1c926b72011-01-07 01:49:06 +00001430 // The second argument is a temporary array with space for NumItems
1431 // pointers. We'll actually be loading elements from the array
1432 // pointer written into the control state; this buffer is so that
1433 // collections that *aren't* backed by arrays can still queue up
1434 // batches of elements.
Eli Friedman43dca6a2011-05-02 17:57:46 +00001435 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump11289f42009-09-09 15:08:12 +00001436
John McCall1c926b72011-01-07 01:49:06 +00001437 // The third argument is the capacity of that temporary array.
Chris Lattner2192fe52011-07-18 04:24:23 +00001438 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001439 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001440 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump11289f42009-09-09 15:08:12 +00001441
John McCall1c926b72011-01-07 01:49:06 +00001442 // Start the enumeration.
Mike Stump11289f42009-09-09 15:08:12 +00001443 RValue CountRV =
John McCall78a15112010-05-22 01:48:05 +00001444 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlsson75658592008-08-31 02:33:12 +00001445 getContext().UnsignedLongTy,
1446 FastEnumSel,
David Chisnall01aa4672010-04-28 19:33:36 +00001447 Collection, Args);
Anders Carlsson75658592008-08-31 02:33:12 +00001448
John McCall1c926b72011-01-07 01:49:06 +00001449 // The initial number of objects that were returned in the buffer.
1450 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump11289f42009-09-09 15:08:12 +00001451
John McCall1c926b72011-01-07 01:49:06 +00001452 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1453 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump11289f42009-09-09 15:08:12 +00001454
John McCall1c926b72011-01-07 01:49:06 +00001455 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlsson75658592008-08-31 02:33:12 +00001456
John McCall1c926b72011-01-07 01:49:06 +00001457 // If the limit pointer was zero to begin with, the collection is
1458 // empty; skip all this.
1459 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1460 EmptyBB, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001461
John McCall1c926b72011-01-07 01:49:06 +00001462 // Otherwise, initialize the loop.
1463 EmitBlock(LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001464
John McCall1c926b72011-01-07 01:49:06 +00001465 // Save the initial mutations value. This is the value at an
1466 // address that was written into the state object by
1467 // countByEnumeratingWithState:objects:count:.
Mike Stump11289f42009-09-09 15:08:12 +00001468 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson3f35a262008-08-31 04:05:03 +00001469 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001470 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson3f35a262008-08-31 04:05:03 +00001471 "mutationsptr");
Mike Stump11289f42009-09-09 15:08:12 +00001472
John McCall1c926b72011-01-07 01:49:06 +00001473 llvm::Value *initialMutations =
1474 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump11289f42009-09-09 15:08:12 +00001475
John McCall1c926b72011-01-07 01:49:06 +00001476 // Start looping. This is the point we return to whenever we have a
1477 // fresh, non-empty batch of objects.
1478 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1479 EmitBlock(LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001480
John McCall1c926b72011-01-07 01:49:06 +00001481 // The current index into the buffer.
Jay Foad20c0f022011-03-30 11:28:58 +00001482 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCall1c926b72011-01-07 01:49:06 +00001483 index->addIncoming(zero, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001484
John McCall1c926b72011-01-07 01:49:06 +00001485 // The current buffer size.
Jay Foad20c0f022011-03-30 11:28:58 +00001486 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCall1c926b72011-01-07 01:49:06 +00001487 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001488
John McCall1c926b72011-01-07 01:49:06 +00001489 // Check whether the mutations value has changed from where it was
1490 // at start. StateMutationsPtr should actually be invariant between
1491 // refreshes.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001492 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCall1c926b72011-01-07 01:49:06 +00001493 llvm::Value *currentMutations
1494 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001495
John McCall1c926b72011-01-07 01:49:06 +00001496 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman6ca99822011-03-02 22:39:34 +00001497 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump11289f42009-09-09 15:08:12 +00001498
John McCall1c926b72011-01-07 01:49:06 +00001499 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1500 WasNotMutatedBB, WasMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001501
John McCall1c926b72011-01-07 01:49:06 +00001502 // If so, call the enumeration-mutation function.
1503 EmitBlock(WasMutatedBB);
Anders Carlsson3f35a262008-08-31 04:05:03 +00001504 llvm::Value *V =
Mike Stump11289f42009-09-09 15:08:12 +00001505 Builder.CreateBitCast(Collection,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001506 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar84388bf2009-02-03 23:55:40 +00001507 CallArgList Args2;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001508 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stump18bb9282009-05-16 07:57:57 +00001509 // FIXME: We shouldn't need to get the function info here, the runtime already
1510 // should have computed it to build the function.
John McCalla729c622012-02-17 03:33:10 +00001511 EmitCall(CGM.getTypes().arrangeFunctionCall(getContext().VoidTy, Args2,
1512 FunctionType::ExtInfo(),
1513 RequiredArgs::All),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001514 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump11289f42009-09-09 15:08:12 +00001515
John McCall1c926b72011-01-07 01:49:06 +00001516 // Otherwise, or if the mutation function returns, just continue.
1517 EmitBlock(WasNotMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001518
John McCall1c926b72011-01-07 01:49:06 +00001519 // Initialize the element variable.
1520 RunCleanupsScope elementVariableScope(*this);
John McCall9e2e22f2011-02-22 07:16:58 +00001521 bool elementIsVariable;
John McCall1c926b72011-01-07 01:49:06 +00001522 LValue elementLValue;
1523 QualType elementType;
1524 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall9e2e22f2011-02-22 07:16:58 +00001525 // Initialize the variable, in case it's a __block variable or something.
1526 EmitAutoVarInit(variable);
John McCall1c926b72011-01-07 01:49:06 +00001527
John McCall9e2e22f2011-02-22 07:16:58 +00001528 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCall113bee02012-03-10 09:33:50 +00001529 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
John McCall1c926b72011-01-07 01:49:06 +00001530 VK_LValue, SourceLocation());
1531 elementLValue = EmitLValue(&tempDRE);
1532 elementType = D->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001533 elementIsVariable = true;
John McCalld4631322011-06-17 06:42:21 +00001534
1535 if (D->isARCPseudoStrong())
1536 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCall1c926b72011-01-07 01:49:06 +00001537 } else {
1538 elementLValue = LValue(); // suppress warning
1539 elementType = cast<Expr>(S.getElement())->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001540 elementIsVariable = false;
John McCall1c926b72011-01-07 01:49:06 +00001541 }
Chris Lattner2192fe52011-07-18 04:24:23 +00001542 llvm::Type *convertedElementType = ConvertType(elementType);
John McCall1c926b72011-01-07 01:49:06 +00001543
1544 // Fetch the buffer out of the enumeration state.
1545 // TODO: this pointer should actually be invariant between
1546 // refreshes, which would help us do certain loop optimizations.
Mike Stump11289f42009-09-09 15:08:12 +00001547 llvm::Value *StateItemsPtr =
Anders Carlsson75658592008-08-31 02:33:12 +00001548 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCall1c926b72011-01-07 01:49:06 +00001549 llvm::Value *EnumStateItems =
1550 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlsson75658592008-08-31 02:33:12 +00001551
John McCall1c926b72011-01-07 01:49:06 +00001552 // Fetch the value at the current index from the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001553 llvm::Value *CurrentItemPtr =
John McCall1c926b72011-01-07 01:49:06 +00001554 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1555 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001556
John McCall1c926b72011-01-07 01:49:06 +00001557 // Cast that value to the right type.
1558 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1559 "currentitem");
Mike Stump11289f42009-09-09 15:08:12 +00001560
John McCall1c926b72011-01-07 01:49:06 +00001561 // Make sure we have an l-value. Yes, this gets evaluated every
1562 // time through the loop.
John McCalld4631322011-06-17 06:42:21 +00001563 if (!elementIsVariable) {
John McCall1c926b72011-01-07 01:49:06 +00001564 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001565 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCalld4631322011-06-17 06:42:21 +00001566 } else {
1567 EmitScalarInit(CurrentItem, elementLValue);
1568 }
Mike Stump11289f42009-09-09 15:08:12 +00001569
John McCall9e2e22f2011-02-22 07:16:58 +00001570 // If we do have an element variable, this assignment is the end of
1571 // its initialization.
1572 if (elementIsVariable)
1573 EmitAutoVarCleanups(variable);
1574
John McCall1c926b72011-01-07 01:49:06 +00001575 // Perform the loop body, setting up break and continue labels.
Anders Carlsson33747b62009-02-10 05:52:02 +00001576 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCall1c926b72011-01-07 01:49:06 +00001577 {
1578 RunCleanupsScope Scope(*this);
1579 EmitStmt(S.getBody());
1580 }
Anders Carlsson75658592008-08-31 02:33:12 +00001581 BreakContinueStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00001582
John McCall1c926b72011-01-07 01:49:06 +00001583 // Destroy the element variable now.
1584 elementVariableScope.ForceCleanup();
1585
1586 // Check whether there are more elements.
John McCallad5d61e2010-07-23 21:56:41 +00001587 EmitBlock(AfterBody.getBlock());
Mike Stump11289f42009-09-09 15:08:12 +00001588
John McCall1c926b72011-01-07 01:49:06 +00001589 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanian6e7ecc82009-01-06 18:56:31 +00001590
John McCall1c926b72011-01-07 01:49:06 +00001591 // First we check in the local buffer.
1592 llvm::Value *indexPlusOne
1593 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlsson75658592008-08-31 02:33:12 +00001594
John McCall1c926b72011-01-07 01:49:06 +00001595 // If we haven't overrun the buffer yet, we can continue.
1596 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1597 LoopBodyBB, FetchMoreBB);
1598
1599 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1600 count->addIncoming(count, AfterBody.getBlock());
1601
1602 // Otherwise, we have to fetch more elements.
1603 EmitBlock(FetchMoreBB);
Mike Stump11289f42009-09-09 15:08:12 +00001604
1605 CountRV =
John McCall78a15112010-05-22 01:48:05 +00001606 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlsson75658592008-08-31 02:33:12 +00001607 getContext().UnsignedLongTy,
Mike Stump11289f42009-09-09 15:08:12 +00001608 FastEnumSel,
David Chisnall01aa4672010-04-28 19:33:36 +00001609 Collection, Args);
Mike Stump11289f42009-09-09 15:08:12 +00001610
John McCall1c926b72011-01-07 01:49:06 +00001611 // If we got a zero count, we're done.
1612 llvm::Value *refetchCount = CountRV.getScalarVal();
1613
1614 // (note that the message send might split FetchMoreBB)
1615 index->addIncoming(zero, Builder.GetInsertBlock());
1616 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1617
1618 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1619 EmptyBB, LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001620
Anders Carlsson75658592008-08-31 02:33:12 +00001621 // No more elements.
John McCall1c926b72011-01-07 01:49:06 +00001622 EmitBlock(EmptyBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001623
John McCall9e2e22f2011-02-22 07:16:58 +00001624 if (!elementIsVariable) {
Anders Carlsson75658592008-08-31 02:33:12 +00001625 // If the element was not a declaration, set it to be null.
1626
John McCall1c926b72011-01-07 01:49:06 +00001627 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1628 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001629 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlsson75658592008-08-31 02:33:12 +00001630 }
1631
Eric Christopher7cdf9482011-10-13 21:45:18 +00001632 if (DI)
1633 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Pateld2d66652011-01-19 01:36:36 +00001634
John McCall53848232011-07-27 01:07:15 +00001635 // Leave the cleanup we entered in ARC.
1636 if (getLangOptions().ObjCAutoRefCount)
1637 PopCleanupBlock();
1638
John McCallad5d61e2010-07-23 21:56:41 +00001639 EmitBlock(LoopEnd.getBlock());
Anders Carlsson2e744e82008-08-30 19:51:14 +00001640}
1641
Mike Stump11289f42009-09-09 15:08:12 +00001642void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001643 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001644}
1645
Mike Stump11289f42009-09-09 15:08:12 +00001646void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001647 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1648}
1649
Chris Lattnere132e242008-11-15 21:26:17 +00001650void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump11289f42009-09-09 15:08:12 +00001651 const ObjCAtSynchronizedStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001652 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattnere132e242008-11-15 21:26:17 +00001653}
1654
John McCall2d637d22011-09-10 06:18:15 +00001655/// Produce the code for a CK_ARCProduceObject. Just does a
John McCall31168b02011-06-15 23:02:42 +00001656/// primitive retain.
1657llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1658 llvm::Value *value) {
1659 return EmitARCRetain(type, value);
1660}
1661
1662namespace {
1663 struct CallObjCRelease : EHScopeStack::Cleanup {
John McCall9c8e1c92011-08-03 22:24:24 +00001664 CallObjCRelease(llvm::Value *object) : object(object) {}
1665 llvm::Value *object;
John McCall31168b02011-06-15 23:02:42 +00001666
John McCall30317fd2011-07-12 20:27:29 +00001667 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall31168b02011-06-15 23:02:42 +00001668 CGF.EmitARCRelease(object, /*precise*/ true);
John McCall31168b02011-06-15 23:02:42 +00001669 }
1670 };
1671}
1672
John McCall2d637d22011-09-10 06:18:15 +00001673/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCall31168b02011-06-15 23:02:42 +00001674/// release at the end of the full-expression.
1675llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1676 llvm::Value *object) {
1677 // If we're in a conditional branch, we need to make the cleanup
John McCall9c8e1c92011-08-03 22:24:24 +00001678 // conditional.
1679 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCall31168b02011-06-15 23:02:42 +00001680 return object;
1681}
1682
1683llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1684 llvm::Value *value) {
1685 return EmitARCRetainAutorelease(type, value);
1686}
1687
1688
1689static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00001690 llvm::FunctionType *type,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001691 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001692 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1693
1694 // In -fobjc-no-arc-runtime, emit weak references to the runtime
1695 // support library.
John McCall24fc0de2011-07-06 00:26:06 +00001696 if (!CGM.getCodeGenOpts().ObjCRuntimeHasARC)
John McCall31168b02011-06-15 23:02:42 +00001697 if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
1698 f->setLinkage(llvm::Function::ExternalWeakLinkage);
1699
1700 return fn;
1701}
1702
1703/// Perform an operation having the signature
1704/// i8* (i8*)
1705/// where a null input causes a no-op and returns null.
1706static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1707 llvm::Value *value,
1708 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001709 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001710 if (isa<llvm::ConstantPointerNull>(value)) return value;
1711
1712 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001713 std::vector<llvm::Type*> args(1, CGF.Int8PtrTy);
Chris Lattner2192fe52011-07-18 04:24:23 +00001714 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00001715 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1716 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1717 }
1718
1719 // Cast the argument to 'id'.
Chris Lattner2192fe52011-07-18 04:24:23 +00001720 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001721 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1722
1723 // Call the function.
1724 llvm::CallInst *call = CGF.Builder.CreateCall(fn, value);
1725 call->setDoesNotThrow();
1726
1727 // Cast the result back to the original type.
1728 return CGF.Builder.CreateBitCast(call, origType);
1729}
1730
1731/// Perform an operation having the following signature:
1732/// i8* (i8**)
1733static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1734 llvm::Value *addr,
1735 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001736 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001737 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001738 std::vector<llvm::Type*> args(1, CGF.Int8PtrPtrTy);
Chris Lattner2192fe52011-07-18 04:24:23 +00001739 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00001740 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1741 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1742 }
1743
1744 // Cast the argument to 'id*'.
Chris Lattner2192fe52011-07-18 04:24:23 +00001745 llvm::Type *origType = addr->getType();
John McCall31168b02011-06-15 23:02:42 +00001746 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1747
1748 // Call the function.
1749 llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr);
1750 call->setDoesNotThrow();
1751
1752 // Cast the result back to a dereference of the original type.
1753 llvm::Value *result = call;
1754 if (origType != CGF.Int8PtrPtrTy)
1755 result = CGF.Builder.CreateBitCast(result,
1756 cast<llvm::PointerType>(origType)->getElementType());
1757
1758 return result;
1759}
1760
1761/// Perform an operation having the following signature:
1762/// i8* (i8**, i8*)
1763static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1764 llvm::Value *addr,
1765 llvm::Value *value,
1766 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001767 StringRef fnName,
John McCall31168b02011-06-15 23:02:42 +00001768 bool ignored) {
1769 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1770 == value->getType());
1771
1772 if (!fn) {
Benjamin Kramer22d24c22011-10-15 12:20:02 +00001773 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
John McCall31168b02011-06-15 23:02:42 +00001774
Chris Lattner2192fe52011-07-18 04:24:23 +00001775 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001776 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1777 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1778 }
1779
Chris Lattner2192fe52011-07-18 04:24:23 +00001780 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001781
1782 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1783 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1784
1785 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value);
1786 result->setDoesNotThrow();
1787
1788 if (ignored) return 0;
1789
1790 return CGF.Builder.CreateBitCast(result, origType);
1791}
1792
1793/// Perform an operation having the following signature:
1794/// void (i8**, i8**)
1795static void emitARCCopyOperation(CodeGenFunction &CGF,
1796 llvm::Value *dst,
1797 llvm::Value *src,
1798 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001799 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001800 assert(dst->getType() == src->getType());
1801
1802 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001803 std::vector<llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy);
Chris Lattner2192fe52011-07-18 04:24:23 +00001804 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001805 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1806 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1807 }
1808
1809 dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy);
1810 src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy);
1811
1812 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src);
1813 result->setDoesNotThrow();
1814}
1815
1816/// Produce the code to do a retain. Based on the type, calls one of:
1817/// call i8* @objc_retain(i8* %value)
1818/// call i8* @objc_retainBlock(i8* %value)
1819llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1820 if (type->isBlockPointerType())
John McCallff613032011-10-04 06:23:45 +00001821 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCall31168b02011-06-15 23:02:42 +00001822 else
1823 return EmitARCRetainNonBlock(value);
1824}
1825
1826/// Retain the given object, with normal retain semantics.
1827/// call i8* @objc_retain(i8* %value)
1828llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1829 return emitARCValueOperation(*this, value,
1830 CGM.getARCEntrypoints().objc_retain,
1831 "objc_retain");
1832}
1833
1834/// Retain the given block, with _Block_copy semantics.
1835/// call i8* @objc_retainBlock(i8* %value)
John McCallff613032011-10-04 06:23:45 +00001836///
1837/// \param mandatory - If false, emit the call with metadata
1838/// indicating that it's okay for the optimizer to eliminate this call
1839/// if it can prove that the block never escapes except down the stack.
1840llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1841 bool mandatory) {
1842 llvm::Value *result
1843 = emitARCValueOperation(*this, value,
1844 CGM.getARCEntrypoints().objc_retainBlock,
1845 "objc_retainBlock");
1846
1847 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1848 // tell the optimizer that it doesn't need to do this copy if the
1849 // block doesn't escape, where being passed as an argument doesn't
1850 // count as escaping.
1851 if (!mandatory && isa<llvm::Instruction>(result)) {
1852 llvm::CallInst *call
1853 = cast<llvm::CallInst>(result->stripPointerCasts());
1854 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
1855
1856 SmallVector<llvm::Value*,1> args;
1857 call->setMetadata("clang.arc.copy_on_escape",
1858 llvm::MDNode::get(Builder.getContext(), args));
1859 }
1860
1861 return result;
John McCall31168b02011-06-15 23:02:42 +00001862}
1863
1864/// Retain the given object which is the result of a function call.
1865/// call i8* @objc_retainAutoreleasedReturnValue(i8* %value)
1866///
1867/// Yes, this function name is one character away from a different
1868/// call with completely different semantics.
1869llvm::Value *
1870CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1871 // Fetch the void(void) inline asm which marks that we're going to
1872 // retain the autoreleased return value.
1873 llvm::InlineAsm *&marker
1874 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1875 if (!marker) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001876 StringRef assembly
John McCall31168b02011-06-15 23:02:42 +00001877 = CGM.getTargetCodeGenInfo()
1878 .getARCRetainAutoreleasedReturnValueMarker();
1879
1880 // If we have an empty assembly string, there's nothing to do.
1881 if (assembly.empty()) {
1882
1883 // Otherwise, at -O0, build an inline asm that we're going to call
1884 // in a moment.
1885 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1886 llvm::FunctionType *type =
Chris Lattnerece04092012-02-07 00:39:47 +00001887 llvm::FunctionType::get(VoidTy, /*variadic*/false);
John McCall31168b02011-06-15 23:02:42 +00001888
1889 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1890
1891 // If we're at -O1 and above, we don't want to litter the code
1892 // with this marker yet, so leave a breadcrumb for the ARC
1893 // optimizer to pick up.
1894 } else {
1895 llvm::NamedMDNode *metadata =
1896 CGM.getModule().getOrInsertNamedMetadata(
1897 "clang.arc.retainAutoreleasedReturnValueMarker");
1898 assert(metadata->getNumOperands() <= 1);
1899 if (metadata->getNumOperands() == 0) {
1900 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
Jay Foad5709f7c2011-07-29 13:56:53 +00001901 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
John McCall31168b02011-06-15 23:02:42 +00001902 }
1903 }
1904 }
1905
1906 // Call the marker asm if we made one, which we do only at -O0.
1907 if (marker) Builder.CreateCall(marker);
1908
1909 return emitARCValueOperation(*this, value,
1910 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1911 "objc_retainAutoreleasedReturnValue");
1912}
1913
1914/// Release the given object.
1915/// call void @objc_release(i8* %value)
1916void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) {
1917 if (isa<llvm::ConstantPointerNull>(value)) return;
1918
1919 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1920 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001921 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2192fe52011-07-18 04:24:23 +00001922 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00001923 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1924 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1925 }
1926
1927 // Cast the argument to 'id'.
1928 value = Builder.CreateBitCast(value, Int8PtrTy);
1929
1930 // Call objc_release.
1931 llvm::CallInst *call = Builder.CreateCall(fn, value);
1932 call->setDoesNotThrow();
1933
1934 if (!precise) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001935 SmallVector<llvm::Value*,1> args;
John McCall31168b02011-06-15 23:02:42 +00001936 call->setMetadata("clang.imprecise_release",
1937 llvm::MDNode::get(Builder.getContext(), args));
1938 }
1939}
1940
1941/// Store into a strong object. Always calls this:
1942/// call void @objc_storeStrong(i8** %addr, i8* %value)
1943llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
1944 llvm::Value *value,
1945 bool ignored) {
1946 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1947 == value->getType());
1948
1949 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
1950 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001951 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2192fe52011-07-18 04:24:23 +00001952 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001953 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
1954 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
1955 }
1956
1957 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1958 llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy);
1959
1960 Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow();
1961
1962 if (ignored) return 0;
1963 return value;
1964}
1965
1966/// Store into a strong object. Sometimes calls this:
1967/// call void @objc_storeStrong(i8** %addr, i8* %value)
1968/// Other times, breaks it down into components.
John McCall55e1fbc2011-06-25 02:11:03 +00001969llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCall31168b02011-06-15 23:02:42 +00001970 llvm::Value *newValue,
1971 bool ignored) {
John McCall55e1fbc2011-06-25 02:11:03 +00001972 QualType type = dst.getType();
John McCall31168b02011-06-15 23:02:42 +00001973 bool isBlock = type->isBlockPointerType();
1974
1975 // Use a store barrier at -O0 unless this is a block type or the
1976 // lvalue is inadequately aligned.
1977 if (shouldUseFusedARCCalls() &&
1978 !isBlock &&
Eli Friedmana0544d62011-12-03 04:14:32 +00001979 (dst.getAlignment().isZero() ||
1980 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCall31168b02011-06-15 23:02:42 +00001981 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
1982 }
1983
1984 // Otherwise, split it out.
1985
1986 // Retain the new value.
1987 newValue = EmitARCRetain(type, newValue);
1988
1989 // Read the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00001990 llvm::Value *oldValue = EmitLoadOfScalar(dst);
John McCall31168b02011-06-15 23:02:42 +00001991
1992 // Store. We do this before the release so that any deallocs won't
1993 // see the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00001994 EmitStoreOfScalar(newValue, dst);
John McCall31168b02011-06-15 23:02:42 +00001995
1996 // Finally, release the old value.
1997 EmitARCRelease(oldValue, /*precise*/ false);
1998
1999 return newValue;
2000}
2001
2002/// Autorelease the given object.
2003/// call i8* @objc_autorelease(i8* %value)
2004llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2005 return emitARCValueOperation(*this, value,
2006 CGM.getARCEntrypoints().objc_autorelease,
2007 "objc_autorelease");
2008}
2009
2010/// Autorelease the given object.
2011/// call i8* @objc_autoreleaseReturnValue(i8* %value)
2012llvm::Value *
2013CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2014 return emitARCValueOperation(*this, value,
2015 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
2016 "objc_autoreleaseReturnValue");
2017}
2018
2019/// Do a fused retain/autorelease of the given object.
2020/// call i8* @objc_retainAutoreleaseReturnValue(i8* %value)
2021llvm::Value *
2022CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2023 return emitARCValueOperation(*this, value,
2024 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
2025 "objc_retainAutoreleaseReturnValue");
2026}
2027
2028/// Do a fused retain/autorelease of the given object.
2029/// call i8* @objc_retainAutorelease(i8* %value)
2030/// or
2031/// %retain = call i8* @objc_retainBlock(i8* %value)
2032/// call i8* @objc_autorelease(i8* %retain)
2033llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2034 llvm::Value *value) {
2035 if (!type->isBlockPointerType())
2036 return EmitARCRetainAutoreleaseNonBlock(value);
2037
2038 if (isa<llvm::ConstantPointerNull>(value)) return value;
2039
Chris Lattner2192fe52011-07-18 04:24:23 +00002040 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002041 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCallff613032011-10-04 06:23:45 +00002042 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCall31168b02011-06-15 23:02:42 +00002043 value = EmitARCAutorelease(value);
2044 return Builder.CreateBitCast(value, origType);
2045}
2046
2047/// Do a fused retain/autorelease of the given object.
2048/// call i8* @objc_retainAutorelease(i8* %value)
2049llvm::Value *
2050CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2051 return emitARCValueOperation(*this, value,
2052 CGM.getARCEntrypoints().objc_retainAutorelease,
2053 "objc_retainAutorelease");
2054}
2055
2056/// i8* @objc_loadWeak(i8** %addr)
2057/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2058llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
2059 return emitARCLoadOperation(*this, addr,
2060 CGM.getARCEntrypoints().objc_loadWeak,
2061 "objc_loadWeak");
2062}
2063
2064/// i8* @objc_loadWeakRetained(i8** %addr)
2065llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
2066 return emitARCLoadOperation(*this, addr,
2067 CGM.getARCEntrypoints().objc_loadWeakRetained,
2068 "objc_loadWeakRetained");
2069}
2070
2071/// i8* @objc_storeWeak(i8** %addr, i8* %value)
2072/// Returns %value.
2073llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
2074 llvm::Value *value,
2075 bool ignored) {
2076 return emitARCStoreOperation(*this, addr, value,
2077 CGM.getARCEntrypoints().objc_storeWeak,
2078 "objc_storeWeak", ignored);
2079}
2080
2081/// i8* @objc_initWeak(i8** %addr, i8* %value)
2082/// Returns %value. %addr is known to not have a current weak entry.
2083/// Essentially equivalent to:
2084/// *addr = nil; objc_storeWeak(addr, value);
2085void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
2086 // If we're initializing to null, just write null to memory; no need
2087 // to get the runtime involved. But don't do this if optimization
2088 // is enabled, because accounting for this would make the optimizer
2089 // much more complicated.
2090 if (isa<llvm::ConstantPointerNull>(value) &&
2091 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2092 Builder.CreateStore(value, addr);
2093 return;
2094 }
2095
2096 emitARCStoreOperation(*this, addr, value,
2097 CGM.getARCEntrypoints().objc_initWeak,
2098 "objc_initWeak", /*ignored*/ true);
2099}
2100
2101/// void @objc_destroyWeak(i8** %addr)
2102/// Essentially objc_storeWeak(addr, nil).
2103void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
2104 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
2105 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002106 std::vector<llvm::Type*> args(1, Int8PtrPtrTy);
Chris Lattner2192fe52011-07-18 04:24:23 +00002107 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00002108 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
2109 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
2110 }
2111
2112 // Cast the argument to 'id*'.
2113 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2114
2115 llvm::CallInst *call = Builder.CreateCall(fn, addr);
2116 call->setDoesNotThrow();
2117}
2118
2119/// void @objc_moveWeak(i8** %dest, i8** %src)
2120/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2121/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
2122void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
2123 emitARCCopyOperation(*this, dst, src,
2124 CGM.getARCEntrypoints().objc_moveWeak,
2125 "objc_moveWeak");
2126}
2127
2128/// void @objc_copyWeak(i8** %dest, i8** %src)
2129/// Disregards the current value in %dest. Essentially
2130/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
2131void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
2132 emitARCCopyOperation(*this, dst, src,
2133 CGM.getARCEntrypoints().objc_copyWeak,
2134 "objc_copyWeak");
2135}
2136
2137/// Produce the code to do a objc_autoreleasepool_push.
2138/// call i8* @objc_autoreleasePoolPush(void)
2139llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2140 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
2141 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002142 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00002143 llvm::FunctionType::get(Int8PtrTy, false);
2144 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
2145 }
2146
2147 llvm::CallInst *call = Builder.CreateCall(fn);
2148 call->setDoesNotThrow();
2149
2150 return call;
2151}
2152
2153/// Produce the code to do a primitive release.
2154/// call void @objc_autoreleasePoolPop(i8* %ptr)
2155void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2156 assert(value->getType() == Int8PtrTy);
2157
2158 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
2159 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002160 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2192fe52011-07-18 04:24:23 +00002161 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00002162 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
2163
2164 // We don't want to use a weak import here; instead we should not
2165 // fall into this path.
2166 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
2167 }
2168
2169 llvm::CallInst *call = Builder.CreateCall(fn, value);
2170 call->setDoesNotThrow();
2171}
2172
2173/// Produce the code to do an MRR version objc_autoreleasepool_push.
2174/// Which is: [[NSAutoreleasePool alloc] init];
2175/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2176/// init is declared as: - (id) init; in its NSObject super class.
2177///
2178llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2179 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2180 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder);
2181 // [NSAutoreleasePool alloc]
2182 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2183 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2184 CallArgList Args;
2185 RValue AllocRV =
2186 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2187 getContext().getObjCIdType(),
2188 AllocSel, Receiver, Args);
2189
2190 // [Receiver init]
2191 Receiver = AllocRV.getScalarVal();
2192 II = &CGM.getContext().Idents.get("init");
2193 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2194 RValue InitRV =
2195 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2196 getContext().getObjCIdType(),
2197 InitSel, Receiver, Args);
2198 return InitRV.getScalarVal();
2199}
2200
2201/// Produce the code to do a primitive release.
2202/// [tmp drain];
2203void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2204 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2205 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2206 CallArgList Args;
2207 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2208 getContext().VoidTy, DrainSel, Arg, Args);
2209}
2210
John McCall82fe67b2011-07-09 01:37:26 +00002211void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2212 llvm::Value *addr,
2213 QualType type) {
2214 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2215 CGF.EmitARCRelease(ptr, /*precise*/ true);
2216}
2217
2218void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2219 llvm::Value *addr,
2220 QualType type) {
2221 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2222 CGF.EmitARCRelease(ptr, /*precise*/ false);
2223}
2224
2225void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2226 llvm::Value *addr,
2227 QualType type) {
2228 CGF.EmitARCDestroyWeak(addr);
2229}
2230
John McCall31168b02011-06-15 23:02:42 +00002231namespace {
John McCall31168b02011-06-15 23:02:42 +00002232 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2233 llvm::Value *Token;
2234
2235 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2236
John McCall30317fd2011-07-12 20:27:29 +00002237 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall31168b02011-06-15 23:02:42 +00002238 CGF.EmitObjCAutoreleasePoolPop(Token);
2239 }
2240 };
2241 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2242 llvm::Value *Token;
2243
2244 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2245
John McCall30317fd2011-07-12 20:27:29 +00002246 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall31168b02011-06-15 23:02:42 +00002247 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2248 }
2249 };
2250}
2251
2252void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
2253 if (CGM.getLangOptions().ObjCAutoRefCount)
2254 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2255 else
2256 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2257}
2258
John McCall31168b02011-06-15 23:02:42 +00002259static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2260 LValue lvalue,
2261 QualType type) {
2262 switch (type.getObjCLifetime()) {
2263 case Qualifiers::OCL_None:
2264 case Qualifiers::OCL_ExplicitNone:
2265 case Qualifiers::OCL_Strong:
2266 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00002267 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(),
John McCall31168b02011-06-15 23:02:42 +00002268 false);
2269
2270 case Qualifiers::OCL_Weak:
2271 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2272 true);
2273 }
2274
2275 llvm_unreachable("impossible lifetime!");
John McCall31168b02011-06-15 23:02:42 +00002276}
2277
2278static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2279 const Expr *e) {
2280 e = e->IgnoreParens();
2281 QualType type = e->getType();
2282
John McCall154a2fd2011-08-30 00:57:29 +00002283 // If we're loading retained from a __strong xvalue, we can avoid
2284 // an extra retain/release pair by zeroing out the source of this
2285 // "move" operation.
2286 if (e->isXValue() &&
2287 !type.isConstQualified() &&
2288 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2289 // Emit the lvalue.
2290 LValue lv = CGF.EmitLValue(e);
2291
2292 // Load the object pointer.
2293 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal();
2294
2295 // Set the source pointer to NULL.
2296 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2297
2298 return TryEmitResult(result, true);
2299 }
2300
John McCall31168b02011-06-15 23:02:42 +00002301 // As a very special optimization, in ARC++, if the l-value is the
2302 // result of a non-volatile assignment, do a simple retain of the
2303 // result of the call to objc_storeWeak instead of reloading.
2304 if (CGF.getLangOptions().CPlusPlus &&
2305 !type.isVolatileQualified() &&
2306 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2307 isa<BinaryOperator>(e) &&
2308 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2309 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2310
2311 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2312}
2313
2314static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2315 llvm::Value *value);
2316
2317/// Given that the given expression is some sort of call (which does
2318/// not return retained), emit a retain following it.
2319static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2320 llvm::Value *value = CGF.EmitScalarExpr(e);
2321 return emitARCRetainAfterCall(CGF, value);
2322}
2323
2324static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2325 llvm::Value *value) {
2326 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2327 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2328
2329 // Place the retain immediately following the call.
2330 CGF.Builder.SetInsertPoint(call->getParent(),
2331 ++llvm::BasicBlock::iterator(call));
2332 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2333
2334 CGF.Builder.restoreIP(ip);
2335 return value;
2336 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2337 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2338
2339 // Place the retain at the beginning of the normal destination block.
2340 llvm::BasicBlock *BB = invoke->getNormalDest();
2341 CGF.Builder.SetInsertPoint(BB, BB->begin());
2342 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2343
2344 CGF.Builder.restoreIP(ip);
2345 return value;
2346
2347 // Bitcasts can arise because of related-result returns. Rewrite
2348 // the operand.
2349 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2350 llvm::Value *operand = bitcast->getOperand(0);
2351 operand = emitARCRetainAfterCall(CGF, operand);
2352 bitcast->setOperand(0, operand);
2353 return bitcast;
2354
2355 // Generic fall-back case.
2356 } else {
2357 // Retain using the non-block variant: we never need to do a copy
2358 // of a block that's been returned to us.
2359 return CGF.EmitARCRetainNonBlock(value);
2360 }
2361}
2362
John McCallcd78e802011-09-10 01:16:55 +00002363/// Determine whether it might be important to emit a separate
2364/// objc_retain_block on the result of the given expression, or
2365/// whether it's okay to just emit it in a +1 context.
2366static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2367 assert(e->getType()->isBlockPointerType());
2368 e = e->IgnoreParens();
2369
2370 // For future goodness, emit block expressions directly in +1
2371 // contexts if we can.
2372 if (isa<BlockExpr>(e))
2373 return false;
2374
2375 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2376 switch (cast->getCastKind()) {
2377 // Emitting these operations in +1 contexts is goodness.
2378 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00002379 case CK_ARCReclaimReturnedObject:
2380 case CK_ARCConsumeObject:
2381 case CK_ARCProduceObject:
John McCallcd78e802011-09-10 01:16:55 +00002382 return false;
2383
2384 // These operations preserve a block type.
2385 case CK_NoOp:
2386 case CK_BitCast:
2387 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2388
2389 // These operations are known to be bad (or haven't been considered).
2390 case CK_AnyPointerToBlockPointerCast:
2391 default:
2392 return true;
2393 }
2394 }
2395
2396 return true;
2397}
2398
John McCallfe96e0b2011-11-06 09:01:30 +00002399/// Try to emit a PseudoObjectExpr at +1.
2400///
2401/// This massively duplicates emitPseudoObjectRValue.
2402static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
2403 const PseudoObjectExpr *E) {
2404 llvm::SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
2405
2406 // Find the result expression.
2407 const Expr *resultExpr = E->getResultExpr();
2408 assert(resultExpr);
2409 TryEmitResult result;
2410
2411 for (PseudoObjectExpr::const_semantics_iterator
2412 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2413 const Expr *semantic = *i;
2414
2415 // If this semantic expression is an opaque value, bind it
2416 // to the result of its source expression.
2417 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2418 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2419 OVMA opaqueData;
2420
2421 // If this semantic is the result of the pseudo-object
2422 // expression, try to evaluate the source as +1.
2423 if (ov == resultExpr) {
2424 assert(!OVMA::shouldBindAsLValue(ov));
2425 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
2426 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
2427
2428 // Otherwise, just bind it.
2429 } else {
2430 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2431 }
2432 opaques.push_back(opaqueData);
2433
2434 // Otherwise, if the expression is the result, evaluate it
2435 // and remember the result.
2436 } else if (semantic == resultExpr) {
2437 result = tryEmitARCRetainScalarExpr(CGF, semantic);
2438
2439 // Otherwise, evaluate the expression in an ignored context.
2440 } else {
2441 CGF.EmitIgnoredExpr(semantic);
2442 }
2443 }
2444
2445 // Unbind all the opaques now.
2446 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2447 opaques[i].unbind(CGF);
2448
2449 return result;
2450}
2451
John McCall31168b02011-06-15 23:02:42 +00002452static TryEmitResult
2453tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCall53848232011-07-27 01:07:15 +00002454 // Look through cleanups.
2455 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
John McCall08ef4662011-11-10 08:15:53 +00002456 CGF.enterFullExpression(cleanups);
John McCall53848232011-07-27 01:07:15 +00002457 CodeGenFunction::RunCleanupsScope scope(CGF);
2458 return tryEmitARCRetainScalarExpr(CGF, cleanups->getSubExpr());
2459 }
2460
John McCall31168b02011-06-15 23:02:42 +00002461 // The desired result type, if it differs from the type of the
2462 // ultimate opaque expression.
Chris Lattner2192fe52011-07-18 04:24:23 +00002463 llvm::Type *resultType = 0;
John McCall31168b02011-06-15 23:02:42 +00002464
2465 while (true) {
2466 e = e->IgnoreParens();
2467
2468 // There's a break at the end of this if-chain; anything
2469 // that wants to keep looping has to explicitly continue.
2470 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2471 switch (ce->getCastKind()) {
2472 // No-op casts don't change the type, so we just ignore them.
2473 case CK_NoOp:
2474 e = ce->getSubExpr();
2475 continue;
2476
2477 case CK_LValueToRValue: {
2478 TryEmitResult loadResult
2479 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2480 if (resultType) {
2481 llvm::Value *value = loadResult.getPointer();
2482 value = CGF.Builder.CreateBitCast(value, resultType);
2483 loadResult.setPointer(value);
2484 }
2485 return loadResult;
2486 }
2487
2488 // These casts can change the type, so remember that and
2489 // soldier on. We only need to remember the outermost such
2490 // cast, though.
John McCall9320b872011-09-09 05:25:32 +00002491 case CK_CPointerToObjCPointerCast:
2492 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00002493 case CK_AnyPointerToBlockPointerCast:
2494 case CK_BitCast:
2495 if (!resultType)
2496 resultType = CGF.ConvertType(ce->getType());
2497 e = ce->getSubExpr();
2498 assert(e->getType()->hasPointerRepresentation());
2499 continue;
2500
2501 // For consumptions, just emit the subexpression and thus elide
2502 // the retain/release pair.
John McCall2d637d22011-09-10 06:18:15 +00002503 case CK_ARCConsumeObject: {
John McCall31168b02011-06-15 23:02:42 +00002504 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2505 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2506 return TryEmitResult(result, true);
2507 }
2508
John McCallcd78e802011-09-10 01:16:55 +00002509 // Block extends are net +0. Naively, we could just recurse on
2510 // the subexpression, but actually we need to ensure that the
2511 // value is copied as a block, so there's a little filter here.
John McCall2d637d22011-09-10 06:18:15 +00002512 case CK_ARCExtendBlockObject: {
John McCallcd78e802011-09-10 01:16:55 +00002513 llvm::Value *result; // will be a +0 value
2514
2515 // If we can't safely assume the sub-expression will produce a
2516 // block-copied value, emit the sub-expression at +0.
2517 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2518 result = CGF.EmitScalarExpr(ce->getSubExpr());
2519
2520 // Otherwise, try to emit the sub-expression at +1 recursively.
2521 } else {
2522 TryEmitResult subresult
2523 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2524 result = subresult.getPointer();
2525
2526 // If that produced a retained value, just use that,
2527 // possibly casting down.
2528 if (subresult.getInt()) {
2529 if (resultType)
2530 result = CGF.Builder.CreateBitCast(result, resultType);
2531 return TryEmitResult(result, true);
2532 }
2533
2534 // Otherwise it's +0.
2535 }
2536
2537 // Retain the object as a block, then cast down.
John McCallff613032011-10-04 06:23:45 +00002538 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
John McCallcd78e802011-09-10 01:16:55 +00002539 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2540 return TryEmitResult(result, true);
2541 }
2542
John McCall4db5c3c2011-07-07 06:58:02 +00002543 // For reclaims, emit the subexpression as a retained call and
2544 // skip the consumption.
John McCall2d637d22011-09-10 06:18:15 +00002545 case CK_ARCReclaimReturnedObject: {
John McCall4db5c3c2011-07-07 06:58:02 +00002546 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2547 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2548 return TryEmitResult(result, true);
2549 }
2550
John McCall31168b02011-06-15 23:02:42 +00002551 default:
2552 break;
2553 }
2554
2555 // Skip __extension__.
2556 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2557 if (op->getOpcode() == UO_Extension) {
2558 e = op->getSubExpr();
2559 continue;
2560 }
2561
2562 // For calls and message sends, use the retained-call logic.
2563 // Delegate inits are a special case in that they're the only
2564 // returns-retained expression that *isn't* surrounded by
2565 // a consume.
2566 } else if (isa<CallExpr>(e) ||
2567 (isa<ObjCMessageExpr>(e) &&
2568 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2569 llvm::Value *result = emitARCRetainCall(CGF, e);
2570 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2571 return TryEmitResult(result, true);
John McCallfe96e0b2011-11-06 09:01:30 +00002572
2573 // Look through pseudo-object expressions.
2574 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2575 TryEmitResult result
2576 = tryEmitARCRetainPseudoObject(CGF, pseudo);
2577 if (resultType) {
2578 llvm::Value *value = result.getPointer();
2579 value = CGF.Builder.CreateBitCast(value, resultType);
2580 result.setPointer(value);
2581 }
2582 return result;
John McCall31168b02011-06-15 23:02:42 +00002583 }
2584
2585 // Conservatively halt the search at any other expression kind.
2586 break;
2587 }
2588
2589 // We didn't find an obvious production, so emit what we've got and
2590 // tell the caller that we didn't manage to retain.
2591 llvm::Value *result = CGF.EmitScalarExpr(e);
2592 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2593 return TryEmitResult(result, false);
2594}
2595
2596static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2597 LValue lvalue,
2598 QualType type) {
2599 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2600 llvm::Value *value = result.getPointer();
2601 if (!result.getInt())
2602 value = CGF.EmitARCRetain(type, value);
2603 return value;
2604}
2605
2606/// EmitARCRetainScalarExpr - Semantically equivalent to
2607/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2608/// best-effort attempt to peephole expressions that naturally produce
2609/// retained objects.
2610llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
2611 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2612 llvm::Value *value = result.getPointer();
2613 if (!result.getInt())
2614 value = EmitARCRetain(e->getType(), value);
2615 return value;
2616}
2617
2618llvm::Value *
2619CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
2620 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2621 llvm::Value *value = result.getPointer();
2622 if (result.getInt())
2623 value = EmitARCAutorelease(value);
2624 else
2625 value = EmitARCRetainAutorelease(e->getType(), value);
2626 return value;
2627}
2628
John McCallff613032011-10-04 06:23:45 +00002629llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2630 llvm::Value *result;
2631 bool doRetain;
2632
2633 if (shouldEmitSeparateBlockRetain(e)) {
2634 result = EmitScalarExpr(e);
2635 doRetain = true;
2636 } else {
2637 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2638 result = subresult.getPointer();
2639 doRetain = !subresult.getInt();
2640 }
2641
2642 if (doRetain)
2643 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2644 return EmitObjCConsumeObject(e->getType(), result);
2645}
2646
John McCall248512a2011-10-01 10:32:24 +00002647llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2648 // In ARC, retain and autorelease the expression.
2649 if (getLangOptions().ObjCAutoRefCount) {
2650 // Do so before running any cleanups for the full-expression.
2651 // tryEmitARCRetainScalarExpr does make an effort to do things
2652 // inside cleanups, but there are crazy cases like
2653 // @throw A().foo;
2654 // where a full retain+autorelease is required and would
2655 // otherwise happen after the destructor for the temporary.
John McCall08ef4662011-11-10 08:15:53 +00002656 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(expr)) {
2657 enterFullExpression(ewc);
John McCall248512a2011-10-01 10:32:24 +00002658 expr = ewc->getSubExpr();
John McCall08ef4662011-11-10 08:15:53 +00002659 }
John McCall248512a2011-10-01 10:32:24 +00002660
John McCall08ef4662011-11-10 08:15:53 +00002661 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall248512a2011-10-01 10:32:24 +00002662 return EmitARCRetainAutoreleaseScalarExpr(expr);
2663 }
2664
2665 // Otherwise, use the normal scalar-expression emission. The
2666 // exception machinery doesn't do anything special with the
2667 // exception like retaining it, so there's no safety associated with
2668 // only running cleanups after the throw has started, and when it
2669 // matters it tends to be substantially inferior code.
2670 return EmitScalarExpr(expr);
2671}
2672
John McCall31168b02011-06-15 23:02:42 +00002673std::pair<LValue,llvm::Value*>
2674CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2675 bool ignored) {
2676 // Evaluate the RHS first.
2677 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2678 llvm::Value *value = result.getPointer();
2679
John McCallb726a552011-07-28 07:23:35 +00002680 bool hasImmediateRetain = result.getInt();
2681
2682 // If we didn't emit a retained object, and the l-value is of block
2683 // type, then we need to emit the block-retain immediately in case
2684 // it invalidates the l-value.
2685 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCallff613032011-10-04 06:23:45 +00002686 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallb726a552011-07-28 07:23:35 +00002687 hasImmediateRetain = true;
2688 }
2689
John McCall31168b02011-06-15 23:02:42 +00002690 LValue lvalue = EmitLValue(e->getLHS());
2691
2692 // If the RHS was emitted retained, expand this.
John McCallb726a552011-07-28 07:23:35 +00002693 if (hasImmediateRetain) {
John McCall31168b02011-06-15 23:02:42 +00002694 llvm::Value *oldValue =
Eli Friedmana0544d62011-12-03 04:14:32 +00002695 EmitLoadOfScalar(lvalue);
2696 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +00002697 EmitARCRelease(oldValue, /*precise*/ false);
2698 } else {
John McCall55e1fbc2011-06-25 02:11:03 +00002699 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCall31168b02011-06-15 23:02:42 +00002700 }
2701
2702 return std::pair<LValue,llvm::Value*>(lvalue, value);
2703}
2704
2705std::pair<LValue,llvm::Value*>
2706CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2707 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2708 LValue lvalue = EmitLValue(e->getLHS());
2709
Eli Friedmana0544d62011-12-03 04:14:32 +00002710 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +00002711
2712 return std::pair<LValue,llvm::Value*>(lvalue, value);
2713}
2714
2715void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
2716 const ObjCAutoreleasePoolStmt &ARPS) {
2717 const Stmt *subStmt = ARPS.getSubStmt();
2718 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2719
2720 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00002721 if (DI)
2722 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCall31168b02011-06-15 23:02:42 +00002723
2724 // Keep track of the current cleanup stack depth.
2725 RunCleanupsScope Scope(*this);
John McCall24fc0de2011-07-06 00:26:06 +00002726 if (CGM.getCodeGenOpts().ObjCRuntimeHasARC) {
John McCall31168b02011-06-15 23:02:42 +00002727 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2728 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2729 } else {
2730 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2731 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2732 }
2733
2734 for (CompoundStmt::const_body_iterator I = S.body_begin(),
2735 E = S.body_end(); I != E; ++I)
2736 EmitStmt(*I);
2737
Eric Christopher7cdf9482011-10-13 21:45:18 +00002738 if (DI)
2739 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCall31168b02011-06-15 23:02:42 +00002740}
John McCall1bd25562011-06-24 23:21:27 +00002741
2742/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2743/// make sure it survives garbage collection until this point.
2744void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2745 // We just use an inline assembly.
John McCall1bd25562011-06-24 23:21:27 +00002746 llvm::FunctionType *extenderType
John McCalla729c622012-02-17 03:33:10 +00002747 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
John McCall1bd25562011-06-24 23:21:27 +00002748 llvm::Value *extender
2749 = llvm::InlineAsm::get(extenderType,
2750 /* assembly */ "",
2751 /* constraints */ "r",
2752 /* side effects */ true);
2753
2754 object = Builder.CreateBitCast(object, VoidPtrTy);
2755 Builder.CreateCall(extender, object)->setDoesNotThrow();
2756}
2757
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002758/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002759/// non-trivial copy assignment function, produce following helper function.
2760/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
2761///
2762llvm::Constant *
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002763CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
2764 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00002765 // FIXME. This api is for NeXt runtime only for now.
2766 if (!getLangOptions().CPlusPlus || !getLangOptions().NeXTRuntime)
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002767 return 0;
2768 QualType Ty = PID->getPropertyIvarDecl()->getType();
2769 if (!Ty->isRecordType())
2770 return 0;
2771 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002772 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002773 return 0;
Fariborz Jahanian1bed4132012-01-08 19:13:23 +00002774 llvm::Constant * HelperFn = 0;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002775 if (hasTrivialSetExpr(PID))
2776 return 0;
2777 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
2778 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
2779 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002780
2781 ASTContext &C = getContext();
2782 IdentifierInfo *II
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002783 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002784 FunctionDecl *FD = FunctionDecl::Create(C,
2785 C.getTranslationUnitDecl(),
2786 SourceLocation(),
2787 SourceLocation(), II, C.VoidTy, 0,
2788 SC_Static,
2789 SC_None,
2790 false,
2791 true);
2792
2793 QualType DestTy = C.getPointerType(Ty);
2794 QualType SrcTy = Ty;
2795 SrcTy.addConst();
2796 SrcTy = C.getPointerType(SrcTy);
2797
2798 FunctionArgList args;
2799 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2800 args.push_back(&dstDecl);
2801 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2802 args.push_back(&srcDecl);
2803
2804 const CGFunctionInfo &FI =
John McCalla729c622012-02-17 03:33:10 +00002805 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
2806 FunctionType::ExtInfo(),
2807 RequiredArgs::All);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002808
John McCalla729c622012-02-17 03:33:10 +00002809 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002810
2811 llvm::Function *Fn =
2812 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002813 "__assign_helper_atomic_property_", &CGM.getModule());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002814
2815 if (CGM.getModuleDebugInfo())
2816 DebugInfo = CGM.getModuleDebugInfo();
2817
2818
2819 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2820
John McCall113bee02012-03-10 09:33:50 +00002821 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2822 VK_RValue, SourceLocation());
2823 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
2824 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002825
John McCall113bee02012-03-10 09:33:50 +00002826 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
2827 VK_RValue, SourceLocation());
2828 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2829 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002830
John McCall113bee02012-03-10 09:33:50 +00002831 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002832 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
John McCall113bee02012-03-10 09:33:50 +00002833 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
2834 Args, 2, DestTy->getPointeeType(),
2835 VK_LValue, SourceLocation());
2836
2837 EmitStmt(&TheCall);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002838
2839 FinishFunction();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00002840 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002841 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00002842 return HelperFn;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002843}
2844
2845llvm::Constant *
2846CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
2847 const ObjCPropertyImplDecl *PID) {
2848 // FIXME. This api is for NeXt runtime only for now.
2849 if (!getLangOptions().CPlusPlus || !getLangOptions().NeXTRuntime)
2850 return 0;
2851 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2852 QualType Ty = PD->getType();
2853 if (!Ty->isRecordType())
2854 return 0;
2855 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
2856 return 0;
2857 llvm::Constant * HelperFn = 0;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002858
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002859 if (hasTrivialGetExpr(PID))
2860 return 0;
2861 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
2862 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
2863 return HelperFn;
2864
2865
2866 ASTContext &C = getContext();
2867 IdentifierInfo *II
2868 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
2869 FunctionDecl *FD = FunctionDecl::Create(C,
2870 C.getTranslationUnitDecl(),
2871 SourceLocation(),
2872 SourceLocation(), II, C.VoidTy, 0,
2873 SC_Static,
2874 SC_None,
2875 false,
2876 true);
2877
2878 QualType DestTy = C.getPointerType(Ty);
2879 QualType SrcTy = Ty;
2880 SrcTy.addConst();
2881 SrcTy = C.getPointerType(SrcTy);
2882
2883 FunctionArgList args;
2884 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2885 args.push_back(&dstDecl);
2886 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2887 args.push_back(&srcDecl);
2888
2889 const CGFunctionInfo &FI =
John McCalla729c622012-02-17 03:33:10 +00002890 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
2891 FunctionType::ExtInfo(),
2892 RequiredArgs::All);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002893
John McCalla729c622012-02-17 03:33:10 +00002894 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002895
2896 llvm::Function *Fn =
2897 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2898 "__copy_helper_atomic_property_", &CGM.getModule());
2899
2900 if (CGM.getModuleDebugInfo())
2901 DebugInfo = CGM.getModuleDebugInfo();
2902
2903
2904 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2905
John McCall113bee02012-03-10 09:33:50 +00002906 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002907 VK_RValue, SourceLocation());
2908
John McCall113bee02012-03-10 09:33:50 +00002909 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2910 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002911
2912 CXXConstructExpr *CXXConstExpr =
2913 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
2914
2915 SmallVector<Expr*, 4> ConstructorArgs;
John McCall113bee02012-03-10 09:33:50 +00002916 ConstructorArgs.push_back(&SRC);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002917 CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin();
2918 ++A;
2919
2920 for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end();
2921 A != AEnd; ++A)
2922 ConstructorArgs.push_back(*A);
2923
2924 CXXConstructExpr *TheCXXConstructExpr =
2925 CXXConstructExpr::Create(C, Ty, SourceLocation(),
2926 CXXConstExpr->getConstructor(),
2927 CXXConstExpr->isElidable(),
2928 &ConstructorArgs[0], ConstructorArgs.size(),
Sebastian Redla9351792012-02-11 23:51:47 +00002929 CXXConstExpr->hadMultipleCandidates(),
2930 CXXConstExpr->isListInitialization(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002931 CXXConstExpr->requiresZeroInitialization(),
2932 CXXConstExpr->getConstructionKind(), SourceRange());
2933
John McCall113bee02012-03-10 09:33:50 +00002934 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2935 VK_RValue, SourceLocation());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002936
John McCall113bee02012-03-10 09:33:50 +00002937 RValue DV = EmitAnyExpr(&DstExpr);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002938 CharUnits Alignment = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
2939 EmitAggExpr(TheCXXConstructExpr,
2940 AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifiers(),
2941 AggValueSlot::IsDestructed,
2942 AggValueSlot::DoesNotNeedGCBarriers,
2943 AggValueSlot::IsNotAliased));
2944
2945 FinishFunction();
2946 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2947 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
2948 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002949}
2950
Eli Friedmanec75fec2012-02-28 01:08:45 +00002951llvm::Value *
2952CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
2953 // Get selectors for retain/autorelease.
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00002954 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
2955 Selector CopySelector =
2956 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmanec75fec2012-02-28 01:08:45 +00002957 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
2958 Selector AutoreleaseSelector =
2959 getContext().Selectors.getNullarySelector(AutoreleaseID);
2960
2961 // Emit calls to retain/autorelease.
2962 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2963 llvm::Value *Val = Block;
2964 RValue Result;
2965 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00002966 Ty, CopySelector,
Eli Friedmanec75fec2012-02-28 01:08:45 +00002967 Val, CallArgList(), 0, 0);
2968 Val = Result.getScalarVal();
2969 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2970 Ty, AutoreleaseSelector,
2971 Val, CallArgList(), 0, 0);
2972 Val = Result.getScalarVal();
2973 return Val;
2974}
2975
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002976
Ted Kremenek43e06332008-04-09 15:51:31 +00002977CGObjCRuntime::~CGObjCRuntime() {}