blob: b582f047075c981e99854f343460cd662f948092 [file] [log] [blame]
Anders Carlsson55085182007-08-21 17:43:55 +00001//===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Anders Carlsson55085182007-08-21 17:43:55 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Objective-C code as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Devang Patelbcbd03a2011-01-19 01:36:36 +000014#include "CGDebugInfo.h"
Ted Kremenek2979ec72008-04-09 15:51:31 +000015#include "CGObjCRuntime.h"
Anders Carlsson55085182007-08-21 17:43:55 +000016#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
John McCallf85e1932011-06-15 23:02:42 +000018#include "TargetInfo.h"
Daniel Dunbar85c59ed2008-08-29 08:11:39 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Chris Lattner16f00492009-04-26 01:32:48 +000021#include "clang/AST/StmtObjC.h"
Daniel Dunbare66f4e32008-09-03 00:27:26 +000022#include "clang/Basic/Diagnostic.h"
Anders Carlsson3d8400d2008-08-30 19:51:14 +000023#include "llvm/ADT/STLExtras.h"
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +000024#include "llvm/Target/TargetData.h"
John McCallf85e1932011-06-15 23:02:42 +000025#include "llvm/InlineAsm.h"
Anders Carlsson55085182007-08-21 17:43:55 +000026using namespace clang;
27using namespace CodeGen;
28
John McCallf85e1932011-06-15 23:02:42 +000029typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
30static TryEmitResult
31tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
32
33/// Given the address of a variable of pointer type, find the correct
34/// null to store into it.
35static llvm::Constant *getNullForVariable(llvm::Value *addr) {
Chris Lattner2acc6e32011-07-18 04:24:23 +000036 llvm::Type *type =
John McCallf85e1932011-06-15 23:02:42 +000037 cast<llvm::PointerType>(addr->getType())->getElementType();
38 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
39}
40
Chris Lattner8fdf3282008-06-24 17:04:18 +000041/// Emits an instance of NSConstantString representing the object.
Mike Stump1eb44332009-09-09 15:08:12 +000042llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar71fcec92008-11-25 21:53:21 +000043{
David Chisnall0d13f6f2010-01-23 02:40:42 +000044 llvm::Constant *C =
45 CGM.getObjCRuntime().GenerateConstantString(E->getString());
Daniel Dunbared7c6182008-08-20 00:28:19 +000046 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Anderson3c4972d2009-07-29 18:54:39 +000047 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattner8fdf3282008-06-24 17:04:18 +000048}
49
50/// Emit a selector.
51llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
52 // Untyped selector.
53 // Note that this implementation allows for non-constant strings to be passed
54 // as arguments to @selector(). Currently, the only thing preventing this
55 // behaviour is the type checking in the front end.
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +000056 return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
Chris Lattner8fdf3282008-06-24 17:04:18 +000057}
58
Daniel Dunbared7c6182008-08-20 00:28:19 +000059llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
60 // FIXME: This should pass the Decl not the name.
61 return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol());
62}
Chris Lattner8fdf3282008-06-24 17:04:18 +000063
Douglas Gregor926df6c2011-06-11 01:09:30 +000064/// \brief Adjust the type of the result of an Objective-C message send
65/// expression when the method has a related result type.
66static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
67 const Expr *E,
68 const ObjCMethodDecl *Method,
69 RValue Result) {
70 if (!Method)
71 return Result;
John McCallf85e1932011-06-15 23:02:42 +000072
Douglas Gregor926df6c2011-06-11 01:09:30 +000073 if (!Method->hasRelatedResultType() ||
74 CGF.getContext().hasSameType(E->getType(), Method->getResultType()) ||
75 !Result.isScalar())
76 return Result;
77
78 // We have applied a related result type. Cast the rvalue appropriately.
79 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
80 CGF.ConvertType(E->getType())));
81}
Chris Lattner8fdf3282008-06-24 17:04:18 +000082
John McCalldc7c5ad2011-07-22 08:53:00 +000083/// Decide whether to extend the lifetime of the receiver of a
84/// returns-inner-pointer message.
85static bool
86shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
87 switch (message->getReceiverKind()) {
88
89 // For a normal instance message, we should extend unless the
90 // receiver is loaded from a variable with precise lifetime.
91 case ObjCMessageExpr::Instance: {
92 const Expr *receiver = message->getInstanceReceiver();
93 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
94 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
95 receiver = ice->getSubExpr()->IgnoreParens();
96
97 // Only __strong variables.
98 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
99 return true;
100
101 // All ivars and fields have precise lifetime.
102 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
103 return false;
104
105 // Otherwise, check for variables.
106 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
107 if (!declRef) return true;
108 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
109 if (!var) return true;
110
111 // All variables have precise lifetime except local variables with
112 // automatic storage duration that aren't specially marked.
113 return (var->hasLocalStorage() &&
114 !var->hasAttr<ObjCPreciseLifetimeAttr>());
115 }
116
117 case ObjCMessageExpr::Class:
118 case ObjCMessageExpr::SuperClass:
119 // It's never necessary for class objects.
120 return false;
121
122 case ObjCMessageExpr::SuperInstance:
123 // We generally assume that 'self' lives throughout a method call.
124 return false;
125 }
126
127 llvm_unreachable("invalid receiver kind");
128}
129
John McCallef072fd2010-05-22 01:48:05 +0000130RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
131 ReturnValueSlot Return) {
Chris Lattner8fdf3282008-06-24 17:04:18 +0000132 // Only the lookup mechanism and first two arguments of the method
133 // implementation vary between runtimes. We can get the receiver and
134 // arguments in generic code.
Mike Stump1eb44332009-09-09 15:08:12 +0000135
John McCallf85e1932011-06-15 23:02:42 +0000136 bool isDelegateInit = E->isDelegateInitCall();
137
John McCalldc7c5ad2011-07-22 08:53:00 +0000138 const ObjCMethodDecl *method = E->getMethodDecl();
139
John McCallf85e1932011-06-15 23:02:42 +0000140 // We don't retain the receiver in delegate init calls, and this is
141 // safe because the receiver value is always loaded from 'self',
142 // which we zero out. We don't want to Block_copy block receivers,
143 // though.
144 bool retainSelf =
145 (!isDelegateInit &&
146 CGM.getLangOptions().ObjCAutoRefCount &&
John McCalldc7c5ad2011-07-22 08:53:00 +0000147 method &&
148 method->hasAttr<NSConsumesSelfAttr>());
John McCallf85e1932011-06-15 23:02:42 +0000149
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000150 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000151 bool isSuperMessage = false;
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000152 bool isClassMessage = false;
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000153 ObjCInterfaceDecl *OID = 0;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000154 // Find the receiver
Douglas Gregor926df6c2011-06-11 01:09:30 +0000155 QualType ReceiverType;
Daniel Dunbar0b647a62010-04-22 03:17:06 +0000156 llvm::Value *Receiver = 0;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000157 switch (E->getReceiverKind()) {
158 case ObjCMessageExpr::Instance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000159 ReceiverType = E->getInstanceReceiver()->getType();
John McCallf85e1932011-06-15 23:02:42 +0000160 if (retainSelf) {
161 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
162 E->getInstanceReceiver());
163 Receiver = ter.getPointer();
John McCalldc7c5ad2011-07-22 08:53:00 +0000164 if (ter.getInt()) retainSelf = false;
John McCallf85e1932011-06-15 23:02:42 +0000165 } else
166 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor04badcf2010-04-21 00:45:42 +0000167 break;
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000168
Douglas Gregor04badcf2010-04-21 00:45:42 +0000169 case ObjCMessageExpr::Class: {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000170 ReceiverType = E->getClassReceiver();
171 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3031c632010-05-17 20:12:43 +0000172 assert(ObjTy && "Invalid Objective-C class message send");
173 OID = ObjTy->getInterface();
174 assert(OID && "Invalid Objective-C class message send");
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000175 Receiver = Runtime.GetClass(Builder, OID);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000176 isClassMessage = true;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000177 break;
178 }
179
180 case ObjCMessageExpr::SuperInstance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000181 ReceiverType = E->getSuperType();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000182 Receiver = LoadObjCSelf();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000183 isSuperMessage = true;
184 break;
185
186 case ObjCMessageExpr::SuperClass:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000187 ReceiverType = E->getSuperType();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000188 Receiver = LoadObjCSelf();
189 isSuperMessage = true;
190 isClassMessage = true;
191 break;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000192 }
193
John McCalldc7c5ad2011-07-22 08:53:00 +0000194 if (retainSelf)
195 Receiver = EmitARCRetainNonBlock(Receiver);
196
197 // In ARC, we sometimes want to "extend the lifetime"
198 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
199 // messages.
200 if (getLangOptions().ObjCAutoRefCount && method &&
201 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
202 shouldExtendReceiverForInnerPointerMessage(E))
203 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
204
John McCallf85e1932011-06-15 23:02:42 +0000205 QualType ResultType =
John McCalldc7c5ad2011-07-22 08:53:00 +0000206 method ? method->getResultType() : E->getType();
John McCallf85e1932011-06-15 23:02:42 +0000207
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000208 CallArgList Args;
John McCalldc7c5ad2011-07-22 08:53:00 +0000209 EmitCallArgs(Args, method, E->arg_begin(), E->arg_end());
Mike Stump1eb44332009-09-09 15:08:12 +0000210
John McCallf85e1932011-06-15 23:02:42 +0000211 // For delegate init calls in ARC, do an unsafe store of null into
212 // self. This represents the call taking direct ownership of that
213 // value. We have to do this after emitting the other call
214 // arguments because they might also reference self, but we don't
215 // have to worry about any of them modifying self because that would
216 // be an undefined read and write of an object in unordered
217 // expressions.
218 if (isDelegateInit) {
219 assert(getLangOptions().ObjCAutoRefCount &&
220 "delegate init calls should only be marked in ARC");
221
222 // Do an unsafe store of null into self.
223 llvm::Value *selfAddr =
224 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
225 assert(selfAddr && "no self entry for a delegate init call?");
226
227 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
228 }
Anders Carlsson7e70fb22010-06-21 20:59:55 +0000229
Douglas Gregor926df6c2011-06-11 01:09:30 +0000230 RValue result;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000231 if (isSuperMessage) {
Chris Lattner9384c762008-06-26 04:42:20 +0000232 // super is only valid in an Objective-C method
233 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000234 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor926df6c2011-06-11 01:09:30 +0000235 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
236 E->getSelector(),
237 OMD->getClassInterface(),
238 isCategoryImpl,
239 Receiver,
240 isClassMessage,
241 Args,
John McCalldc7c5ad2011-07-22 08:53:00 +0000242 method);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000243 } else {
244 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
245 E->getSelector(),
246 Receiver, Args, OID,
John McCalldc7c5ad2011-07-22 08:53:00 +0000247 method);
Chris Lattner8fdf3282008-06-24 17:04:18 +0000248 }
John McCallf85e1932011-06-15 23:02:42 +0000249
250 // For delegate init calls in ARC, implicitly store the result of
251 // the call back into self. This takes ownership of the value.
252 if (isDelegateInit) {
253 llvm::Value *selfAddr =
254 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
255 llvm::Value *newSelf = result.getScalarVal();
256
257 // The delegate return type isn't necessarily a matching type; in
258 // fact, it's quite likely to be 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000259 llvm::Type *selfTy =
John McCallf85e1932011-06-15 23:02:42 +0000260 cast<llvm::PointerType>(selfAddr->getType())->getElementType();
261 newSelf = Builder.CreateBitCast(newSelf, selfTy);
262
263 Builder.CreateStore(newSelf, selfAddr);
264 }
265
John McCalldc7c5ad2011-07-22 08:53:00 +0000266 return AdjustRelatedResultType(*this, E, method, result);
Anders Carlsson55085182007-08-21 17:43:55 +0000267}
268
John McCallf85e1932011-06-15 23:02:42 +0000269namespace {
270struct FinishARCDealloc : EHScopeStack::Cleanup {
John McCallad346f42011-07-12 20:27:29 +0000271 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +0000272 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCall799d34e2011-07-13 18:26:47 +0000273
274 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCallf85e1932011-06-15 23:02:42 +0000275 const ObjCInterfaceDecl *iface = impl->getClassInterface();
276 if (!iface->getSuperClass()) return;
277
John McCall799d34e2011-07-13 18:26:47 +0000278 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
279
John McCallf85e1932011-06-15 23:02:42 +0000280 // Call [super dealloc] if we have a superclass.
281 llvm::Value *self = CGF.LoadObjCSelf();
282
283 CallArgList args;
284 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
285 CGF.getContext().VoidTy,
286 method->getSelector(),
287 iface,
John McCall799d34e2011-07-13 18:26:47 +0000288 isCategory,
John McCallf85e1932011-06-15 23:02:42 +0000289 self,
290 /*is class msg*/ false,
291 args,
292 method);
293 }
294};
295}
296
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000297/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
298/// the LLVM function and sets the other context used by
299/// CodeGenFunction.
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000300void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
Devang Patel8d3f8972011-05-19 23:37:41 +0000301 const ObjCContainerDecl *CD,
302 SourceLocation StartLoc) {
John McCalld26bc762011-03-09 04:27:21 +0000303 FunctionArgList args;
Devang Patel4800ea62010-04-05 21:09:15 +0000304 // Check if we should generate debug info for this method.
Devang Patelaa112892011-03-07 18:45:56 +0000305 if (CGM.getModuleDebugInfo() && !OMD->hasAttr<NoDebugAttr>())
306 DebugInfo = CGM.getModuleDebugInfo();
Devang Patel4800ea62010-04-05 21:09:15 +0000307
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000308 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000309
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000310 const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(OMD);
311 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner41110242008-06-17 18:05:57 +0000312
John McCalld26bc762011-03-09 04:27:21 +0000313 args.push_back(OMD->getSelfDecl());
314 args.push_back(OMD->getCmdDecl());
Chris Lattner41110242008-06-17 18:05:57 +0000315
Chris Lattner89951a82009-02-20 18:43:26 +0000316 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
317 E = OMD->param_end(); PI != E; ++PI)
John McCalld26bc762011-03-09 04:27:21 +0000318 args.push_back(*PI);
Chris Lattner41110242008-06-17 18:05:57 +0000319
Peter Collingbourne14110472011-01-13 18:57:25 +0000320 CurGD = OMD;
321
Devang Patel8d3f8972011-05-19 23:37:41 +0000322 StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc);
John McCallf85e1932011-06-15 23:02:42 +0000323
324 // In ARC, certain methods get an extra cleanup.
325 if (CGM.getLangOptions().ObjCAutoRefCount &&
326 OMD->isInstanceMethod() &&
327 OMD->getSelector().isUnarySelector()) {
328 const IdentifierInfo *ident =
329 OMD->getSelector().getIdentifierInfoForSlot(0);
330 if (ident->isStr("dealloc"))
331 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
332 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000333}
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000334
John McCallf85e1932011-06-15 23:02:42 +0000335static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
336 LValue lvalue, QualType type);
337
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000338void CodeGenFunction::GenerateObjCGetterBody(ObjCIvarDecl *Ivar,
339 bool IsAtomic, bool IsStrong) {
340 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
341 Ivar, 0);
342 llvm::Value *GetCopyStructFn =
343 CGM.getObjCRuntime().GetGetStructFunction();
344 CodeGenTypes &Types = CGM.getTypes();
345 // objc_copyStruct (ReturnValue, &structIvar,
346 // sizeof (Type of Ivar), isAtomic, false);
347 CallArgList Args;
John McCall0774cb82011-05-15 01:53:33 +0000348 RValue RV = RValue::get(Builder.CreateBitCast(ReturnValue, VoidPtrTy));
Eli Friedman04c9a492011-05-02 17:57:46 +0000349 Args.add(RV, getContext().VoidPtrTy);
John McCall0774cb82011-05-15 01:53:33 +0000350 RV = RValue::get(Builder.CreateBitCast(LV.getAddress(), VoidPtrTy));
Eli Friedman04c9a492011-05-02 17:57:46 +0000351 Args.add(RV, getContext().VoidPtrTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000352 // sizeof (Type of Ivar)
353 CharUnits Size = getContext().getTypeSizeInChars(Ivar->getType());
354 llvm::Value *SizeVal =
John McCall0774cb82011-05-15 01:53:33 +0000355 llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy),
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000356 Size.getQuantity());
Eli Friedman04c9a492011-05-02 17:57:46 +0000357 Args.add(RValue::get(SizeVal), getContext().LongTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000358 llvm::Value *isAtomic =
359 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy),
360 IsAtomic ? 1 : 0);
Eli Friedman04c9a492011-05-02 17:57:46 +0000361 Args.add(RValue::get(isAtomic), getContext().BoolTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000362 llvm::Value *hasStrong =
363 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy),
364 IsStrong ? 1 : 0);
Eli Friedman04c9a492011-05-02 17:57:46 +0000365 Args.add(RValue::get(hasStrong), getContext().BoolTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000366 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
367 FunctionType::ExtInfo()),
368 GetCopyStructFn, ReturnValueSlot(), Args);
369}
370
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000371/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump1eb44332009-09-09 15:08:12 +0000372/// its pointer, name, and types registered in the class struture.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000373void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
Devang Patel8d3f8972011-05-19 23:37:41 +0000374 StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000375 EmitStmt(OMD->getBody());
376 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000377}
378
Mike Stumpf5408fe2009-05-16 07:57:57 +0000379// FIXME: I wasn't sure about the synthesis approach. If we end up generating an
380// AST for the whole body we can just fall back to having a GenerateFunction
381// which takes the body Stmt.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000382
383/// GenerateObjCGetter - Generate an Objective-C property getter
Steve Naroff489034c2009-01-10 22:55:25 +0000384/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
385/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000386void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
387 const ObjCPropertyImplDecl *PID) {
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000388 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000389 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000390 bool IsAtomic =
391 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000392 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
393 assert(OMD && "Invalid call to generate getter (empty method)");
Devang Patel8d3f8972011-05-19 23:37:41 +0000394 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000395
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000396 // Determine if we should use an objc_getProperty call for
Fariborz Jahanian447d7ae2008-12-08 23:56:17 +0000397 // this. Non-atomic properties are directly evaluated.
398 // atomic 'copy' and 'retain' properties are also directly
399 // evaluated in gc-only mode.
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000400 if (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000401 IsAtomic &&
Fariborz Jahanian447d7ae2008-12-08 23:56:17 +0000402 (PD->getSetterKind() == ObjCPropertyDecl::Copy ||
403 PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000404 llvm::Value *GetPropertyFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000405 CGM.getObjCRuntime().GetPropertyGetFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000407 if (!GetPropertyFn) {
408 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
409 FinishFunction();
410 return;
411 }
412
413 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
414 // FIXME: Can't this be simpler? This might even be worse than the
415 // corresponding gcc code.
416 CodeGenTypes &Types = CGM.getTypes();
417 ValueDecl *Cmd = OMD->getCmdDecl();
418 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
419 QualType IdTy = getContext().getObjCIdType();
Mike Stump1eb44332009-09-09 15:08:12 +0000420 llvm::Value *SelfAsId =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000421 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000422 llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000423 llvm::Value *True =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000424 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000425 CallArgList Args;
Eli Friedman04c9a492011-05-02 17:57:46 +0000426 Args.add(RValue::get(SelfAsId), IdTy);
427 Args.add(RValue::get(CmdVal), Cmd->getType());
428 Args.add(RValue::get(Offset), getContext().getPointerDiffType());
429 Args.add(RValue::get(True), getContext().BoolTy);
Daniel Dunbare4be5a62009-02-03 23:43:59 +0000430 // FIXME: We shouldn't need to get the function info here, the
431 // runtime already should have computed it to build the function.
John McCall04a67a62010-02-05 21:31:56 +0000432 RValue RV = EmitCall(Types.getFunctionInfo(PD->getType(), Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000433 FunctionType::ExtInfo()),
Anders Carlssonf3c47c92009-12-24 19:25:24 +0000434 GetPropertyFn, ReturnValueSlot(), Args);
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000435 // We need to fix the type here. Ivars with copy & retain are
436 // always objects so we don't need to worry about complex or
437 // aggregates.
Mike Stump1eb44332009-09-09 15:08:12 +0000438 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000439 Types.ConvertType(PD->getType())));
440 EmitReturnOfRValue(RV, PD->getType());
John McCallf85e1932011-06-15 23:02:42 +0000441
442 // objc_getProperty does an autorelease, so we should suppress ours.
443 AutoreleaseResult = false;
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000444 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000445 const llvm::Triple &Triple = getContext().getTargetInfo().getTriple();
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000446 QualType IVART = Ivar->getType();
447 if (IsAtomic &&
448 IVART->isScalarType() &&
449 (Triple.getArch() == llvm::Triple::arm ||
450 Triple.getArch() == llvm::Triple::thumb) &&
451 (getContext().getTypeSizeInChars(IVART)
452 > CharUnits::fromQuantity(4)) &&
453 CGM.getObjCRuntime().GetGetStructFunction()) {
454 GenerateObjCGetterBody(Ivar, true, false);
455 }
Fariborz Jahanian1d3a61a2011-04-05 21:41:23 +0000456 else if (IsAtomic &&
457 (IVART->isScalarType() && !IVART->isRealFloatingType()) &&
458 Triple.getArch() == llvm::Triple::x86 &&
459 (getContext().getTypeSizeInChars(IVART)
460 > CharUnits::fromQuantity(4)) &&
461 CGM.getObjCRuntime().GetGetStructFunction()) {
462 GenerateObjCGetterBody(Ivar, true, false);
463 }
464 else if (IsAtomic &&
465 (IVART->isScalarType() && !IVART->isRealFloatingType()) &&
466 Triple.getArch() == llvm::Triple::x86_64 &&
467 (getContext().getTypeSizeInChars(IVART)
468 > CharUnits::fromQuantity(8)) &&
469 CGM.getObjCRuntime().GetGetStructFunction()) {
470 GenerateObjCGetterBody(Ivar, true, false);
471 }
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000472 else if (IVART->isAnyComplexType()) {
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000473 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
474 Ivar, 0);
Fariborz Jahanian1b23fe62010-03-25 21:56:43 +0000475 ComplexPairTy Pair = LoadComplexFromAddr(LV.getAddress(),
476 LV.isVolatileQualified());
477 StoreComplexToAddr(Pair, ReturnValue, LV.isVolatileQualified());
478 }
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000479 else if (hasAggregateLLVMType(IVART)) {
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000480 bool IsStrong = false;
Fariborz Jahanian5fb65092011-04-05 23:01:27 +0000481 if ((IsStrong = IvarTypeWithAggrGCObjects(IVART))
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000482 && CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect
David Chisnall8fac25d2010-12-26 22:13:16 +0000483 && CGM.getObjCRuntime().GetGetStructFunction()) {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000484 GenerateObjCGetterBody(Ivar, IsAtomic, IsStrong);
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000485 }
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000486 else {
Fariborz Jahanian01cb3072011-04-06 16:05:26 +0000487 const CXXRecordDecl *classDecl = IVART->getAsCXXRecordDecl();
488
489 if (PID->getGetterCXXConstructor() &&
Sean Hunt023df372011-05-09 18:22:59 +0000490 classDecl && !classDecl->hasTrivialDefaultConstructor()) {
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000491 ReturnStmt *Stmt =
492 new (getContext()) ReturnStmt(SourceLocation(),
Douglas Gregor5077c382010-05-15 06:01:05 +0000493 PID->getGetterCXXConstructor(),
494 0);
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000495 EmitReturnStmt(*Stmt);
Fariborz Jahanian1d3a61a2011-04-05 21:41:23 +0000496 } else if (IsAtomic &&
497 !IVART->isAnyComplexType() &&
498 Triple.getArch() == llvm::Triple::x86 &&
499 (getContext().getTypeSizeInChars(IVART)
500 > CharUnits::fromQuantity(4)) &&
501 CGM.getObjCRuntime().GetGetStructFunction()) {
502 GenerateObjCGetterBody(Ivar, true, false);
503 }
504 else if (IsAtomic &&
505 !IVART->isAnyComplexType() &&
506 Triple.getArch() == llvm::Triple::x86_64 &&
507 (getContext().getTypeSizeInChars(IVART)
508 > CharUnits::fromQuantity(8)) &&
509 CGM.getObjCRuntime().GetGetStructFunction()) {
510 GenerateObjCGetterBody(Ivar, true, false);
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000511 }
512 else {
513 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
514 Ivar, 0);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000515 EmitAggregateCopy(ReturnValue, LV.getAddress(), IVART);
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000516 }
517 }
John McCallba3dd902011-07-22 05:23:13 +0000518 } else {
519 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
520 Ivar, 0);
521 QualType propType = PD->getType();
John McCallf85e1932011-06-15 23:02:42 +0000522
John McCallba3dd902011-07-22 05:23:13 +0000523 llvm::Value *value;
524 if (propType->isReferenceType()) {
525 value = LV.getAddress();
526 } else {
527 // We want to load and autoreleaseReturnValue ARC __weak ivars.
528 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
529 value = emitARCRetainLoadOfScalar(*this, LV, IVART);
530
531 // Otherwise we want to do a simple load, suppressing the
532 // final autorelease.
John McCallf85e1932011-06-15 23:02:42 +0000533 } else {
John McCallba3dd902011-07-22 05:23:13 +0000534 value = EmitLoadOfLValue(LV).getScalarVal();
535 AutoreleaseResult = false;
Fariborz Jahanian14086762011-03-28 23:47:18 +0000536 }
John McCallf85e1932011-06-15 23:02:42 +0000537
John McCallba3dd902011-07-22 05:23:13 +0000538 value = Builder.CreateBitCast(value, ConvertType(propType));
539 }
540
541 EmitReturnOfRValue(RValue::get(value), propType);
Fariborz Jahanianed1d29d2009-03-03 18:49:40 +0000542 }
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000543 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000544
545 FinishFunction();
546}
547
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000548void CodeGenFunction::GenerateObjCAtomicSetterBody(ObjCMethodDecl *OMD,
John McCallbbb253c2011-09-10 09:30:49 +0000549 ObjCIvarDecl *ivar) {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000550 // objc_copyStruct (&structIvar, &Arg,
551 // sizeof (struct something), true, false);
John McCallbbb253c2011-09-10 09:30:49 +0000552 CallArgList args;
553
554 // The first argument is the address of the ivar.
555 llvm::Value *ivarAddr =
556 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0).getAddress();
557 ivarAddr = Builder.CreateBitCast(ivarAddr, Int8PtrTy);
558 args.add(RValue::get(ivarAddr), getContext().VoidPtrTy);
559
560 // The second argument is the address of the parameter variable.
561 llvm::Value *argAddr = LocalDeclMap[*OMD->param_begin()];
562 argAddr = Builder.CreateBitCast(argAddr, Int8PtrTy);
563 args.add(RValue::get(argAddr), getContext().VoidPtrTy);
564
565 // The third argument is the sizeof the type.
566 llvm::Value *size =
567 CGM.getSize(getContext().getTypeSizeInChars(ivar->getType()));
568 args.add(RValue::get(size), getContext().getSizeType());
569
570 // The fourth and fifth arguments are just flags.
571 args.add(RValue::get(Builder.getTrue()), getContext().BoolTy);
572 args.add(RValue::get(Builder.getFalse()), getContext().BoolTy);
573
574 llvm::Value *copyStructFn = CGM.getObjCRuntime().GetSetStructFunction();
575 EmitCall(getTypes().getFunctionInfo(getContext().VoidTy, args,
576 FunctionType::ExtInfo()),
577 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000578}
579
John McCall71c758d2011-09-10 09:17:20 +0000580static bool hasTrivialAssignment(const ObjCPropertyImplDecl *PID) {
581 Expr *assign = PID->getSetterCXXAssignment();
582 if (!assign) return true;
583
584 // An operator call is trivial if the function it calls is trivial.
585 if (CallExpr *call = dyn_cast<CallExpr>(assign)) {
586 if (const FunctionDecl *callee
587 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
588 if (callee->isTrivial())
589 return true;
590 return false;
Fariborz Jahanian01cb3072011-04-06 16:05:26 +0000591 }
John McCall71c758d2011-09-10 09:17:20 +0000592
593 assert(isa<BinaryOperator>(assign));
594 return true;
595}
596
597/// Should the setter use objc_setProperty?
598static bool shouldUseSetProperty(CodeGenFunction &CGF,
599 ObjCPropertyDecl::SetterKind setterKind) {
600 // Copy setters require objc_setProperty.
601 if (setterKind == ObjCPropertyDecl::Copy)
602 return true;
603
604 // So do retain setters, if we're not in GC-only mode (where
605 // 'retain' is ignored).
606 if (setterKind == ObjCPropertyDecl::Retain &&
607 CGF.getLangOptions().getGCMode() != LangOptions::GCOnly)
608 return true;
609
610 // Otherwise, we don't need this.
611 return false;
612}
613
614static bool isAssignmentImplicitlyAtomic(CodeGenFunction &CGF,
615 const ObjCIvarDecl *ivar) {
616 // Aggregate assignment is not implicitly atomic if it includes a GC
617 // barrier.
618 QualType ivarType = ivar->getType();
619 if (CGF.getLangOptions().getGCMode())
620 if (const RecordType *ivarRecordTy = ivarType->getAs<RecordType>())
621 if (ivarRecordTy->getDecl()->hasObjectMember())
622 return false;
623
624 // Assume that any store no larger than a pointer, and as aligned as
625 // the required size, can be performed atomically.
626 ASTContext &Context = CGF.getContext();
627 std::pair<CharUnits,CharUnits> ivarSizeAndAlignment
628 = Context.getTypeInfoInChars(ivar->getType());
629
630 return (ivarSizeAndAlignment.first
631 <= CharUnits::fromQuantity(CGF.PointerSizeInBytes) &&
632 ivarSizeAndAlignment.second >= ivarSizeAndAlignment.first);
633}
634
635void
636CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
637 const ObjCPropertyImplDecl *propImpl) {
638 // Just use the setter expression if Sema gave us one and it's
639 // non-trivial. There's no way to do this atomically.
640 if (!hasTrivialAssignment(propImpl)) {
641 EmitStmt(propImpl->getSetterCXXAssignment());
642 return;
643 }
644
645 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
646 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
647 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
648
649 // A property is copy if it says it's copy.
650 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
651 bool isCopy = (setterKind == ObjCPropertyDecl::Copy);
652
653 // A property is atomic if it doesn't say it's nonatomic.
654 bool isAtomic =
655 !(prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
656
657 // Should we call the runtime's set property function?
658 if (shouldUseSetProperty(*this, setterKind)) {
659 llvm::Value *setPropertyFn =
660 CGM.getObjCRuntime().GetPropertySetFunction();
661 if (!setPropertyFn) {
662 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
663 return;
664 }
665
666 // Emit objc_setProperty((id) self, _cmd, offset, arg,
667 // <is-atomic>, <is-copy>).
668 llvm::Value *cmd =
669 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
670 llvm::Value *self =
671 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
672 llvm::Value *ivarOffset =
673 EmitIvarOffset(classImpl->getClassInterface(), ivar);
674 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
675 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
676
677 CallArgList args;
678 args.add(RValue::get(self), getContext().getObjCIdType());
679 args.add(RValue::get(cmd), getContext().getObjCSelType());
680 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
681 args.add(RValue::get(arg), getContext().getObjCIdType());
682 args.add(RValue::get(Builder.getInt1(isAtomic)), getContext().BoolTy);
683 args.add(RValue::get(Builder.getInt1(isCopy)), getContext().BoolTy);
684 // FIXME: We shouldn't need to get the function info here, the runtime
685 // already should have computed it to build the function.
686 EmitCall(getTypes().getFunctionInfo(getContext().VoidTy, args,
687 FunctionType::ExtInfo()),
688 setPropertyFn, ReturnValueSlot(), args);
689 return;
690 }
691
692 // If the property is atomic but has ARC or GC qualification, we
693 // must use the expression expansion. This isn't actually right for
694 // ARC strong, but we shouldn't actually get here for ARC strong,
695 // which should always end up using setProperty.
696 if (isAtomic &&
697 (ivar->getType().hasNonTrivialObjCLifetime() ||
698 (getLangOptions().getGCMode() &&
699 getContext().getObjCGCAttrKind(ivar->getType())))) {
700 // fallthrough
701
702 // If the property is atomic and can be implicitly performed
703 // atomically with an assignment, do so.
704 } else if (isAtomic && isAssignmentImplicitlyAtomic(*this, ivar)) {
705 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
706
707 LValue ivarLValue =
708 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
709 llvm::Value *ivarAddr = ivarLValue.getAddress();
710
711 // If necessary, use a non-aggregate type.
712 llvm::Type *eltType =
713 cast<llvm::PointerType>(ivarAddr->getType())->getElementType();
714 if (eltType->isAggregateType()) {
715 eltType = llvm::Type::getIntNTy(getLLVMContext(),
716 getContext().getTypeSize(ivar->getType()));
717 }
718
719 // Cast both arguments to the chosen operation type.
720 argAddr = Builder.CreateBitCast(argAddr, eltType->getPointerTo());
721 ivarAddr = Builder.CreateBitCast(ivarAddr, eltType->getPointerTo());
722
723 // Emit a single store.
724 // TODO: this should be a 'store atomic unordered'.
725 Builder.CreateStore(Builder.CreateLoad(argAddr), ivarAddr);
726 return;
727
728 // Otherwise, if the property is atomic, try to use the runtime's
729 // atomic-store-struct routine.
730 } else if (isAtomic && CGM.getObjCRuntime().GetSetStructFunction()) {
731 GenerateObjCAtomicSetterBody(setterMethod, ivar);
732 return;
733 }
734
735 // Otherwise, fake up some ASTs and emit a normal assignment.
736 ValueDecl *selfDecl = setterMethod->getSelfDecl();
737 DeclRefExpr self(selfDecl, selfDecl->getType(), VK_LValue, SourceLocation());
738 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
739 selfDecl->getType(), CK_LValueToRValue, &self,
740 VK_RValue);
741 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
742 SourceLocation(), &selfLoad, true, true);
743
744 ParmVarDecl *argDecl = *setterMethod->param_begin();
745 QualType argType = argDecl->getType().getNonReferenceType();
746 DeclRefExpr arg(argDecl, argType, VK_LValue, SourceLocation());
747 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
748 argType.getUnqualifiedType(), CK_LValueToRValue,
749 &arg, VK_RValue);
750
751 // The property type can differ from the ivar type in some situations with
752 // Objective-C pointer types, we can always bit cast the RHS in these cases.
753 // The following absurdity is just to ensure well-formed IR.
754 CastKind argCK = CK_NoOp;
755 if (ivarRef.getType()->isObjCObjectPointerType()) {
756 if (argLoad.getType()->isObjCObjectPointerType())
757 argCK = CK_BitCast;
758 else if (argLoad.getType()->isBlockPointerType())
759 argCK = CK_BlockPointerToObjCPointerCast;
760 else
761 argCK = CK_CPointerToObjCPointerCast;
762 } else if (ivarRef.getType()->isBlockPointerType()) {
763 if (argLoad.getType()->isBlockPointerType())
764 argCK = CK_BitCast;
765 else
766 argCK = CK_AnyPointerToBlockPointerCast;
767 } else if (ivarRef.getType()->isPointerType()) {
768 argCK = CK_BitCast;
769 }
770 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
771 ivarRef.getType(), argCK, &argLoad,
772 VK_RValue);
773 Expr *finalArg = &argLoad;
774 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
775 argLoad.getType()))
776 finalArg = &argCast;
777
778
779 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
780 ivarRef.getType(), VK_RValue, OK_Ordinary,
781 SourceLocation());
782 EmitStmt(&assign);
Fariborz Jahanian01cb3072011-04-06 16:05:26 +0000783}
784
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000785/// GenerateObjCSetter - Generate an Objective-C property setter
Steve Naroff489034c2009-01-10 22:55:25 +0000786/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
787/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000788void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
789 const ObjCPropertyImplDecl *PID) {
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000790 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
791 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
792 assert(OMD && "Invalid call to generate setter (empty method)");
Devang Patel8d3f8972011-05-19 23:37:41 +0000793 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000794
John McCall71c758d2011-09-10 09:17:20 +0000795 generateObjCSetterBody(IMP, PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000796
797 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +0000798}
799
John McCalle81ac692011-03-22 07:05:39 +0000800namespace {
John McCall9928c482011-07-12 16:41:08 +0000801 struct DestroyIvar : EHScopeStack::Cleanup {
802 private:
803 llvm::Value *addr;
John McCalle81ac692011-03-22 07:05:39 +0000804 const ObjCIvarDecl *ivar;
John McCall9928c482011-07-12 16:41:08 +0000805 CodeGenFunction::Destroyer &destroyer;
806 bool useEHCleanupForArray;
807 public:
808 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
809 CodeGenFunction::Destroyer *destroyer,
810 bool useEHCleanupForArray)
811 : addr(addr), ivar(ivar), destroyer(*destroyer),
812 useEHCleanupForArray(useEHCleanupForArray) {}
John McCalle81ac692011-03-22 07:05:39 +0000813
John McCallad346f42011-07-12 20:27:29 +0000814 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +0000815 LValue lvalue
816 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
817 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +0000818 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCalle81ac692011-03-22 07:05:39 +0000819 }
820 };
821}
822
John McCall9928c482011-07-12 16:41:08 +0000823/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
824static void destroyARCStrongWithStore(CodeGenFunction &CGF,
825 llvm::Value *addr,
826 QualType type) {
827 llvm::Value *null = getNullForVariable(addr);
828 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
829}
John McCallf85e1932011-06-15 23:02:42 +0000830
John McCalle81ac692011-03-22 07:05:39 +0000831static void emitCXXDestructMethod(CodeGenFunction &CGF,
832 ObjCImplementationDecl *impl) {
833 CodeGenFunction::RunCleanupsScope scope(CGF);
834
835 llvm::Value *self = CGF.LoadObjCSelf();
836
Jordy Rosedb8264e2011-07-22 02:08:32 +0000837 const ObjCInterfaceDecl *iface = impl->getClassInterface();
838 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +0000839 ivar; ivar = ivar->getNextIvar()) {
840 QualType type = ivar->getType();
841
John McCalle81ac692011-03-22 07:05:39 +0000842 // Check whether the ivar is a destructible type.
John McCall9928c482011-07-12 16:41:08 +0000843 QualType::DestructionKind dtorKind = type.isDestructedType();
844 if (!dtorKind) continue;
John McCalle81ac692011-03-22 07:05:39 +0000845
John McCall9928c482011-07-12 16:41:08 +0000846 CodeGenFunction::Destroyer *destroyer = 0;
John McCalle81ac692011-03-22 07:05:39 +0000847
John McCall9928c482011-07-12 16:41:08 +0000848 // Use a call to objc_storeStrong to destroy strong ivars, for the
849 // general benefit of the tools.
850 if (dtorKind == QualType::DK_objc_strong_lifetime) {
851 destroyer = &destroyARCStrongWithStore;
John McCallf85e1932011-06-15 23:02:42 +0000852
John McCall9928c482011-07-12 16:41:08 +0000853 // Otherwise use the default for the destruction kind.
854 } else {
855 destroyer = &CGF.getDestroyer(dtorKind);
John McCalle81ac692011-03-22 07:05:39 +0000856 }
John McCall9928c482011-07-12 16:41:08 +0000857
858 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
859
860 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
861 cleanupKind & EHCleanup);
John McCalle81ac692011-03-22 07:05:39 +0000862 }
863
864 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
865}
866
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000867void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
868 ObjCMethodDecl *MD,
869 bool ctor) {
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000870 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Devang Patel8d3f8972011-05-19 23:37:41 +0000871 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
John McCalle81ac692011-03-22 07:05:39 +0000872
873 // Emit .cxx_construct.
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000874 if (ctor) {
John McCallf85e1932011-06-15 23:02:42 +0000875 // Suppress the final autorelease in ARC.
876 AutoreleaseResult = false;
877
Chris Lattner5f9e2722011-07-23 10:55:15 +0000878 SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
John McCalle81ac692011-03-22 07:05:39 +0000879 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
880 E = IMP->init_end(); B != E; ++B) {
881 CXXCtorInitializer *IvarInit = (*B);
Francois Pichet00eb3f92010-12-04 09:14:42 +0000882 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000883 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian9b4d4fc2010-04-28 22:30:33 +0000884 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
885 LoadObjCSelf(), Ivar, 0);
John McCall7c2349b2011-08-25 20:40:09 +0000886 EmitAggExpr(IvarInit->getInit(),
887 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +0000888 AggValueSlot::DoesNotNeedGCBarriers,
889 AggValueSlot::IsNotAliased));
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000890 }
891 // constructor returns 'self'.
892 CodeGenTypes &Types = CGM.getTypes();
893 QualType IdTy(CGM.getContext().getObjCIdType());
894 llvm::Value *SelfAsId =
895 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
896 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCalle81ac692011-03-22 07:05:39 +0000897
898 // Emit .cxx_destruct.
Chandler Carruthbc397cf2010-05-06 00:20:39 +0000899 } else {
John McCalle81ac692011-03-22 07:05:39 +0000900 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000901 }
902 FinishFunction();
903}
904
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000905bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
906 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
907 it++; it++;
908 const ABIArgInfo &AI = it->info;
909 // FIXME. Is this sufficient check?
910 return (AI.getKind() == ABIArgInfo::Indirect);
911}
912
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000913bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
914 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
915 return false;
916 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
917 return FDTTy->getDecl()->hasObjectMember();
918 return false;
919}
920
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000921llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000922 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
923 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner41110242008-06-17 18:05:57 +0000924}
925
Fariborz Jahanian45012a72009-02-03 00:09:52 +0000926QualType CodeGenFunction::TypeOfSelfObject() {
927 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
928 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff14108da2009-07-10 23:34:53 +0000929 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
930 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanian45012a72009-02-03 00:09:52 +0000931 return PTy->getPointeeType();
932}
933
John McCalle68b9842010-12-04 03:11:00 +0000934LValue
935CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
936 // This is a special l-value that just issues sends when we load or
937 // store through it.
938
939 // For certain base kinds, we need to emit the base immediately.
940 llvm::Value *Base;
941 if (E->isSuperReceiver())
942 Base = LoadObjCSelf();
943 else if (E->isClassReceiver())
944 Base = CGM.getObjCRuntime().GetClass(Builder, E->getClassReceiver());
945 else
946 Base = EmitScalarExpr(E->getBase());
947 return LValue::MakePropertyRef(E, Base);
948}
949
950static RValue GenerateMessageSendSuper(CodeGenFunction &CGF,
951 ReturnValueSlot Return,
952 QualType ResultType,
953 Selector S,
954 llvm::Value *Receiver,
955 const CallArgList &CallArgs) {
956 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CGF.CurFuncDecl);
Fariborz Jahanianf4695572009-03-20 19:18:21 +0000957 bool isClassMessage = OMD->isClassMethod();
958 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
John McCalle68b9842010-12-04 03:11:00 +0000959 return CGF.CGM.getObjCRuntime()
960 .GenerateMessageSendSuper(CGF, Return, ResultType,
961 S, OMD->getClassInterface(),
962 isCategoryImpl, Receiver,
963 isClassMessage, CallArgs);
Fariborz Jahanianf4695572009-03-20 19:18:21 +0000964}
965
John McCall119a1c62010-12-04 02:32:38 +0000966RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
967 ReturnValueSlot Return) {
968 const ObjCPropertyRefExpr *E = LV.getPropertyRefExpr();
Fariborz Jahanian68af13f2011-03-30 16:11:20 +0000969 QualType ResultType = E->getGetterResultType();
John McCall12f78a62010-12-02 01:19:52 +0000970 Selector S;
Douglas Gregor926df6c2011-06-11 01:09:30 +0000971 const ObjCMethodDecl *method;
John McCall12f78a62010-12-02 01:19:52 +0000972 if (E->isExplicitProperty()) {
973 const ObjCPropertyDecl *Property = E->getExplicitProperty();
974 S = Property->getGetterName();
Douglas Gregor926df6c2011-06-11 01:09:30 +0000975 method = Property->getGetterMethodDecl();
Mike Stumpb3589f42009-07-30 22:28:39 +0000976 } else {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000977 method = E->getImplicitPropertyGetter();
978 S = method->getSelector();
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000979 }
John McCall12f78a62010-12-02 01:19:52 +0000980
John McCall119a1c62010-12-04 02:32:38 +0000981 llvm::Value *Receiver = LV.getPropertyRefBaseAddr();
John McCalle68b9842010-12-04 03:11:00 +0000982
John McCallf85e1932011-06-15 23:02:42 +0000983 if (CGM.getLangOptions().ObjCAutoRefCount) {
984 QualType receiverType;
985 if (E->isSuperReceiver())
986 receiverType = E->getSuperReceiverType();
987 else if (E->isClassReceiver())
988 receiverType = getContext().getObjCClassType();
989 else
990 receiverType = E->getBase()->getType();
991 }
992
John McCalle68b9842010-12-04 03:11:00 +0000993 // Accesses to 'super' follow a different code path.
994 if (E->isSuperReceiver())
Douglas Gregor926df6c2011-06-11 01:09:30 +0000995 return AdjustRelatedResultType(*this, E, method,
996 GenerateMessageSendSuper(*this, Return,
997 ResultType,
998 S, Receiver,
999 CallArgList()));
John McCall119a1c62010-12-04 02:32:38 +00001000 const ObjCInterfaceDecl *ReceiverClass
1001 = (E->isClassReceiver() ? E->getClassReceiver() : 0);
Douglas Gregor926df6c2011-06-11 01:09:30 +00001002 return AdjustRelatedResultType(*this, E, method,
John McCallf85e1932011-06-15 23:02:42 +00001003 CGM.getObjCRuntime().
1004 GenerateMessageSend(*this, Return, ResultType, S,
1005 Receiver, CallArgList(), ReceiverClass));
Daniel Dunbar9c3fc702008-08-27 06:57:25 +00001006}
1007
John McCall119a1c62010-12-04 02:32:38 +00001008void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
1009 LValue Dst) {
1010 const ObjCPropertyRefExpr *E = Dst.getPropertyRefExpr();
John McCall12f78a62010-12-02 01:19:52 +00001011 Selector S = E->getSetterSelector();
Fariborz Jahanian68af13f2011-03-30 16:11:20 +00001012 QualType ArgType = E->getSetterArgType();
1013
Fariborz Jahanianb19c76e2011-02-08 22:33:23 +00001014 // FIXME. Other than scalars, AST is not adequate for setter and
1015 // getter type mismatches which require conversion.
1016 if (Src.isScalar()) {
1017 llvm::Value *SrcVal = Src.getScalarVal();
1018 QualType DstType = getContext().getCanonicalType(ArgType);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001019 llvm::Type *DstTy = ConvertType(DstType);
Fariborz Jahanianb19c76e2011-02-08 22:33:23 +00001020 if (SrcVal->getType() != DstTy)
1021 Src =
1022 RValue::get(EmitScalarConversion(SrcVal, E->getType(), DstType));
1023 }
1024
John McCalle68b9842010-12-04 03:11:00 +00001025 CallArgList Args;
Eli Friedman04c9a492011-05-02 17:57:46 +00001026 Args.add(Src, ArgType);
John McCalle68b9842010-12-04 03:11:00 +00001027
1028 llvm::Value *Receiver = Dst.getPropertyRefBaseAddr();
1029 QualType ResultType = getContext().VoidTy;
1030
John McCall12f78a62010-12-02 01:19:52 +00001031 if (E->isSuperReceiver()) {
John McCalle68b9842010-12-04 03:11:00 +00001032 GenerateMessageSendSuper(*this, ReturnValueSlot(),
1033 ResultType, S, Receiver, Args);
John McCall12f78a62010-12-02 01:19:52 +00001034 return;
1035 }
1036
John McCall119a1c62010-12-04 02:32:38 +00001037 const ObjCInterfaceDecl *ReceiverClass
1038 = (E->isClassReceiver() ? E->getClassReceiver() : 0);
John McCall12f78a62010-12-02 01:19:52 +00001039
John McCall12f78a62010-12-02 01:19:52 +00001040 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
John McCalle68b9842010-12-04 03:11:00 +00001041 ResultType, S, Receiver, Args,
1042 ReceiverClass);
Daniel Dunbar85c59ed2008-08-29 08:11:39 +00001043}
1044
Chris Lattner74391b42009-03-22 21:03:39 +00001045void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump1eb44332009-09-09 15:08:12 +00001046 llvm::Constant *EnumerationMutationFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001047 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +00001048
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001049 if (!EnumerationMutationFn) {
1050 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1051 return;
1052 }
1053
Devang Patelbcbd03a2011-01-19 01:36:36 +00001054 CGDebugInfo *DI = getDebugInfo();
1055 if (DI) {
1056 DI->setLocation(S.getSourceRange().getBegin());
1057 DI->EmitRegionStart(Builder);
1058 }
1059
Devang Patel9d99f2d2011-06-13 23:15:32 +00001060 // The local variable comes into scope immediately.
1061 AutoVarEmission variable = AutoVarEmission::invalid();
1062 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1063 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1064
John McCalld88687f2011-01-07 01:49:06 +00001065 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump1eb44332009-09-09 15:08:12 +00001066
Anders Carlssonf484c312008-08-31 02:33:12 +00001067 // Fast enumeration state.
Douglas Gregor0815b572011-08-09 17:23:49 +00001068 QualType StateTy = CGM.getObjCFastEnumerationStateType();
Daniel Dunbar195337d2010-02-09 02:48:28 +00001069 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlsson1884eb02010-05-22 17:35:42 +00001070 EmitNullInitialization(StatePtr, StateTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001071
Anders Carlssonf484c312008-08-31 02:33:12 +00001072 // Number of elements in the items array.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001073 static const unsigned NumItems = 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001074
John McCalld88687f2011-01-07 01:49:06 +00001075 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramerad468862010-03-30 11:36:44 +00001076 IdentifierInfo *II[] = {
1077 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1078 &CGM.getContext().Idents.get("objects"),
1079 &CGM.getContext().Idents.get("count")
1080 };
1081 Selector FastEnumSel =
1082 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlssonf484c312008-08-31 02:33:12 +00001083
1084 QualType ItemsTy =
1085 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +00001086 llvm::APInt(32, NumItems),
Anders Carlssonf484c312008-08-31 02:33:12 +00001087 ArrayType::Normal, 0);
Daniel Dunbar195337d2010-02-09 02:48:28 +00001088 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001089
John McCall990567c2011-07-27 01:07:15 +00001090 // Emit the collection pointer. In ARC, we do a retain.
1091 llvm::Value *Collection;
1092 if (getLangOptions().ObjCAutoRefCount) {
1093 Collection = EmitARCRetainScalarExpr(S.getCollection());
1094
1095 // Enter a cleanup to do the release.
1096 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1097 } else {
1098 Collection = EmitScalarExpr(S.getCollection());
1099 }
Mike Stump1eb44332009-09-09 15:08:12 +00001100
John McCall4b302d32011-08-05 00:14:38 +00001101 // The 'continue' label needs to appear within the cleanup for the
1102 // collection object.
1103 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1104
John McCalld88687f2011-01-07 01:49:06 +00001105 // Send it our message:
Anders Carlssonf484c312008-08-31 02:33:12 +00001106 CallArgList Args;
John McCalld88687f2011-01-07 01:49:06 +00001107
1108 // The first argument is a temporary of the enumeration-state type.
Eli Friedman04c9a492011-05-02 17:57:46 +00001109 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001110
John McCalld88687f2011-01-07 01:49:06 +00001111 // The second argument is a temporary array with space for NumItems
1112 // pointers. We'll actually be loading elements from the array
1113 // pointer written into the control state; this buffer is so that
1114 // collections that *aren't* backed by arrays can still queue up
1115 // batches of elements.
Eli Friedman04c9a492011-05-02 17:57:46 +00001116 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001117
John McCalld88687f2011-01-07 01:49:06 +00001118 // The third argument is the capacity of that temporary array.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001119 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001120 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman04c9a492011-05-02 17:57:46 +00001121 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001122
John McCalld88687f2011-01-07 01:49:06 +00001123 // Start the enumeration.
Mike Stump1eb44332009-09-09 15:08:12 +00001124 RValue CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001125 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001126 getContext().UnsignedLongTy,
1127 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001128 Collection, Args);
Anders Carlssonf484c312008-08-31 02:33:12 +00001129
John McCalld88687f2011-01-07 01:49:06 +00001130 // The initial number of objects that were returned in the buffer.
1131 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump1eb44332009-09-09 15:08:12 +00001132
John McCalld88687f2011-01-07 01:49:06 +00001133 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1134 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump1eb44332009-09-09 15:08:12 +00001135
John McCalld88687f2011-01-07 01:49:06 +00001136 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlssonf484c312008-08-31 02:33:12 +00001137
John McCalld88687f2011-01-07 01:49:06 +00001138 // If the limit pointer was zero to begin with, the collection is
1139 // empty; skip all this.
1140 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1141 EmptyBB, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001142
John McCalld88687f2011-01-07 01:49:06 +00001143 // Otherwise, initialize the loop.
1144 EmitBlock(LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001145
John McCalld88687f2011-01-07 01:49:06 +00001146 // Save the initial mutations value. This is the value at an
1147 // address that was written into the state object by
1148 // countByEnumeratingWithState:objects:count:.
Mike Stump1eb44332009-09-09 15:08:12 +00001149 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001150 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001151 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001152 "mutationsptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001153
John McCalld88687f2011-01-07 01:49:06 +00001154 llvm::Value *initialMutations =
1155 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump1eb44332009-09-09 15:08:12 +00001156
John McCalld88687f2011-01-07 01:49:06 +00001157 // Start looping. This is the point we return to whenever we have a
1158 // fresh, non-empty batch of objects.
1159 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1160 EmitBlock(LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001161
John McCalld88687f2011-01-07 01:49:06 +00001162 // The current index into the buffer.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001163 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCalld88687f2011-01-07 01:49:06 +00001164 index->addIncoming(zero, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001165
John McCalld88687f2011-01-07 01:49:06 +00001166 // The current buffer size.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001167 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCalld88687f2011-01-07 01:49:06 +00001168 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001169
John McCalld88687f2011-01-07 01:49:06 +00001170 // Check whether the mutations value has changed from where it was
1171 // at start. StateMutationsPtr should actually be invariant between
1172 // refreshes.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001173 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCalld88687f2011-01-07 01:49:06 +00001174 llvm::Value *currentMutations
1175 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001176
John McCalld88687f2011-01-07 01:49:06 +00001177 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman361cf982011-03-02 22:39:34 +00001178 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump1eb44332009-09-09 15:08:12 +00001179
John McCalld88687f2011-01-07 01:49:06 +00001180 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1181 WasNotMutatedBB, WasMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001182
John McCalld88687f2011-01-07 01:49:06 +00001183 // If so, call the enumeration-mutation function.
1184 EmitBlock(WasMutatedBB);
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001185 llvm::Value *V =
Mike Stump1eb44332009-09-09 15:08:12 +00001186 Builder.CreateBitCast(Collection,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001187 ConvertType(getContext().getObjCIdType()),
1188 "tmp");
Daniel Dunbar2b2105e2009-02-03 23:55:40 +00001189 CallArgList Args2;
Eli Friedman04c9a492011-05-02 17:57:46 +00001190 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stumpf5408fe2009-05-16 07:57:57 +00001191 // FIXME: We shouldn't need to get the function info here, the runtime already
1192 // should have computed it to build the function.
John McCall04a67a62010-02-05 21:31:56 +00001193 EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2,
Rafael Espindola264ba482010-03-30 20:24:48 +00001194 FunctionType::ExtInfo()),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001195 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump1eb44332009-09-09 15:08:12 +00001196
John McCalld88687f2011-01-07 01:49:06 +00001197 // Otherwise, or if the mutation function returns, just continue.
1198 EmitBlock(WasNotMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001199
John McCalld88687f2011-01-07 01:49:06 +00001200 // Initialize the element variable.
1201 RunCleanupsScope elementVariableScope(*this);
John McCall57b3b6a2011-02-22 07:16:58 +00001202 bool elementIsVariable;
John McCalld88687f2011-01-07 01:49:06 +00001203 LValue elementLValue;
1204 QualType elementType;
1205 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall57b3b6a2011-02-22 07:16:58 +00001206 // Initialize the variable, in case it's a __block variable or something.
1207 EmitAutoVarInit(variable);
John McCalld88687f2011-01-07 01:49:06 +00001208
John McCall57b3b6a2011-02-22 07:16:58 +00001209 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCalld88687f2011-01-07 01:49:06 +00001210 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), D->getType(),
1211 VK_LValue, SourceLocation());
1212 elementLValue = EmitLValue(&tempDRE);
1213 elementType = D->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001214 elementIsVariable = true;
John McCall7acddac2011-06-17 06:42:21 +00001215
1216 if (D->isARCPseudoStrong())
1217 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCalld88687f2011-01-07 01:49:06 +00001218 } else {
1219 elementLValue = LValue(); // suppress warning
1220 elementType = cast<Expr>(S.getElement())->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001221 elementIsVariable = false;
John McCalld88687f2011-01-07 01:49:06 +00001222 }
Chris Lattner2acc6e32011-07-18 04:24:23 +00001223 llvm::Type *convertedElementType = ConvertType(elementType);
John McCalld88687f2011-01-07 01:49:06 +00001224
1225 // Fetch the buffer out of the enumeration state.
1226 // TODO: this pointer should actually be invariant between
1227 // refreshes, which would help us do certain loop optimizations.
Mike Stump1eb44332009-09-09 15:08:12 +00001228 llvm::Value *StateItemsPtr =
Anders Carlssonf484c312008-08-31 02:33:12 +00001229 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCalld88687f2011-01-07 01:49:06 +00001230 llvm::Value *EnumStateItems =
1231 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlssonf484c312008-08-31 02:33:12 +00001232
John McCalld88687f2011-01-07 01:49:06 +00001233 // Fetch the value at the current index from the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001234 llvm::Value *CurrentItemPtr =
John McCalld88687f2011-01-07 01:49:06 +00001235 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1236 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001237
John McCalld88687f2011-01-07 01:49:06 +00001238 // Cast that value to the right type.
1239 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1240 "currentitem");
Mike Stump1eb44332009-09-09 15:08:12 +00001241
John McCalld88687f2011-01-07 01:49:06 +00001242 // Make sure we have an l-value. Yes, this gets evaluated every
1243 // time through the loop.
John McCall7acddac2011-06-17 06:42:21 +00001244 if (!elementIsVariable) {
John McCalld88687f2011-01-07 01:49:06 +00001245 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001246 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCall7acddac2011-06-17 06:42:21 +00001247 } else {
1248 EmitScalarInit(CurrentItem, elementLValue);
1249 }
Mike Stump1eb44332009-09-09 15:08:12 +00001250
John McCall57b3b6a2011-02-22 07:16:58 +00001251 // If we do have an element variable, this assignment is the end of
1252 // its initialization.
1253 if (elementIsVariable)
1254 EmitAutoVarCleanups(variable);
1255
John McCalld88687f2011-01-07 01:49:06 +00001256 // Perform the loop body, setting up break and continue labels.
Anders Carlssone4b6d342009-02-10 05:52:02 +00001257 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCalld88687f2011-01-07 01:49:06 +00001258 {
1259 RunCleanupsScope Scope(*this);
1260 EmitStmt(S.getBody());
1261 }
Anders Carlssonf484c312008-08-31 02:33:12 +00001262 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001263
John McCalld88687f2011-01-07 01:49:06 +00001264 // Destroy the element variable now.
1265 elementVariableScope.ForceCleanup();
1266
1267 // Check whether there are more elements.
John McCallff8e1152010-07-23 21:56:41 +00001268 EmitBlock(AfterBody.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001269
John McCalld88687f2011-01-07 01:49:06 +00001270 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanianf0906c42009-01-06 18:56:31 +00001271
John McCalld88687f2011-01-07 01:49:06 +00001272 // First we check in the local buffer.
1273 llvm::Value *indexPlusOne
1274 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlssonf484c312008-08-31 02:33:12 +00001275
John McCalld88687f2011-01-07 01:49:06 +00001276 // If we haven't overrun the buffer yet, we can continue.
1277 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1278 LoopBodyBB, FetchMoreBB);
1279
1280 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1281 count->addIncoming(count, AfterBody.getBlock());
1282
1283 // Otherwise, we have to fetch more elements.
1284 EmitBlock(FetchMoreBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001285
1286 CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001287 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001288 getContext().UnsignedLongTy,
Mike Stump1eb44332009-09-09 15:08:12 +00001289 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001290 Collection, Args);
Mike Stump1eb44332009-09-09 15:08:12 +00001291
John McCalld88687f2011-01-07 01:49:06 +00001292 // If we got a zero count, we're done.
1293 llvm::Value *refetchCount = CountRV.getScalarVal();
1294
1295 // (note that the message send might split FetchMoreBB)
1296 index->addIncoming(zero, Builder.GetInsertBlock());
1297 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1298
1299 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1300 EmptyBB, LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001301
Anders Carlssonf484c312008-08-31 02:33:12 +00001302 // No more elements.
John McCalld88687f2011-01-07 01:49:06 +00001303 EmitBlock(EmptyBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001304
John McCall57b3b6a2011-02-22 07:16:58 +00001305 if (!elementIsVariable) {
Anders Carlssonf484c312008-08-31 02:33:12 +00001306 // If the element was not a declaration, set it to be null.
1307
John McCalld88687f2011-01-07 01:49:06 +00001308 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1309 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001310 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlssonf484c312008-08-31 02:33:12 +00001311 }
1312
Devang Patelbcbd03a2011-01-19 01:36:36 +00001313 if (DI) {
1314 DI->setLocation(S.getSourceRange().getEnd());
1315 DI->EmitRegionEnd(Builder);
1316 }
1317
John McCall990567c2011-07-27 01:07:15 +00001318 // Leave the cleanup we entered in ARC.
1319 if (getLangOptions().ObjCAutoRefCount)
1320 PopCleanupBlock();
1321
John McCallff8e1152010-07-23 21:56:41 +00001322 EmitBlock(LoopEnd.getBlock());
Anders Carlsson3d8400d2008-08-30 19:51:14 +00001323}
1324
Mike Stump1eb44332009-09-09 15:08:12 +00001325void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001326 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001327}
1328
Mike Stump1eb44332009-09-09 15:08:12 +00001329void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001330 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1331}
1332
Chris Lattner10cac6f2008-11-15 21:26:17 +00001333void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump1eb44332009-09-09 15:08:12 +00001334 const ObjCAtSynchronizedStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001335 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +00001336}
1337
John McCall33e56f32011-09-10 06:18:15 +00001338/// Produce the code for a CK_ARCProduceObject. Just does a
John McCallf85e1932011-06-15 23:02:42 +00001339/// primitive retain.
1340llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1341 llvm::Value *value) {
1342 return EmitARCRetain(type, value);
1343}
1344
1345namespace {
1346 struct CallObjCRelease : EHScopeStack::Cleanup {
John McCallbddfd872011-08-03 22:24:24 +00001347 CallObjCRelease(llvm::Value *object) : object(object) {}
1348 llvm::Value *object;
John McCallf85e1932011-06-15 23:02:42 +00001349
John McCallad346f42011-07-12 20:27:29 +00001350 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001351 CGF.EmitARCRelease(object, /*precise*/ true);
John McCallf85e1932011-06-15 23:02:42 +00001352 }
1353 };
1354}
1355
John McCall33e56f32011-09-10 06:18:15 +00001356/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCallf85e1932011-06-15 23:02:42 +00001357/// release at the end of the full-expression.
1358llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1359 llvm::Value *object) {
1360 // If we're in a conditional branch, we need to make the cleanup
John McCallbddfd872011-08-03 22:24:24 +00001361 // conditional.
1362 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCallf85e1932011-06-15 23:02:42 +00001363 return object;
1364}
1365
1366llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1367 llvm::Value *value) {
1368 return EmitARCRetainAutorelease(type, value);
1369}
1370
1371
1372static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001373 llvm::FunctionType *type,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001374 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001375 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1376
1377 // In -fobjc-no-arc-runtime, emit weak references to the runtime
1378 // support library.
John McCall9f084a32011-07-06 00:26:06 +00001379 if (!CGM.getCodeGenOpts().ObjCRuntimeHasARC)
John McCallf85e1932011-06-15 23:02:42 +00001380 if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
1381 f->setLinkage(llvm::Function::ExternalWeakLinkage);
1382
1383 return fn;
1384}
1385
1386/// Perform an operation having the signature
1387/// i8* (i8*)
1388/// where a null input causes a no-op and returns null.
1389static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1390 llvm::Value *value,
1391 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001392 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001393 if (isa<llvm::ConstantPointerNull>(value)) return value;
1394
1395 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001396 std::vector<llvm::Type*> args(1, CGF.Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001397 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001398 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1399 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1400 }
1401
1402 // Cast the argument to 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001403 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001404 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1405
1406 // Call the function.
1407 llvm::CallInst *call = CGF.Builder.CreateCall(fn, value);
1408 call->setDoesNotThrow();
1409
1410 // Cast the result back to the original type.
1411 return CGF.Builder.CreateBitCast(call, origType);
1412}
1413
1414/// Perform an operation having the following signature:
1415/// i8* (i8**)
1416static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1417 llvm::Value *addr,
1418 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001419 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001420 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001421 std::vector<llvm::Type*> args(1, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001422 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001423 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1424 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1425 }
1426
1427 // Cast the argument to 'id*'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001428 llvm::Type *origType = addr->getType();
John McCallf85e1932011-06-15 23:02:42 +00001429 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1430
1431 // Call the function.
1432 llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr);
1433 call->setDoesNotThrow();
1434
1435 // Cast the result back to a dereference of the original type.
1436 llvm::Value *result = call;
1437 if (origType != CGF.Int8PtrPtrTy)
1438 result = CGF.Builder.CreateBitCast(result,
1439 cast<llvm::PointerType>(origType)->getElementType());
1440
1441 return result;
1442}
1443
1444/// Perform an operation having the following signature:
1445/// i8* (i8**, i8*)
1446static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1447 llvm::Value *addr,
1448 llvm::Value *value,
1449 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001450 StringRef fnName,
John McCallf85e1932011-06-15 23:02:42 +00001451 bool ignored) {
1452 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1453 == value->getType());
1454
1455 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001456 std::vector<llvm::Type*> argTypes(2);
John McCallf85e1932011-06-15 23:02:42 +00001457 argTypes[0] = CGF.Int8PtrPtrTy;
1458 argTypes[1] = CGF.Int8PtrTy;
1459
Chris Lattner2acc6e32011-07-18 04:24:23 +00001460 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001461 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1462 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1463 }
1464
Chris Lattner2acc6e32011-07-18 04:24:23 +00001465 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001466
1467 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1468 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1469
1470 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value);
1471 result->setDoesNotThrow();
1472
1473 if (ignored) return 0;
1474
1475 return CGF.Builder.CreateBitCast(result, origType);
1476}
1477
1478/// Perform an operation having the following signature:
1479/// void (i8**, i8**)
1480static void emitARCCopyOperation(CodeGenFunction &CGF,
1481 llvm::Value *dst,
1482 llvm::Value *src,
1483 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001484 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001485 assert(dst->getType() == src->getType());
1486
1487 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001488 std::vector<llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001489 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001490 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1491 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1492 }
1493
1494 dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy);
1495 src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy);
1496
1497 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src);
1498 result->setDoesNotThrow();
1499}
1500
1501/// Produce the code to do a retain. Based on the type, calls one of:
1502/// call i8* @objc_retain(i8* %value)
1503/// call i8* @objc_retainBlock(i8* %value)
1504llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1505 if (type->isBlockPointerType())
1506 return EmitARCRetainBlock(value);
1507 else
1508 return EmitARCRetainNonBlock(value);
1509}
1510
1511/// Retain the given object, with normal retain semantics.
1512/// call i8* @objc_retain(i8* %value)
1513llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1514 return emitARCValueOperation(*this, value,
1515 CGM.getARCEntrypoints().objc_retain,
1516 "objc_retain");
1517}
1518
1519/// Retain the given block, with _Block_copy semantics.
1520/// call i8* @objc_retainBlock(i8* %value)
1521llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value) {
1522 return emitARCValueOperation(*this, value,
1523 CGM.getARCEntrypoints().objc_retainBlock,
1524 "objc_retainBlock");
1525}
1526
1527/// Retain the given object which is the result of a function call.
1528/// call i8* @objc_retainAutoreleasedReturnValue(i8* %value)
1529///
1530/// Yes, this function name is one character away from a different
1531/// call with completely different semantics.
1532llvm::Value *
1533CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1534 // Fetch the void(void) inline asm which marks that we're going to
1535 // retain the autoreleased return value.
1536 llvm::InlineAsm *&marker
1537 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1538 if (!marker) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001539 StringRef assembly
John McCallf85e1932011-06-15 23:02:42 +00001540 = CGM.getTargetCodeGenInfo()
1541 .getARCRetainAutoreleasedReturnValueMarker();
1542
1543 // If we have an empty assembly string, there's nothing to do.
1544 if (assembly.empty()) {
1545
1546 // Otherwise, at -O0, build an inline asm that we're going to call
1547 // in a moment.
1548 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1549 llvm::FunctionType *type =
1550 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
1551 /*variadic*/ false);
1552
1553 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1554
1555 // If we're at -O1 and above, we don't want to litter the code
1556 // with this marker yet, so leave a breadcrumb for the ARC
1557 // optimizer to pick up.
1558 } else {
1559 llvm::NamedMDNode *metadata =
1560 CGM.getModule().getOrInsertNamedMetadata(
1561 "clang.arc.retainAutoreleasedReturnValueMarker");
1562 assert(metadata->getNumOperands() <= 1);
1563 if (metadata->getNumOperands() == 0) {
1564 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
Jay Foadda549e82011-07-29 13:56:53 +00001565 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
John McCallf85e1932011-06-15 23:02:42 +00001566 }
1567 }
1568 }
1569
1570 // Call the marker asm if we made one, which we do only at -O0.
1571 if (marker) Builder.CreateCall(marker);
1572
1573 return emitARCValueOperation(*this, value,
1574 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1575 "objc_retainAutoreleasedReturnValue");
1576}
1577
1578/// Release the given object.
1579/// call void @objc_release(i8* %value)
1580void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) {
1581 if (isa<llvm::ConstantPointerNull>(value)) return;
1582
1583 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1584 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001585 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001586 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001587 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1588 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1589 }
1590
1591 // Cast the argument to 'id'.
1592 value = Builder.CreateBitCast(value, Int8PtrTy);
1593
1594 // Call objc_release.
1595 llvm::CallInst *call = Builder.CreateCall(fn, value);
1596 call->setDoesNotThrow();
1597
1598 if (!precise) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001599 SmallVector<llvm::Value*,1> args;
John McCallf85e1932011-06-15 23:02:42 +00001600 call->setMetadata("clang.imprecise_release",
1601 llvm::MDNode::get(Builder.getContext(), args));
1602 }
1603}
1604
1605/// Store into a strong object. Always calls this:
1606/// call void @objc_storeStrong(i8** %addr, i8* %value)
1607llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
1608 llvm::Value *value,
1609 bool ignored) {
1610 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1611 == value->getType());
1612
1613 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
1614 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001615 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2acc6e32011-07-18 04:24:23 +00001616 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001617 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
1618 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
1619 }
1620
1621 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1622 llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy);
1623
1624 Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow();
1625
1626 if (ignored) return 0;
1627 return value;
1628}
1629
1630/// Store into a strong object. Sometimes calls this:
1631/// call void @objc_storeStrong(i8** %addr, i8* %value)
1632/// Other times, breaks it down into components.
John McCall545d9962011-06-25 02:11:03 +00001633llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCallf85e1932011-06-15 23:02:42 +00001634 llvm::Value *newValue,
1635 bool ignored) {
John McCall545d9962011-06-25 02:11:03 +00001636 QualType type = dst.getType();
John McCallf85e1932011-06-15 23:02:42 +00001637 bool isBlock = type->isBlockPointerType();
1638
1639 // Use a store barrier at -O0 unless this is a block type or the
1640 // lvalue is inadequately aligned.
1641 if (shouldUseFusedARCCalls() &&
1642 !isBlock &&
1643 !(dst.getAlignment() && dst.getAlignment() < PointerAlignInBytes)) {
1644 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
1645 }
1646
1647 // Otherwise, split it out.
1648
1649 // Retain the new value.
1650 newValue = EmitARCRetain(type, newValue);
1651
1652 // Read the old value.
John McCall545d9962011-06-25 02:11:03 +00001653 llvm::Value *oldValue = EmitLoadOfScalar(dst);
John McCallf85e1932011-06-15 23:02:42 +00001654
1655 // Store. We do this before the release so that any deallocs won't
1656 // see the old value.
John McCall545d9962011-06-25 02:11:03 +00001657 EmitStoreOfScalar(newValue, dst);
John McCallf85e1932011-06-15 23:02:42 +00001658
1659 // Finally, release the old value.
1660 EmitARCRelease(oldValue, /*precise*/ false);
1661
1662 return newValue;
1663}
1664
1665/// Autorelease the given object.
1666/// call i8* @objc_autorelease(i8* %value)
1667llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
1668 return emitARCValueOperation(*this, value,
1669 CGM.getARCEntrypoints().objc_autorelease,
1670 "objc_autorelease");
1671}
1672
1673/// Autorelease the given object.
1674/// call i8* @objc_autoreleaseReturnValue(i8* %value)
1675llvm::Value *
1676CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
1677 return emitARCValueOperation(*this, value,
1678 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
1679 "objc_autoreleaseReturnValue");
1680}
1681
1682/// Do a fused retain/autorelease of the given object.
1683/// call i8* @objc_retainAutoreleaseReturnValue(i8* %value)
1684llvm::Value *
1685CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
1686 return emitARCValueOperation(*this, value,
1687 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
1688 "objc_retainAutoreleaseReturnValue");
1689}
1690
1691/// Do a fused retain/autorelease of the given object.
1692/// call i8* @objc_retainAutorelease(i8* %value)
1693/// or
1694/// %retain = call i8* @objc_retainBlock(i8* %value)
1695/// call i8* @objc_autorelease(i8* %retain)
1696llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
1697 llvm::Value *value) {
1698 if (!type->isBlockPointerType())
1699 return EmitARCRetainAutoreleaseNonBlock(value);
1700
1701 if (isa<llvm::ConstantPointerNull>(value)) return value;
1702
Chris Lattner2acc6e32011-07-18 04:24:23 +00001703 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001704 value = Builder.CreateBitCast(value, Int8PtrTy);
1705 value = EmitARCRetainBlock(value);
1706 value = EmitARCAutorelease(value);
1707 return Builder.CreateBitCast(value, origType);
1708}
1709
1710/// Do a fused retain/autorelease of the given object.
1711/// call i8* @objc_retainAutorelease(i8* %value)
1712llvm::Value *
1713CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
1714 return emitARCValueOperation(*this, value,
1715 CGM.getARCEntrypoints().objc_retainAutorelease,
1716 "objc_retainAutorelease");
1717}
1718
1719/// i8* @objc_loadWeak(i8** %addr)
1720/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
1721llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
1722 return emitARCLoadOperation(*this, addr,
1723 CGM.getARCEntrypoints().objc_loadWeak,
1724 "objc_loadWeak");
1725}
1726
1727/// i8* @objc_loadWeakRetained(i8** %addr)
1728llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
1729 return emitARCLoadOperation(*this, addr,
1730 CGM.getARCEntrypoints().objc_loadWeakRetained,
1731 "objc_loadWeakRetained");
1732}
1733
1734/// i8* @objc_storeWeak(i8** %addr, i8* %value)
1735/// Returns %value.
1736llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
1737 llvm::Value *value,
1738 bool ignored) {
1739 return emitARCStoreOperation(*this, addr, value,
1740 CGM.getARCEntrypoints().objc_storeWeak,
1741 "objc_storeWeak", ignored);
1742}
1743
1744/// i8* @objc_initWeak(i8** %addr, i8* %value)
1745/// Returns %value. %addr is known to not have a current weak entry.
1746/// Essentially equivalent to:
1747/// *addr = nil; objc_storeWeak(addr, value);
1748void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
1749 // If we're initializing to null, just write null to memory; no need
1750 // to get the runtime involved. But don't do this if optimization
1751 // is enabled, because accounting for this would make the optimizer
1752 // much more complicated.
1753 if (isa<llvm::ConstantPointerNull>(value) &&
1754 CGM.getCodeGenOpts().OptimizationLevel == 0) {
1755 Builder.CreateStore(value, addr);
1756 return;
1757 }
1758
1759 emitARCStoreOperation(*this, addr, value,
1760 CGM.getARCEntrypoints().objc_initWeak,
1761 "objc_initWeak", /*ignored*/ true);
1762}
1763
1764/// void @objc_destroyWeak(i8** %addr)
1765/// Essentially objc_storeWeak(addr, nil).
1766void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
1767 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
1768 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001769 std::vector<llvm::Type*> args(1, Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001770 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001771 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1772 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
1773 }
1774
1775 // Cast the argument to 'id*'.
1776 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1777
1778 llvm::CallInst *call = Builder.CreateCall(fn, addr);
1779 call->setDoesNotThrow();
1780}
1781
1782/// void @objc_moveWeak(i8** %dest, i8** %src)
1783/// Disregards the current value in %dest. Leaves %src pointing to nothing.
1784/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
1785void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
1786 emitARCCopyOperation(*this, dst, src,
1787 CGM.getARCEntrypoints().objc_moveWeak,
1788 "objc_moveWeak");
1789}
1790
1791/// void @objc_copyWeak(i8** %dest, i8** %src)
1792/// Disregards the current value in %dest. Essentially
1793/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
1794void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
1795 emitARCCopyOperation(*this, dst, src,
1796 CGM.getARCEntrypoints().objc_copyWeak,
1797 "objc_copyWeak");
1798}
1799
1800/// Produce the code to do a objc_autoreleasepool_push.
1801/// call i8* @objc_autoreleasePoolPush(void)
1802llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
1803 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
1804 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001805 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001806 llvm::FunctionType::get(Int8PtrTy, false);
1807 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
1808 }
1809
1810 llvm::CallInst *call = Builder.CreateCall(fn);
1811 call->setDoesNotThrow();
1812
1813 return call;
1814}
1815
1816/// Produce the code to do a primitive release.
1817/// call void @objc_autoreleasePoolPop(i8* %ptr)
1818void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
1819 assert(value->getType() == Int8PtrTy);
1820
1821 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
1822 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001823 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001824 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001825 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1826
1827 // We don't want to use a weak import here; instead we should not
1828 // fall into this path.
1829 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
1830 }
1831
1832 llvm::CallInst *call = Builder.CreateCall(fn, value);
1833 call->setDoesNotThrow();
1834}
1835
1836/// Produce the code to do an MRR version objc_autoreleasepool_push.
1837/// Which is: [[NSAutoreleasePool alloc] init];
1838/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
1839/// init is declared as: - (id) init; in its NSObject super class.
1840///
1841llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
1842 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
1843 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder);
1844 // [NSAutoreleasePool alloc]
1845 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
1846 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
1847 CallArgList Args;
1848 RValue AllocRV =
1849 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
1850 getContext().getObjCIdType(),
1851 AllocSel, Receiver, Args);
1852
1853 // [Receiver init]
1854 Receiver = AllocRV.getScalarVal();
1855 II = &CGM.getContext().Idents.get("init");
1856 Selector InitSel = getContext().Selectors.getSelector(0, &II);
1857 RValue InitRV =
1858 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
1859 getContext().getObjCIdType(),
1860 InitSel, Receiver, Args);
1861 return InitRV.getScalarVal();
1862}
1863
1864/// Produce the code to do a primitive release.
1865/// [tmp drain];
1866void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
1867 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
1868 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
1869 CallArgList Args;
1870 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1871 getContext().VoidTy, DrainSel, Arg, Args);
1872}
1873
John McCallbdc4d802011-07-09 01:37:26 +00001874void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
1875 llvm::Value *addr,
1876 QualType type) {
1877 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
1878 CGF.EmitARCRelease(ptr, /*precise*/ true);
1879}
1880
1881void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
1882 llvm::Value *addr,
1883 QualType type) {
1884 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
1885 CGF.EmitARCRelease(ptr, /*precise*/ false);
1886}
1887
1888void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
1889 llvm::Value *addr,
1890 QualType type) {
1891 CGF.EmitARCDestroyWeak(addr);
1892}
1893
John McCallf85e1932011-06-15 23:02:42 +00001894namespace {
John McCallf85e1932011-06-15 23:02:42 +00001895 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
1896 llvm::Value *Token;
1897
1898 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
1899
John McCallad346f42011-07-12 20:27:29 +00001900 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001901 CGF.EmitObjCAutoreleasePoolPop(Token);
1902 }
1903 };
1904 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
1905 llvm::Value *Token;
1906
1907 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
1908
John McCallad346f42011-07-12 20:27:29 +00001909 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001910 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
1911 }
1912 };
1913}
1914
1915void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
1916 if (CGM.getLangOptions().ObjCAutoRefCount)
1917 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
1918 else
1919 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
1920}
1921
John McCallf85e1932011-06-15 23:02:42 +00001922static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
1923 LValue lvalue,
1924 QualType type) {
1925 switch (type.getObjCLifetime()) {
1926 case Qualifiers::OCL_None:
1927 case Qualifiers::OCL_ExplicitNone:
1928 case Qualifiers::OCL_Strong:
1929 case Qualifiers::OCL_Autoreleasing:
John McCall545d9962011-06-25 02:11:03 +00001930 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(),
John McCallf85e1932011-06-15 23:02:42 +00001931 false);
1932
1933 case Qualifiers::OCL_Weak:
1934 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
1935 true);
1936 }
1937
1938 llvm_unreachable("impossible lifetime!");
1939 return TryEmitResult();
1940}
1941
1942static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
1943 const Expr *e) {
1944 e = e->IgnoreParens();
1945 QualType type = e->getType();
1946
John McCall21480112011-08-30 00:57:29 +00001947 // If we're loading retained from a __strong xvalue, we can avoid
1948 // an extra retain/release pair by zeroing out the source of this
1949 // "move" operation.
1950 if (e->isXValue() &&
1951 !type.isConstQualified() &&
1952 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
1953 // Emit the lvalue.
1954 LValue lv = CGF.EmitLValue(e);
1955
1956 // Load the object pointer.
1957 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal();
1958
1959 // Set the source pointer to NULL.
1960 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
1961
1962 return TryEmitResult(result, true);
1963 }
1964
John McCallf85e1932011-06-15 23:02:42 +00001965 // As a very special optimization, in ARC++, if the l-value is the
1966 // result of a non-volatile assignment, do a simple retain of the
1967 // result of the call to objc_storeWeak instead of reloading.
1968 if (CGF.getLangOptions().CPlusPlus &&
1969 !type.isVolatileQualified() &&
1970 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
1971 isa<BinaryOperator>(e) &&
1972 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
1973 return TryEmitResult(CGF.EmitScalarExpr(e), false);
1974
1975 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
1976}
1977
1978static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
1979 llvm::Value *value);
1980
1981/// Given that the given expression is some sort of call (which does
1982/// not return retained), emit a retain following it.
1983static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
1984 llvm::Value *value = CGF.EmitScalarExpr(e);
1985 return emitARCRetainAfterCall(CGF, value);
1986}
1987
1988static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
1989 llvm::Value *value) {
1990 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
1991 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
1992
1993 // Place the retain immediately following the call.
1994 CGF.Builder.SetInsertPoint(call->getParent(),
1995 ++llvm::BasicBlock::iterator(call));
1996 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1997
1998 CGF.Builder.restoreIP(ip);
1999 return value;
2000 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2001 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2002
2003 // Place the retain at the beginning of the normal destination block.
2004 llvm::BasicBlock *BB = invoke->getNormalDest();
2005 CGF.Builder.SetInsertPoint(BB, BB->begin());
2006 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2007
2008 CGF.Builder.restoreIP(ip);
2009 return value;
2010
2011 // Bitcasts can arise because of related-result returns. Rewrite
2012 // the operand.
2013 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2014 llvm::Value *operand = bitcast->getOperand(0);
2015 operand = emitARCRetainAfterCall(CGF, operand);
2016 bitcast->setOperand(0, operand);
2017 return bitcast;
2018
2019 // Generic fall-back case.
2020 } else {
2021 // Retain using the non-block variant: we never need to do a copy
2022 // of a block that's been returned to us.
2023 return CGF.EmitARCRetainNonBlock(value);
2024 }
2025}
2026
John McCalldc05b112011-09-10 01:16:55 +00002027/// Determine whether it might be important to emit a separate
2028/// objc_retain_block on the result of the given expression, or
2029/// whether it's okay to just emit it in a +1 context.
2030static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2031 assert(e->getType()->isBlockPointerType());
2032 e = e->IgnoreParens();
2033
2034 // For future goodness, emit block expressions directly in +1
2035 // contexts if we can.
2036 if (isa<BlockExpr>(e))
2037 return false;
2038
2039 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2040 switch (cast->getCastKind()) {
2041 // Emitting these operations in +1 contexts is goodness.
2042 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00002043 case CK_ARCReclaimReturnedObject:
2044 case CK_ARCConsumeObject:
2045 case CK_ARCProduceObject:
John McCalldc05b112011-09-10 01:16:55 +00002046 return false;
2047
2048 // These operations preserve a block type.
2049 case CK_NoOp:
2050 case CK_BitCast:
2051 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2052
2053 // These operations are known to be bad (or haven't been considered).
2054 case CK_AnyPointerToBlockPointerCast:
2055 default:
2056 return true;
2057 }
2058 }
2059
2060 return true;
2061}
2062
John McCallf85e1932011-06-15 23:02:42 +00002063static TryEmitResult
2064tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCall990567c2011-07-27 01:07:15 +00002065 // Look through cleanups.
2066 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2067 CodeGenFunction::RunCleanupsScope scope(CGF);
2068 return tryEmitARCRetainScalarExpr(CGF, cleanups->getSubExpr());
2069 }
2070
John McCallf85e1932011-06-15 23:02:42 +00002071 // The desired result type, if it differs from the type of the
2072 // ultimate opaque expression.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002073 llvm::Type *resultType = 0;
John McCallf85e1932011-06-15 23:02:42 +00002074
2075 while (true) {
2076 e = e->IgnoreParens();
2077
2078 // There's a break at the end of this if-chain; anything
2079 // that wants to keep looping has to explicitly continue.
2080 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2081 switch (ce->getCastKind()) {
2082 // No-op casts don't change the type, so we just ignore them.
2083 case CK_NoOp:
2084 e = ce->getSubExpr();
2085 continue;
2086
2087 case CK_LValueToRValue: {
2088 TryEmitResult loadResult
2089 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2090 if (resultType) {
2091 llvm::Value *value = loadResult.getPointer();
2092 value = CGF.Builder.CreateBitCast(value, resultType);
2093 loadResult.setPointer(value);
2094 }
2095 return loadResult;
2096 }
2097
2098 // These casts can change the type, so remember that and
2099 // soldier on. We only need to remember the outermost such
2100 // cast, though.
John McCall1d9b3b22011-09-09 05:25:32 +00002101 case CK_CPointerToObjCPointerCast:
2102 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00002103 case CK_AnyPointerToBlockPointerCast:
2104 case CK_BitCast:
2105 if (!resultType)
2106 resultType = CGF.ConvertType(ce->getType());
2107 e = ce->getSubExpr();
2108 assert(e->getType()->hasPointerRepresentation());
2109 continue;
2110
2111 // For consumptions, just emit the subexpression and thus elide
2112 // the retain/release pair.
John McCall33e56f32011-09-10 06:18:15 +00002113 case CK_ARCConsumeObject: {
John McCallf85e1932011-06-15 23:02:42 +00002114 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2115 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2116 return TryEmitResult(result, true);
2117 }
2118
John McCalldc05b112011-09-10 01:16:55 +00002119 // Block extends are net +0. Naively, we could just recurse on
2120 // the subexpression, but actually we need to ensure that the
2121 // value is copied as a block, so there's a little filter here.
John McCall33e56f32011-09-10 06:18:15 +00002122 case CK_ARCExtendBlockObject: {
John McCalldc05b112011-09-10 01:16:55 +00002123 llvm::Value *result; // will be a +0 value
2124
2125 // If we can't safely assume the sub-expression will produce a
2126 // block-copied value, emit the sub-expression at +0.
2127 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2128 result = CGF.EmitScalarExpr(ce->getSubExpr());
2129
2130 // Otherwise, try to emit the sub-expression at +1 recursively.
2131 } else {
2132 TryEmitResult subresult
2133 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2134 result = subresult.getPointer();
2135
2136 // If that produced a retained value, just use that,
2137 // possibly casting down.
2138 if (subresult.getInt()) {
2139 if (resultType)
2140 result = CGF.Builder.CreateBitCast(result, resultType);
2141 return TryEmitResult(result, true);
2142 }
2143
2144 // Otherwise it's +0.
2145 }
2146
2147 // Retain the object as a block, then cast down.
2148 result = CGF.EmitARCRetainBlock(result);
2149 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2150 return TryEmitResult(result, true);
2151 }
2152
John McCall7e5e5f42011-07-07 06:58:02 +00002153 // For reclaims, emit the subexpression as a retained call and
2154 // skip the consumption.
John McCall33e56f32011-09-10 06:18:15 +00002155 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00002156 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2157 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2158 return TryEmitResult(result, true);
2159 }
2160
John McCallf85e1932011-06-15 23:02:42 +00002161 case CK_GetObjCProperty: {
2162 llvm::Value *result = emitARCRetainCall(CGF, ce);
2163 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2164 return TryEmitResult(result, true);
2165 }
2166
2167 default:
2168 break;
2169 }
2170
2171 // Skip __extension__.
2172 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2173 if (op->getOpcode() == UO_Extension) {
2174 e = op->getSubExpr();
2175 continue;
2176 }
2177
2178 // For calls and message sends, use the retained-call logic.
2179 // Delegate inits are a special case in that they're the only
2180 // returns-retained expression that *isn't* surrounded by
2181 // a consume.
2182 } else if (isa<CallExpr>(e) ||
2183 (isa<ObjCMessageExpr>(e) &&
2184 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2185 llvm::Value *result = emitARCRetainCall(CGF, e);
2186 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2187 return TryEmitResult(result, true);
2188 }
2189
2190 // Conservatively halt the search at any other expression kind.
2191 break;
2192 }
2193
2194 // We didn't find an obvious production, so emit what we've got and
2195 // tell the caller that we didn't manage to retain.
2196 llvm::Value *result = CGF.EmitScalarExpr(e);
2197 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2198 return TryEmitResult(result, false);
2199}
2200
2201static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2202 LValue lvalue,
2203 QualType type) {
2204 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2205 llvm::Value *value = result.getPointer();
2206 if (!result.getInt())
2207 value = CGF.EmitARCRetain(type, value);
2208 return value;
2209}
2210
2211/// EmitARCRetainScalarExpr - Semantically equivalent to
2212/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2213/// best-effort attempt to peephole expressions that naturally produce
2214/// retained objects.
2215llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
2216 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2217 llvm::Value *value = result.getPointer();
2218 if (!result.getInt())
2219 value = EmitARCRetain(e->getType(), value);
2220 return value;
2221}
2222
2223llvm::Value *
2224CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
2225 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2226 llvm::Value *value = result.getPointer();
2227 if (result.getInt())
2228 value = EmitARCAutorelease(value);
2229 else
2230 value = EmitARCRetainAutorelease(e->getType(), value);
2231 return value;
2232}
2233
2234std::pair<LValue,llvm::Value*>
2235CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2236 bool ignored) {
2237 // Evaluate the RHS first.
2238 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2239 llvm::Value *value = result.getPointer();
2240
John McCallfb720812011-07-28 07:23:35 +00002241 bool hasImmediateRetain = result.getInt();
2242
2243 // If we didn't emit a retained object, and the l-value is of block
2244 // type, then we need to emit the block-retain immediately in case
2245 // it invalidates the l-value.
2246 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
2247 value = EmitARCRetainBlock(value);
2248 hasImmediateRetain = true;
2249 }
2250
John McCallf85e1932011-06-15 23:02:42 +00002251 LValue lvalue = EmitLValue(e->getLHS());
2252
2253 // If the RHS was emitted retained, expand this.
John McCallfb720812011-07-28 07:23:35 +00002254 if (hasImmediateRetain) {
John McCallf85e1932011-06-15 23:02:42 +00002255 llvm::Value *oldValue =
2256 EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatileQualified(),
2257 lvalue.getAlignment(), e->getType(),
2258 lvalue.getTBAAInfo());
2259 EmitStoreOfScalar(value, lvalue.getAddress(),
2260 lvalue.isVolatileQualified(), lvalue.getAlignment(),
2261 e->getType(), lvalue.getTBAAInfo());
2262 EmitARCRelease(oldValue, /*precise*/ false);
2263 } else {
John McCall545d9962011-06-25 02:11:03 +00002264 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCallf85e1932011-06-15 23:02:42 +00002265 }
2266
2267 return std::pair<LValue,llvm::Value*>(lvalue, value);
2268}
2269
2270std::pair<LValue,llvm::Value*>
2271CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2272 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2273 LValue lvalue = EmitLValue(e->getLHS());
2274
2275 EmitStoreOfScalar(value, lvalue.getAddress(),
2276 lvalue.isVolatileQualified(), lvalue.getAlignment(),
2277 e->getType(), lvalue.getTBAAInfo());
2278
2279 return std::pair<LValue,llvm::Value*>(lvalue, value);
2280}
2281
2282void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
2283 const ObjCAutoreleasePoolStmt &ARPS) {
2284 const Stmt *subStmt = ARPS.getSubStmt();
2285 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2286
2287 CGDebugInfo *DI = getDebugInfo();
2288 if (DI) {
2289 DI->setLocation(S.getLBracLoc());
2290 DI->EmitRegionStart(Builder);
2291 }
2292
2293 // Keep track of the current cleanup stack depth.
2294 RunCleanupsScope Scope(*this);
John McCall9f084a32011-07-06 00:26:06 +00002295 if (CGM.getCodeGenOpts().ObjCRuntimeHasARC) {
John McCallf85e1932011-06-15 23:02:42 +00002296 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2297 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2298 } else {
2299 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2300 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2301 }
2302
2303 for (CompoundStmt::const_body_iterator I = S.body_begin(),
2304 E = S.body_end(); I != E; ++I)
2305 EmitStmt(*I);
2306
2307 if (DI) {
2308 DI->setLocation(S.getRBracLoc());
2309 DI->EmitRegionEnd(Builder);
2310 }
2311}
John McCall0c24c802011-06-24 23:21:27 +00002312
2313/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2314/// make sure it survives garbage collection until this point.
2315void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2316 // We just use an inline assembly.
John McCall0c24c802011-06-24 23:21:27 +00002317 llvm::FunctionType *extenderType
Jay Foadda549e82011-07-29 13:56:53 +00002318 = llvm::FunctionType::get(VoidTy, VoidPtrTy, /*variadic*/ false);
John McCall0c24c802011-06-24 23:21:27 +00002319 llvm::Value *extender
2320 = llvm::InlineAsm::get(extenderType,
2321 /* assembly */ "",
2322 /* constraints */ "r",
2323 /* side effects */ true);
2324
2325 object = Builder.CreateBitCast(object, VoidPtrTy);
2326 Builder.CreateCall(extender, object)->setDoesNotThrow();
2327}
2328
Ted Kremenek2979ec72008-04-09 15:51:31 +00002329CGObjCRuntime::~CGObjCRuntime() {}