blob: 3bc5ca91b57f9895d11b08ea98cfc41934acd79b [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
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000338/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump1eb44332009-09-09 15:08:12 +0000339/// its pointer, name, and types registered in the class struture.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000340void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
Devang Patel8d3f8972011-05-19 23:37:41 +0000341 StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000342 EmitStmt(OMD->getBody());
343 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000344}
345
John McCall41bdde92011-09-12 23:06:44 +0000346/// emitStructGetterCall - Call the runtime function to load a property
347/// into the return value slot.
348static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
349 bool isAtomic, bool hasStrong) {
350 ASTContext &Context = CGF.getContext();
351
352 llvm::Value *src =
353 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(),
354 ivar, 0).getAddress();
355
356 // objc_copyStruct (ReturnValue, &structIvar,
357 // sizeof (Type of Ivar), isAtomic, false);
358 CallArgList args;
359
360 llvm::Value *dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
361 args.add(RValue::get(dest), Context.VoidPtrTy);
362
363 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
364 args.add(RValue::get(src), Context.VoidPtrTy);
365
366 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
367 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
368 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
369 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
370
371 llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
372 CGF.EmitCall(CGF.getTypes().getFunctionInfo(Context.VoidTy, args,
373 FunctionType::ExtInfo()),
374 fn, ReturnValueSlot(), args);
375}
376
Mike Stumpf5408fe2009-05-16 07:57:57 +0000377// FIXME: I wasn't sure about the synthesis approach. If we end up generating an
378// AST for the whole body we can just fall back to having a GenerateFunction
379// which takes the body Stmt.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000380
381/// GenerateObjCGetter - Generate an Objective-C property getter
Steve Naroff489034c2009-01-10 22:55:25 +0000382/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
383/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000384void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
385 const ObjCPropertyImplDecl *PID) {
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000386 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000387 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000388 bool IsAtomic =
389 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000390 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
391 assert(OMD && "Invalid call to generate getter (empty method)");
Devang Patel8d3f8972011-05-19 23:37:41 +0000392 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000393
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000394 // Determine if we should use an objc_getProperty call for
Fariborz Jahanian447d7ae2008-12-08 23:56:17 +0000395 // this. Non-atomic properties are directly evaluated.
396 // atomic 'copy' and 'retain' properties are also directly
397 // evaluated in gc-only mode.
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000398 if (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000399 IsAtomic &&
Fariborz Jahanian447d7ae2008-12-08 23:56:17 +0000400 (PD->getSetterKind() == ObjCPropertyDecl::Copy ||
401 PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000402 llvm::Value *GetPropertyFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000403 CGM.getObjCRuntime().GetPropertyGetFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000405 if (!GetPropertyFn) {
406 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
407 FinishFunction();
408 return;
409 }
410
411 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
412 // FIXME: Can't this be simpler? This might even be worse than the
413 // corresponding gcc code.
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000414 ValueDecl *Cmd = OMD->getCmdDecl();
415 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
John McCall41bdde92011-09-12 23:06:44 +0000416 llvm::Value *SelfAsId = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000417 llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000418 CallArgList Args;
John McCall41bdde92011-09-12 23:06:44 +0000419 Args.add(RValue::get(SelfAsId), getContext().getObjCIdType());
Eli Friedman04c9a492011-05-02 17:57:46 +0000420 Args.add(RValue::get(CmdVal), Cmd->getType());
421 Args.add(RValue::get(Offset), getContext().getPointerDiffType());
John McCall41bdde92011-09-12 23:06:44 +0000422 Args.add(RValue::get(Builder.getTrue()), getContext().BoolTy);
Daniel Dunbare4be5a62009-02-03 23:43:59 +0000423 // FIXME: We shouldn't need to get the function info here, the
424 // runtime already should have computed it to build the function.
John McCall41bdde92011-09-12 23:06:44 +0000425 RValue RV = EmitCall(getTypes().getFunctionInfo(PD->getType(), Args,
426 FunctionType::ExtInfo()),
Anders Carlssonf3c47c92009-12-24 19:25:24 +0000427 GetPropertyFn, ReturnValueSlot(), Args);
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000428 // We need to fix the type here. Ivars with copy & retain are
429 // always objects so we don't need to worry about complex or
430 // aggregates.
Mike Stump1eb44332009-09-09 15:08:12 +0000431 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
John McCall41bdde92011-09-12 23:06:44 +0000432 getTypes().ConvertType(PD->getType())));
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000433 EmitReturnOfRValue(RV, PD->getType());
John McCallf85e1932011-06-15 23:02:42 +0000434
435 // objc_getProperty does an autorelease, so we should suppress ours.
436 AutoreleaseResult = false;
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000437 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000438 const llvm::Triple &Triple = getContext().getTargetInfo().getTriple();
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000439 QualType IVART = Ivar->getType();
440 if (IsAtomic &&
441 IVART->isScalarType() &&
442 (Triple.getArch() == llvm::Triple::arm ||
443 Triple.getArch() == llvm::Triple::thumb) &&
444 (getContext().getTypeSizeInChars(IVART)
445 > CharUnits::fromQuantity(4)) &&
446 CGM.getObjCRuntime().GetGetStructFunction()) {
John McCall41bdde92011-09-12 23:06:44 +0000447 emitStructGetterCall(*this, Ivar, true, false);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000448 }
Fariborz Jahanian1d3a61a2011-04-05 21:41:23 +0000449 else if (IsAtomic &&
450 (IVART->isScalarType() && !IVART->isRealFloatingType()) &&
451 Triple.getArch() == llvm::Triple::x86 &&
452 (getContext().getTypeSizeInChars(IVART)
453 > CharUnits::fromQuantity(4)) &&
454 CGM.getObjCRuntime().GetGetStructFunction()) {
John McCall41bdde92011-09-12 23:06:44 +0000455 emitStructGetterCall(*this, Ivar, true, false);
Fariborz Jahanian1d3a61a2011-04-05 21:41:23 +0000456 }
457 else if (IsAtomic &&
458 (IVART->isScalarType() && !IVART->isRealFloatingType()) &&
459 Triple.getArch() == llvm::Triple::x86_64 &&
460 (getContext().getTypeSizeInChars(IVART)
461 > CharUnits::fromQuantity(8)) &&
462 CGM.getObjCRuntime().GetGetStructFunction()) {
John McCall41bdde92011-09-12 23:06:44 +0000463 emitStructGetterCall(*this, Ivar, true, false);
Fariborz Jahanian1d3a61a2011-04-05 21:41:23 +0000464 }
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000465 else if (IVART->isAnyComplexType()) {
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000466 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
467 Ivar, 0);
Fariborz Jahanian1b23fe62010-03-25 21:56:43 +0000468 ComplexPairTy Pair = LoadComplexFromAddr(LV.getAddress(),
469 LV.isVolatileQualified());
470 StoreComplexToAddr(Pair, ReturnValue, LV.isVolatileQualified());
471 }
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000472 else if (hasAggregateLLVMType(IVART)) {
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000473 bool IsStrong = false;
Fariborz Jahanian5fb65092011-04-05 23:01:27 +0000474 if ((IsStrong = IvarTypeWithAggrGCObjects(IVART))
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000475 && CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect
David Chisnall8fac25d2010-12-26 22:13:16 +0000476 && CGM.getObjCRuntime().GetGetStructFunction()) {
John McCall41bdde92011-09-12 23:06:44 +0000477 emitStructGetterCall(*this, Ivar, IsAtomic, IsStrong);
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000478 }
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000479 else {
Fariborz Jahanian01cb3072011-04-06 16:05:26 +0000480 const CXXRecordDecl *classDecl = IVART->getAsCXXRecordDecl();
481
482 if (PID->getGetterCXXConstructor() &&
Sean Hunt023df372011-05-09 18:22:59 +0000483 classDecl && !classDecl->hasTrivialDefaultConstructor()) {
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000484 ReturnStmt *Stmt =
485 new (getContext()) ReturnStmt(SourceLocation(),
Douglas Gregor5077c382010-05-15 06:01:05 +0000486 PID->getGetterCXXConstructor(),
487 0);
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000488 EmitReturnStmt(*Stmt);
Fariborz Jahanian1d3a61a2011-04-05 21:41:23 +0000489 } else if (IsAtomic &&
490 !IVART->isAnyComplexType() &&
491 Triple.getArch() == llvm::Triple::x86 &&
492 (getContext().getTypeSizeInChars(IVART)
493 > CharUnits::fromQuantity(4)) &&
494 CGM.getObjCRuntime().GetGetStructFunction()) {
John McCall41bdde92011-09-12 23:06:44 +0000495 emitStructGetterCall(*this, Ivar, true, false);
Fariborz Jahanian1d3a61a2011-04-05 21:41:23 +0000496 }
497 else if (IsAtomic &&
498 !IVART->isAnyComplexType() &&
499 Triple.getArch() == llvm::Triple::x86_64 &&
500 (getContext().getTypeSizeInChars(IVART)
501 > CharUnits::fromQuantity(8)) &&
502 CGM.getObjCRuntime().GetGetStructFunction()) {
John McCall41bdde92011-09-12 23:06:44 +0000503 emitStructGetterCall(*this, Ivar, true, false);
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000504 }
505 else {
506 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
507 Ivar, 0);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000508 EmitAggregateCopy(ReturnValue, LV.getAddress(), IVART);
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000509 }
510 }
John McCallba3dd902011-07-22 05:23:13 +0000511 } else {
512 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
513 Ivar, 0);
514 QualType propType = PD->getType();
John McCallf85e1932011-06-15 23:02:42 +0000515
John McCallba3dd902011-07-22 05:23:13 +0000516 llvm::Value *value;
517 if (propType->isReferenceType()) {
518 value = LV.getAddress();
519 } else {
520 // We want to load and autoreleaseReturnValue ARC __weak ivars.
521 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
522 value = emitARCRetainLoadOfScalar(*this, LV, IVART);
523
524 // Otherwise we want to do a simple load, suppressing the
525 // final autorelease.
John McCallf85e1932011-06-15 23:02:42 +0000526 } else {
John McCallba3dd902011-07-22 05:23:13 +0000527 value = EmitLoadOfLValue(LV).getScalarVal();
528 AutoreleaseResult = false;
Fariborz Jahanian14086762011-03-28 23:47:18 +0000529 }
John McCallf85e1932011-06-15 23:02:42 +0000530
John McCallba3dd902011-07-22 05:23:13 +0000531 value = Builder.CreateBitCast(value, ConvertType(propType));
532 }
533
534 EmitReturnOfRValue(RValue::get(value), propType);
Fariborz Jahanianed1d29d2009-03-03 18:49:40 +0000535 }
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000536 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000537
538 FinishFunction();
539}
540
John McCall41bdde92011-09-12 23:06:44 +0000541/// emitStructSetterCall - Call the runtime function to store the value
542/// from the first formal parameter into the given ivar.
543static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
544 ObjCIvarDecl *ivar) {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000545 // objc_copyStruct (&structIvar, &Arg,
546 // sizeof (struct something), true, false);
John McCallbbb253c2011-09-10 09:30:49 +0000547 CallArgList args;
548
549 // The first argument is the address of the ivar.
John McCall41bdde92011-09-12 23:06:44 +0000550 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
551 CGF.LoadObjCSelf(), ivar, 0)
552 .getAddress();
553 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
554 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000555
556 // The second argument is the address of the parameter variable.
John McCall41bdde92011-09-12 23:06:44 +0000557 ParmVarDecl *argVar = *OMD->param_begin();
558 DeclRefExpr argRef(argVar, argVar->getType(), VK_LValue, SourceLocation());
559 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
560 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
561 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000562
563 // The third argument is the sizeof the type.
564 llvm::Value *size =
John McCall41bdde92011-09-12 23:06:44 +0000565 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
566 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCallbbb253c2011-09-10 09:30:49 +0000567
John McCall41bdde92011-09-12 23:06:44 +0000568 // The fourth argument is the 'isAtomic' flag.
569 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCallbbb253c2011-09-10 09:30:49 +0000570
John McCall41bdde92011-09-12 23:06:44 +0000571 // The fifth argument is the 'hasStrong' flag.
572 // FIXME: should this really always be false?
573 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
574
575 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
576 CGF.EmitCall(CGF.getTypes().getFunctionInfo(CGF.getContext().VoidTy, args,
577 FunctionType::ExtInfo()),
578 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000579}
580
John McCall71c758d2011-09-10 09:17:20 +0000581static bool hasTrivialAssignment(const ObjCPropertyImplDecl *PID) {
582 Expr *assign = PID->getSetterCXXAssignment();
583 if (!assign) return true;
584
585 // An operator call is trivial if the function it calls is trivial.
586 if (CallExpr *call = dyn_cast<CallExpr>(assign)) {
587 if (const FunctionDecl *callee
588 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
589 if (callee->isTrivial())
590 return true;
591 return false;
Fariborz Jahanian01cb3072011-04-06 16:05:26 +0000592 }
John McCall71c758d2011-09-10 09:17:20 +0000593
594 assert(isa<BinaryOperator>(assign));
595 return true;
596}
597
598/// Should the setter use objc_setProperty?
599static bool shouldUseSetProperty(CodeGenFunction &CGF,
600 ObjCPropertyDecl::SetterKind setterKind) {
601 // Copy setters require objc_setProperty.
602 if (setterKind == ObjCPropertyDecl::Copy)
603 return true;
604
605 // So do retain setters, if we're not in GC-only mode (where
606 // 'retain' is ignored).
607 if (setterKind == ObjCPropertyDecl::Retain &&
608 CGF.getLangOptions().getGCMode() != LangOptions::GCOnly)
609 return true;
610
611 // Otherwise, we don't need this.
612 return false;
613}
614
615static bool isAssignmentImplicitlyAtomic(CodeGenFunction &CGF,
616 const ObjCIvarDecl *ivar) {
617 // Aggregate assignment is not implicitly atomic if it includes a GC
618 // barrier.
619 QualType ivarType = ivar->getType();
620 if (CGF.getLangOptions().getGCMode())
621 if (const RecordType *ivarRecordTy = ivarType->getAs<RecordType>())
622 if (ivarRecordTy->getDecl()->hasObjectMember())
623 return false;
624
625 // Assume that any store no larger than a pointer, and as aligned as
626 // the required size, can be performed atomically.
627 ASTContext &Context = CGF.getContext();
628 std::pair<CharUnits,CharUnits> ivarSizeAndAlignment
629 = Context.getTypeInfoInChars(ivar->getType());
630
631 return (ivarSizeAndAlignment.first
632 <= CharUnits::fromQuantity(CGF.PointerSizeInBytes) &&
633 ivarSizeAndAlignment.second >= ivarSizeAndAlignment.first);
634}
635
636void
637CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
638 const ObjCPropertyImplDecl *propImpl) {
639 // Just use the setter expression if Sema gave us one and it's
640 // non-trivial. There's no way to do this atomically.
641 if (!hasTrivialAssignment(propImpl)) {
642 EmitStmt(propImpl->getSetterCXXAssignment());
643 return;
644 }
645
646 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
647 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
648 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
649
650 // A property is copy if it says it's copy.
651 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
652 bool isCopy = (setterKind == ObjCPropertyDecl::Copy);
653
654 // A property is atomic if it doesn't say it's nonatomic.
655 bool isAtomic =
656 !(prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
657
658 // Should we call the runtime's set property function?
659 if (shouldUseSetProperty(*this, setterKind)) {
660 llvm::Value *setPropertyFn =
661 CGM.getObjCRuntime().GetPropertySetFunction();
662 if (!setPropertyFn) {
663 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
664 return;
665 }
666
667 // Emit objc_setProperty((id) self, _cmd, offset, arg,
668 // <is-atomic>, <is-copy>).
669 llvm::Value *cmd =
670 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
671 llvm::Value *self =
672 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
673 llvm::Value *ivarOffset =
674 EmitIvarOffset(classImpl->getClassInterface(), ivar);
675 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
676 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
677
678 CallArgList args;
679 args.add(RValue::get(self), getContext().getObjCIdType());
680 args.add(RValue::get(cmd), getContext().getObjCSelType());
681 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
682 args.add(RValue::get(arg), getContext().getObjCIdType());
683 args.add(RValue::get(Builder.getInt1(isAtomic)), getContext().BoolTy);
684 args.add(RValue::get(Builder.getInt1(isCopy)), getContext().BoolTy);
685 // FIXME: We shouldn't need to get the function info here, the runtime
686 // already should have computed it to build the function.
687 EmitCall(getTypes().getFunctionInfo(getContext().VoidTy, args,
688 FunctionType::ExtInfo()),
689 setPropertyFn, ReturnValueSlot(), args);
690 return;
691 }
692
693 // If the property is atomic but has ARC or GC qualification, we
694 // must use the expression expansion. This isn't actually right for
695 // ARC strong, but we shouldn't actually get here for ARC strong,
696 // which should always end up using setProperty.
697 if (isAtomic &&
698 (ivar->getType().hasNonTrivialObjCLifetime() ||
699 (getLangOptions().getGCMode() &&
700 getContext().getObjCGCAttrKind(ivar->getType())))) {
701 // fallthrough
702
703 // If the property is atomic and can be implicitly performed
704 // atomically with an assignment, do so.
705 } else if (isAtomic && isAssignmentImplicitlyAtomic(*this, ivar)) {
706 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
707
708 LValue ivarLValue =
709 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
710 llvm::Value *ivarAddr = ivarLValue.getAddress();
711
712 // If necessary, use a non-aggregate type.
713 llvm::Type *eltType =
714 cast<llvm::PointerType>(ivarAddr->getType())->getElementType();
715 if (eltType->isAggregateType()) {
716 eltType = llvm::Type::getIntNTy(getLLVMContext(),
717 getContext().getTypeSize(ivar->getType()));
718 }
719
720 // Cast both arguments to the chosen operation type.
721 argAddr = Builder.CreateBitCast(argAddr, eltType->getPointerTo());
722 ivarAddr = Builder.CreateBitCast(ivarAddr, eltType->getPointerTo());
723
724 // Emit a single store.
725 // TODO: this should be a 'store atomic unordered'.
726 Builder.CreateStore(Builder.CreateLoad(argAddr), ivarAddr);
727 return;
728
729 // Otherwise, if the property is atomic, try to use the runtime's
730 // atomic-store-struct routine.
731 } else if (isAtomic && CGM.getObjCRuntime().GetSetStructFunction()) {
John McCall41bdde92011-09-12 23:06:44 +0000732 emitStructSetterCall(*this, setterMethod, ivar);
John McCall71c758d2011-09-10 09:17:20 +0000733 return;
734 }
735
736 // Otherwise, fake up some ASTs and emit a normal assignment.
737 ValueDecl *selfDecl = setterMethod->getSelfDecl();
738 DeclRefExpr self(selfDecl, selfDecl->getType(), VK_LValue, SourceLocation());
739 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
740 selfDecl->getType(), CK_LValueToRValue, &self,
741 VK_RValue);
742 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
743 SourceLocation(), &selfLoad, true, true);
744
745 ParmVarDecl *argDecl = *setterMethod->param_begin();
746 QualType argType = argDecl->getType().getNonReferenceType();
747 DeclRefExpr arg(argDecl, argType, VK_LValue, SourceLocation());
748 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
749 argType.getUnqualifiedType(), CK_LValueToRValue,
750 &arg, VK_RValue);
751
752 // The property type can differ from the ivar type in some situations with
753 // Objective-C pointer types, we can always bit cast the RHS in these cases.
754 // The following absurdity is just to ensure well-formed IR.
755 CastKind argCK = CK_NoOp;
756 if (ivarRef.getType()->isObjCObjectPointerType()) {
757 if (argLoad.getType()->isObjCObjectPointerType())
758 argCK = CK_BitCast;
759 else if (argLoad.getType()->isBlockPointerType())
760 argCK = CK_BlockPointerToObjCPointerCast;
761 else
762 argCK = CK_CPointerToObjCPointerCast;
763 } else if (ivarRef.getType()->isBlockPointerType()) {
764 if (argLoad.getType()->isBlockPointerType())
765 argCK = CK_BitCast;
766 else
767 argCK = CK_AnyPointerToBlockPointerCast;
768 } else if (ivarRef.getType()->isPointerType()) {
769 argCK = CK_BitCast;
770 }
771 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
772 ivarRef.getType(), argCK, &argLoad,
773 VK_RValue);
774 Expr *finalArg = &argLoad;
775 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
776 argLoad.getType()))
777 finalArg = &argCast;
778
779
780 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
781 ivarRef.getType(), VK_RValue, OK_Ordinary,
782 SourceLocation());
783 EmitStmt(&assign);
Fariborz Jahanian01cb3072011-04-06 16:05:26 +0000784}
785
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000786/// GenerateObjCSetter - Generate an Objective-C property setter
Steve Naroff489034c2009-01-10 22:55:25 +0000787/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
788/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000789void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
790 const ObjCPropertyImplDecl *PID) {
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000791 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
792 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
793 assert(OMD && "Invalid call to generate setter (empty method)");
Devang Patel8d3f8972011-05-19 23:37:41 +0000794 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000795
John McCall71c758d2011-09-10 09:17:20 +0000796 generateObjCSetterBody(IMP, PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000797
798 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +0000799}
800
John McCalle81ac692011-03-22 07:05:39 +0000801namespace {
John McCall9928c482011-07-12 16:41:08 +0000802 struct DestroyIvar : EHScopeStack::Cleanup {
803 private:
804 llvm::Value *addr;
John McCalle81ac692011-03-22 07:05:39 +0000805 const ObjCIvarDecl *ivar;
John McCall9928c482011-07-12 16:41:08 +0000806 CodeGenFunction::Destroyer &destroyer;
807 bool useEHCleanupForArray;
808 public:
809 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
810 CodeGenFunction::Destroyer *destroyer,
811 bool useEHCleanupForArray)
812 : addr(addr), ivar(ivar), destroyer(*destroyer),
813 useEHCleanupForArray(useEHCleanupForArray) {}
John McCalle81ac692011-03-22 07:05:39 +0000814
John McCallad346f42011-07-12 20:27:29 +0000815 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +0000816 LValue lvalue
817 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
818 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +0000819 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCalle81ac692011-03-22 07:05:39 +0000820 }
821 };
822}
823
John McCall9928c482011-07-12 16:41:08 +0000824/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
825static void destroyARCStrongWithStore(CodeGenFunction &CGF,
826 llvm::Value *addr,
827 QualType type) {
828 llvm::Value *null = getNullForVariable(addr);
829 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
830}
John McCallf85e1932011-06-15 23:02:42 +0000831
John McCalle81ac692011-03-22 07:05:39 +0000832static void emitCXXDestructMethod(CodeGenFunction &CGF,
833 ObjCImplementationDecl *impl) {
834 CodeGenFunction::RunCleanupsScope scope(CGF);
835
836 llvm::Value *self = CGF.LoadObjCSelf();
837
Jordy Rosedb8264e2011-07-22 02:08:32 +0000838 const ObjCInterfaceDecl *iface = impl->getClassInterface();
839 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +0000840 ivar; ivar = ivar->getNextIvar()) {
841 QualType type = ivar->getType();
842
John McCalle81ac692011-03-22 07:05:39 +0000843 // Check whether the ivar is a destructible type.
John McCall9928c482011-07-12 16:41:08 +0000844 QualType::DestructionKind dtorKind = type.isDestructedType();
845 if (!dtorKind) continue;
John McCalle81ac692011-03-22 07:05:39 +0000846
John McCall9928c482011-07-12 16:41:08 +0000847 CodeGenFunction::Destroyer *destroyer = 0;
John McCalle81ac692011-03-22 07:05:39 +0000848
John McCall9928c482011-07-12 16:41:08 +0000849 // Use a call to objc_storeStrong to destroy strong ivars, for the
850 // general benefit of the tools.
851 if (dtorKind == QualType::DK_objc_strong_lifetime) {
852 destroyer = &destroyARCStrongWithStore;
John McCallf85e1932011-06-15 23:02:42 +0000853
John McCall9928c482011-07-12 16:41:08 +0000854 // Otherwise use the default for the destruction kind.
855 } else {
856 destroyer = &CGF.getDestroyer(dtorKind);
John McCalle81ac692011-03-22 07:05:39 +0000857 }
John McCall9928c482011-07-12 16:41:08 +0000858
859 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
860
861 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
862 cleanupKind & EHCleanup);
John McCalle81ac692011-03-22 07:05:39 +0000863 }
864
865 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
866}
867
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000868void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
869 ObjCMethodDecl *MD,
870 bool ctor) {
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000871 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Devang Patel8d3f8972011-05-19 23:37:41 +0000872 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
John McCalle81ac692011-03-22 07:05:39 +0000873
874 // Emit .cxx_construct.
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000875 if (ctor) {
John McCallf85e1932011-06-15 23:02:42 +0000876 // Suppress the final autorelease in ARC.
877 AutoreleaseResult = false;
878
Chris Lattner5f9e2722011-07-23 10:55:15 +0000879 SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
John McCalle81ac692011-03-22 07:05:39 +0000880 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
881 E = IMP->init_end(); B != E; ++B) {
882 CXXCtorInitializer *IvarInit = (*B);
Francois Pichet00eb3f92010-12-04 09:14:42 +0000883 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000884 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian9b4d4fc2010-04-28 22:30:33 +0000885 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
886 LoadObjCSelf(), Ivar, 0);
John McCall7c2349b2011-08-25 20:40:09 +0000887 EmitAggExpr(IvarInit->getInit(),
888 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +0000889 AggValueSlot::DoesNotNeedGCBarriers,
890 AggValueSlot::IsNotAliased));
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000891 }
892 // constructor returns 'self'.
893 CodeGenTypes &Types = CGM.getTypes();
894 QualType IdTy(CGM.getContext().getObjCIdType());
895 llvm::Value *SelfAsId =
896 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
897 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCalle81ac692011-03-22 07:05:39 +0000898
899 // Emit .cxx_destruct.
Chandler Carruthbc397cf2010-05-06 00:20:39 +0000900 } else {
John McCalle81ac692011-03-22 07:05:39 +0000901 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000902 }
903 FinishFunction();
904}
905
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000906bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
907 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
908 it++; it++;
909 const ABIArgInfo &AI = it->info;
910 // FIXME. Is this sufficient check?
911 return (AI.getKind() == ABIArgInfo::Indirect);
912}
913
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000914bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
915 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
916 return false;
917 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
918 return FDTTy->getDecl()->hasObjectMember();
919 return false;
920}
921
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000922llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000923 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
924 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner41110242008-06-17 18:05:57 +0000925}
926
Fariborz Jahanian45012a72009-02-03 00:09:52 +0000927QualType CodeGenFunction::TypeOfSelfObject() {
928 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
929 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff14108da2009-07-10 23:34:53 +0000930 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
931 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanian45012a72009-02-03 00:09:52 +0000932 return PTy->getPointeeType();
933}
934
John McCalle68b9842010-12-04 03:11:00 +0000935LValue
936CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
937 // This is a special l-value that just issues sends when we load or
938 // store through it.
939
940 // For certain base kinds, we need to emit the base immediately.
941 llvm::Value *Base;
942 if (E->isSuperReceiver())
943 Base = LoadObjCSelf();
944 else if (E->isClassReceiver())
945 Base = CGM.getObjCRuntime().GetClass(Builder, E->getClassReceiver());
946 else
947 Base = EmitScalarExpr(E->getBase());
948 return LValue::MakePropertyRef(E, Base);
949}
950
951static RValue GenerateMessageSendSuper(CodeGenFunction &CGF,
952 ReturnValueSlot Return,
953 QualType ResultType,
954 Selector S,
955 llvm::Value *Receiver,
956 const CallArgList &CallArgs) {
957 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CGF.CurFuncDecl);
Fariborz Jahanianf4695572009-03-20 19:18:21 +0000958 bool isClassMessage = OMD->isClassMethod();
959 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
John McCalle68b9842010-12-04 03:11:00 +0000960 return CGF.CGM.getObjCRuntime()
961 .GenerateMessageSendSuper(CGF, Return, ResultType,
962 S, OMD->getClassInterface(),
963 isCategoryImpl, Receiver,
964 isClassMessage, CallArgs);
Fariborz Jahanianf4695572009-03-20 19:18:21 +0000965}
966
John McCall119a1c62010-12-04 02:32:38 +0000967RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
968 ReturnValueSlot Return) {
969 const ObjCPropertyRefExpr *E = LV.getPropertyRefExpr();
Fariborz Jahanian68af13f2011-03-30 16:11:20 +0000970 QualType ResultType = E->getGetterResultType();
John McCall12f78a62010-12-02 01:19:52 +0000971 Selector S;
Douglas Gregor926df6c2011-06-11 01:09:30 +0000972 const ObjCMethodDecl *method;
John McCall12f78a62010-12-02 01:19:52 +0000973 if (E->isExplicitProperty()) {
974 const ObjCPropertyDecl *Property = E->getExplicitProperty();
975 S = Property->getGetterName();
Douglas Gregor926df6c2011-06-11 01:09:30 +0000976 method = Property->getGetterMethodDecl();
Mike Stumpb3589f42009-07-30 22:28:39 +0000977 } else {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000978 method = E->getImplicitPropertyGetter();
979 S = method->getSelector();
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000980 }
John McCall12f78a62010-12-02 01:19:52 +0000981
John McCall119a1c62010-12-04 02:32:38 +0000982 llvm::Value *Receiver = LV.getPropertyRefBaseAddr();
John McCalle68b9842010-12-04 03:11:00 +0000983
John McCallf85e1932011-06-15 23:02:42 +0000984 if (CGM.getLangOptions().ObjCAutoRefCount) {
985 QualType receiverType;
986 if (E->isSuperReceiver())
987 receiverType = E->getSuperReceiverType();
988 else if (E->isClassReceiver())
989 receiverType = getContext().getObjCClassType();
990 else
991 receiverType = E->getBase()->getType();
992 }
993
John McCalle68b9842010-12-04 03:11:00 +0000994 // Accesses to 'super' follow a different code path.
995 if (E->isSuperReceiver())
Douglas Gregor926df6c2011-06-11 01:09:30 +0000996 return AdjustRelatedResultType(*this, E, method,
997 GenerateMessageSendSuper(*this, Return,
998 ResultType,
999 S, Receiver,
1000 CallArgList()));
John McCall119a1c62010-12-04 02:32:38 +00001001 const ObjCInterfaceDecl *ReceiverClass
1002 = (E->isClassReceiver() ? E->getClassReceiver() : 0);
Douglas Gregor926df6c2011-06-11 01:09:30 +00001003 return AdjustRelatedResultType(*this, E, method,
John McCallf85e1932011-06-15 23:02:42 +00001004 CGM.getObjCRuntime().
1005 GenerateMessageSend(*this, Return, ResultType, S,
1006 Receiver, CallArgList(), ReceiverClass));
Daniel Dunbar9c3fc702008-08-27 06:57:25 +00001007}
1008
John McCall119a1c62010-12-04 02:32:38 +00001009void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
1010 LValue Dst) {
1011 const ObjCPropertyRefExpr *E = Dst.getPropertyRefExpr();
John McCall12f78a62010-12-02 01:19:52 +00001012 Selector S = E->getSetterSelector();
Fariborz Jahanian68af13f2011-03-30 16:11:20 +00001013 QualType ArgType = E->getSetterArgType();
1014
Fariborz Jahanianb19c76e2011-02-08 22:33:23 +00001015 // FIXME. Other than scalars, AST is not adequate for setter and
1016 // getter type mismatches which require conversion.
1017 if (Src.isScalar()) {
1018 llvm::Value *SrcVal = Src.getScalarVal();
1019 QualType DstType = getContext().getCanonicalType(ArgType);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001020 llvm::Type *DstTy = ConvertType(DstType);
Fariborz Jahanianb19c76e2011-02-08 22:33:23 +00001021 if (SrcVal->getType() != DstTy)
1022 Src =
1023 RValue::get(EmitScalarConversion(SrcVal, E->getType(), DstType));
1024 }
1025
John McCalle68b9842010-12-04 03:11:00 +00001026 CallArgList Args;
Eli Friedman04c9a492011-05-02 17:57:46 +00001027 Args.add(Src, ArgType);
John McCalle68b9842010-12-04 03:11:00 +00001028
1029 llvm::Value *Receiver = Dst.getPropertyRefBaseAddr();
1030 QualType ResultType = getContext().VoidTy;
1031
John McCall12f78a62010-12-02 01:19:52 +00001032 if (E->isSuperReceiver()) {
John McCalle68b9842010-12-04 03:11:00 +00001033 GenerateMessageSendSuper(*this, ReturnValueSlot(),
1034 ResultType, S, Receiver, Args);
John McCall12f78a62010-12-02 01:19:52 +00001035 return;
1036 }
1037
John McCall119a1c62010-12-04 02:32:38 +00001038 const ObjCInterfaceDecl *ReceiverClass
1039 = (E->isClassReceiver() ? E->getClassReceiver() : 0);
John McCall12f78a62010-12-02 01:19:52 +00001040
John McCall12f78a62010-12-02 01:19:52 +00001041 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
John McCalle68b9842010-12-04 03:11:00 +00001042 ResultType, S, Receiver, Args,
1043 ReceiverClass);
Daniel Dunbar85c59ed2008-08-29 08:11:39 +00001044}
1045
Chris Lattner74391b42009-03-22 21:03:39 +00001046void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump1eb44332009-09-09 15:08:12 +00001047 llvm::Constant *EnumerationMutationFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001048 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +00001049
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001050 if (!EnumerationMutationFn) {
1051 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1052 return;
1053 }
1054
Devang Patelbcbd03a2011-01-19 01:36:36 +00001055 CGDebugInfo *DI = getDebugInfo();
1056 if (DI) {
1057 DI->setLocation(S.getSourceRange().getBegin());
1058 DI->EmitRegionStart(Builder);
1059 }
1060
Devang Patel9d99f2d2011-06-13 23:15:32 +00001061 // The local variable comes into scope immediately.
1062 AutoVarEmission variable = AutoVarEmission::invalid();
1063 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1064 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1065
John McCalld88687f2011-01-07 01:49:06 +00001066 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump1eb44332009-09-09 15:08:12 +00001067
Anders Carlssonf484c312008-08-31 02:33:12 +00001068 // Fast enumeration state.
Douglas Gregor0815b572011-08-09 17:23:49 +00001069 QualType StateTy = CGM.getObjCFastEnumerationStateType();
Daniel Dunbar195337d2010-02-09 02:48:28 +00001070 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlsson1884eb02010-05-22 17:35:42 +00001071 EmitNullInitialization(StatePtr, StateTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001072
Anders Carlssonf484c312008-08-31 02:33:12 +00001073 // Number of elements in the items array.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001074 static const unsigned NumItems = 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001075
John McCalld88687f2011-01-07 01:49:06 +00001076 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramerad468862010-03-30 11:36:44 +00001077 IdentifierInfo *II[] = {
1078 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1079 &CGM.getContext().Idents.get("objects"),
1080 &CGM.getContext().Idents.get("count")
1081 };
1082 Selector FastEnumSel =
1083 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlssonf484c312008-08-31 02:33:12 +00001084
1085 QualType ItemsTy =
1086 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +00001087 llvm::APInt(32, NumItems),
Anders Carlssonf484c312008-08-31 02:33:12 +00001088 ArrayType::Normal, 0);
Daniel Dunbar195337d2010-02-09 02:48:28 +00001089 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001090
John McCall990567c2011-07-27 01:07:15 +00001091 // Emit the collection pointer. In ARC, we do a retain.
1092 llvm::Value *Collection;
1093 if (getLangOptions().ObjCAutoRefCount) {
1094 Collection = EmitARCRetainScalarExpr(S.getCollection());
1095
1096 // Enter a cleanup to do the release.
1097 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1098 } else {
1099 Collection = EmitScalarExpr(S.getCollection());
1100 }
Mike Stump1eb44332009-09-09 15:08:12 +00001101
John McCall4b302d32011-08-05 00:14:38 +00001102 // The 'continue' label needs to appear within the cleanup for the
1103 // collection object.
1104 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1105
John McCalld88687f2011-01-07 01:49:06 +00001106 // Send it our message:
Anders Carlssonf484c312008-08-31 02:33:12 +00001107 CallArgList Args;
John McCalld88687f2011-01-07 01:49:06 +00001108
1109 // The first argument is a temporary of the enumeration-state type.
Eli Friedman04c9a492011-05-02 17:57:46 +00001110 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001111
John McCalld88687f2011-01-07 01:49:06 +00001112 // The second argument is a temporary array with space for NumItems
1113 // pointers. We'll actually be loading elements from the array
1114 // pointer written into the control state; this buffer is so that
1115 // collections that *aren't* backed by arrays can still queue up
1116 // batches of elements.
Eli Friedman04c9a492011-05-02 17:57:46 +00001117 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001118
John McCalld88687f2011-01-07 01:49:06 +00001119 // The third argument is the capacity of that temporary array.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001120 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001121 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman04c9a492011-05-02 17:57:46 +00001122 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001123
John McCalld88687f2011-01-07 01:49:06 +00001124 // Start the enumeration.
Mike Stump1eb44332009-09-09 15:08:12 +00001125 RValue CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001126 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001127 getContext().UnsignedLongTy,
1128 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001129 Collection, Args);
Anders Carlssonf484c312008-08-31 02:33:12 +00001130
John McCalld88687f2011-01-07 01:49:06 +00001131 // The initial number of objects that were returned in the buffer.
1132 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump1eb44332009-09-09 15:08:12 +00001133
John McCalld88687f2011-01-07 01:49:06 +00001134 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1135 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump1eb44332009-09-09 15:08:12 +00001136
John McCalld88687f2011-01-07 01:49:06 +00001137 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlssonf484c312008-08-31 02:33:12 +00001138
John McCalld88687f2011-01-07 01:49:06 +00001139 // If the limit pointer was zero to begin with, the collection is
1140 // empty; skip all this.
1141 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1142 EmptyBB, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001143
John McCalld88687f2011-01-07 01:49:06 +00001144 // Otherwise, initialize the loop.
1145 EmitBlock(LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001146
John McCalld88687f2011-01-07 01:49:06 +00001147 // Save the initial mutations value. This is the value at an
1148 // address that was written into the state object by
1149 // countByEnumeratingWithState:objects:count:.
Mike Stump1eb44332009-09-09 15:08:12 +00001150 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001151 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001152 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001153 "mutationsptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001154
John McCalld88687f2011-01-07 01:49:06 +00001155 llvm::Value *initialMutations =
1156 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump1eb44332009-09-09 15:08:12 +00001157
John McCalld88687f2011-01-07 01:49:06 +00001158 // Start looping. This is the point we return to whenever we have a
1159 // fresh, non-empty batch of objects.
1160 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1161 EmitBlock(LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001162
John McCalld88687f2011-01-07 01:49:06 +00001163 // The current index into the buffer.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001164 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCalld88687f2011-01-07 01:49:06 +00001165 index->addIncoming(zero, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001166
John McCalld88687f2011-01-07 01:49:06 +00001167 // The current buffer size.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001168 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCalld88687f2011-01-07 01:49:06 +00001169 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001170
John McCalld88687f2011-01-07 01:49:06 +00001171 // Check whether the mutations value has changed from where it was
1172 // at start. StateMutationsPtr should actually be invariant between
1173 // refreshes.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001174 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCalld88687f2011-01-07 01:49:06 +00001175 llvm::Value *currentMutations
1176 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001177
John McCalld88687f2011-01-07 01:49:06 +00001178 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman361cf982011-03-02 22:39:34 +00001179 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump1eb44332009-09-09 15:08:12 +00001180
John McCalld88687f2011-01-07 01:49:06 +00001181 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1182 WasNotMutatedBB, WasMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001183
John McCalld88687f2011-01-07 01:49:06 +00001184 // If so, call the enumeration-mutation function.
1185 EmitBlock(WasMutatedBB);
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001186 llvm::Value *V =
Mike Stump1eb44332009-09-09 15:08:12 +00001187 Builder.CreateBitCast(Collection,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001188 ConvertType(getContext().getObjCIdType()),
1189 "tmp");
Daniel Dunbar2b2105e2009-02-03 23:55:40 +00001190 CallArgList Args2;
Eli Friedman04c9a492011-05-02 17:57:46 +00001191 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stumpf5408fe2009-05-16 07:57:57 +00001192 // FIXME: We shouldn't need to get the function info here, the runtime already
1193 // should have computed it to build the function.
John McCall04a67a62010-02-05 21:31:56 +00001194 EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2,
Rafael Espindola264ba482010-03-30 20:24:48 +00001195 FunctionType::ExtInfo()),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001196 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump1eb44332009-09-09 15:08:12 +00001197
John McCalld88687f2011-01-07 01:49:06 +00001198 // Otherwise, or if the mutation function returns, just continue.
1199 EmitBlock(WasNotMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001200
John McCalld88687f2011-01-07 01:49:06 +00001201 // Initialize the element variable.
1202 RunCleanupsScope elementVariableScope(*this);
John McCall57b3b6a2011-02-22 07:16:58 +00001203 bool elementIsVariable;
John McCalld88687f2011-01-07 01:49:06 +00001204 LValue elementLValue;
1205 QualType elementType;
1206 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall57b3b6a2011-02-22 07:16:58 +00001207 // Initialize the variable, in case it's a __block variable or something.
1208 EmitAutoVarInit(variable);
John McCalld88687f2011-01-07 01:49:06 +00001209
John McCall57b3b6a2011-02-22 07:16:58 +00001210 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCalld88687f2011-01-07 01:49:06 +00001211 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), D->getType(),
1212 VK_LValue, SourceLocation());
1213 elementLValue = EmitLValue(&tempDRE);
1214 elementType = D->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001215 elementIsVariable = true;
John McCall7acddac2011-06-17 06:42:21 +00001216
1217 if (D->isARCPseudoStrong())
1218 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCalld88687f2011-01-07 01:49:06 +00001219 } else {
1220 elementLValue = LValue(); // suppress warning
1221 elementType = cast<Expr>(S.getElement())->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001222 elementIsVariable = false;
John McCalld88687f2011-01-07 01:49:06 +00001223 }
Chris Lattner2acc6e32011-07-18 04:24:23 +00001224 llvm::Type *convertedElementType = ConvertType(elementType);
John McCalld88687f2011-01-07 01:49:06 +00001225
1226 // Fetch the buffer out of the enumeration state.
1227 // TODO: this pointer should actually be invariant between
1228 // refreshes, which would help us do certain loop optimizations.
Mike Stump1eb44332009-09-09 15:08:12 +00001229 llvm::Value *StateItemsPtr =
Anders Carlssonf484c312008-08-31 02:33:12 +00001230 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCalld88687f2011-01-07 01:49:06 +00001231 llvm::Value *EnumStateItems =
1232 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlssonf484c312008-08-31 02:33:12 +00001233
John McCalld88687f2011-01-07 01:49:06 +00001234 // Fetch the value at the current index from the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001235 llvm::Value *CurrentItemPtr =
John McCalld88687f2011-01-07 01:49:06 +00001236 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1237 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001238
John McCalld88687f2011-01-07 01:49:06 +00001239 // Cast that value to the right type.
1240 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1241 "currentitem");
Mike Stump1eb44332009-09-09 15:08:12 +00001242
John McCalld88687f2011-01-07 01:49:06 +00001243 // Make sure we have an l-value. Yes, this gets evaluated every
1244 // time through the loop.
John McCall7acddac2011-06-17 06:42:21 +00001245 if (!elementIsVariable) {
John McCalld88687f2011-01-07 01:49:06 +00001246 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001247 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCall7acddac2011-06-17 06:42:21 +00001248 } else {
1249 EmitScalarInit(CurrentItem, elementLValue);
1250 }
Mike Stump1eb44332009-09-09 15:08:12 +00001251
John McCall57b3b6a2011-02-22 07:16:58 +00001252 // If we do have an element variable, this assignment is the end of
1253 // its initialization.
1254 if (elementIsVariable)
1255 EmitAutoVarCleanups(variable);
1256
John McCalld88687f2011-01-07 01:49:06 +00001257 // Perform the loop body, setting up break and continue labels.
Anders Carlssone4b6d342009-02-10 05:52:02 +00001258 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCalld88687f2011-01-07 01:49:06 +00001259 {
1260 RunCleanupsScope Scope(*this);
1261 EmitStmt(S.getBody());
1262 }
Anders Carlssonf484c312008-08-31 02:33:12 +00001263 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001264
John McCalld88687f2011-01-07 01:49:06 +00001265 // Destroy the element variable now.
1266 elementVariableScope.ForceCleanup();
1267
1268 // Check whether there are more elements.
John McCallff8e1152010-07-23 21:56:41 +00001269 EmitBlock(AfterBody.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001270
John McCalld88687f2011-01-07 01:49:06 +00001271 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanianf0906c42009-01-06 18:56:31 +00001272
John McCalld88687f2011-01-07 01:49:06 +00001273 // First we check in the local buffer.
1274 llvm::Value *indexPlusOne
1275 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlssonf484c312008-08-31 02:33:12 +00001276
John McCalld88687f2011-01-07 01:49:06 +00001277 // If we haven't overrun the buffer yet, we can continue.
1278 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1279 LoopBodyBB, FetchMoreBB);
1280
1281 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1282 count->addIncoming(count, AfterBody.getBlock());
1283
1284 // Otherwise, we have to fetch more elements.
1285 EmitBlock(FetchMoreBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001286
1287 CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001288 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001289 getContext().UnsignedLongTy,
Mike Stump1eb44332009-09-09 15:08:12 +00001290 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001291 Collection, Args);
Mike Stump1eb44332009-09-09 15:08:12 +00001292
John McCalld88687f2011-01-07 01:49:06 +00001293 // If we got a zero count, we're done.
1294 llvm::Value *refetchCount = CountRV.getScalarVal();
1295
1296 // (note that the message send might split FetchMoreBB)
1297 index->addIncoming(zero, Builder.GetInsertBlock());
1298 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1299
1300 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1301 EmptyBB, LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001302
Anders Carlssonf484c312008-08-31 02:33:12 +00001303 // No more elements.
John McCalld88687f2011-01-07 01:49:06 +00001304 EmitBlock(EmptyBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001305
John McCall57b3b6a2011-02-22 07:16:58 +00001306 if (!elementIsVariable) {
Anders Carlssonf484c312008-08-31 02:33:12 +00001307 // If the element was not a declaration, set it to be null.
1308
John McCalld88687f2011-01-07 01:49:06 +00001309 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1310 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001311 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlssonf484c312008-08-31 02:33:12 +00001312 }
1313
Devang Patelbcbd03a2011-01-19 01:36:36 +00001314 if (DI) {
1315 DI->setLocation(S.getSourceRange().getEnd());
1316 DI->EmitRegionEnd(Builder);
1317 }
1318
John McCall990567c2011-07-27 01:07:15 +00001319 // Leave the cleanup we entered in ARC.
1320 if (getLangOptions().ObjCAutoRefCount)
1321 PopCleanupBlock();
1322
John McCallff8e1152010-07-23 21:56:41 +00001323 EmitBlock(LoopEnd.getBlock());
Anders Carlsson3d8400d2008-08-30 19:51:14 +00001324}
1325
Mike Stump1eb44332009-09-09 15:08:12 +00001326void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001327 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001328}
1329
Mike Stump1eb44332009-09-09 15:08:12 +00001330void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001331 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1332}
1333
Chris Lattner10cac6f2008-11-15 21:26:17 +00001334void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump1eb44332009-09-09 15:08:12 +00001335 const ObjCAtSynchronizedStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001336 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +00001337}
1338
John McCall33e56f32011-09-10 06:18:15 +00001339/// Produce the code for a CK_ARCProduceObject. Just does a
John McCallf85e1932011-06-15 23:02:42 +00001340/// primitive retain.
1341llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1342 llvm::Value *value) {
1343 return EmitARCRetain(type, value);
1344}
1345
1346namespace {
1347 struct CallObjCRelease : EHScopeStack::Cleanup {
John McCallbddfd872011-08-03 22:24:24 +00001348 CallObjCRelease(llvm::Value *object) : object(object) {}
1349 llvm::Value *object;
John McCallf85e1932011-06-15 23:02:42 +00001350
John McCallad346f42011-07-12 20:27:29 +00001351 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001352 CGF.EmitARCRelease(object, /*precise*/ true);
John McCallf85e1932011-06-15 23:02:42 +00001353 }
1354 };
1355}
1356
John McCall33e56f32011-09-10 06:18:15 +00001357/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCallf85e1932011-06-15 23:02:42 +00001358/// release at the end of the full-expression.
1359llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1360 llvm::Value *object) {
1361 // If we're in a conditional branch, we need to make the cleanup
John McCallbddfd872011-08-03 22:24:24 +00001362 // conditional.
1363 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCallf85e1932011-06-15 23:02:42 +00001364 return object;
1365}
1366
1367llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1368 llvm::Value *value) {
1369 return EmitARCRetainAutorelease(type, value);
1370}
1371
1372
1373static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001374 llvm::FunctionType *type,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001375 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001376 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1377
1378 // In -fobjc-no-arc-runtime, emit weak references to the runtime
1379 // support library.
John McCall9f084a32011-07-06 00:26:06 +00001380 if (!CGM.getCodeGenOpts().ObjCRuntimeHasARC)
John McCallf85e1932011-06-15 23:02:42 +00001381 if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
1382 f->setLinkage(llvm::Function::ExternalWeakLinkage);
1383
1384 return fn;
1385}
1386
1387/// Perform an operation having the signature
1388/// i8* (i8*)
1389/// where a null input causes a no-op and returns null.
1390static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1391 llvm::Value *value,
1392 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001393 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001394 if (isa<llvm::ConstantPointerNull>(value)) return value;
1395
1396 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001397 std::vector<llvm::Type*> args(1, CGF.Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001398 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001399 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1400 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1401 }
1402
1403 // Cast the argument to 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001404 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001405 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1406
1407 // Call the function.
1408 llvm::CallInst *call = CGF.Builder.CreateCall(fn, value);
1409 call->setDoesNotThrow();
1410
1411 // Cast the result back to the original type.
1412 return CGF.Builder.CreateBitCast(call, origType);
1413}
1414
1415/// Perform an operation having the following signature:
1416/// i8* (i8**)
1417static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1418 llvm::Value *addr,
1419 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001420 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001421 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001422 std::vector<llvm::Type*> args(1, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001423 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001424 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1425 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1426 }
1427
1428 // Cast the argument to 'id*'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001429 llvm::Type *origType = addr->getType();
John McCallf85e1932011-06-15 23:02:42 +00001430 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1431
1432 // Call the function.
1433 llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr);
1434 call->setDoesNotThrow();
1435
1436 // Cast the result back to a dereference of the original type.
1437 llvm::Value *result = call;
1438 if (origType != CGF.Int8PtrPtrTy)
1439 result = CGF.Builder.CreateBitCast(result,
1440 cast<llvm::PointerType>(origType)->getElementType());
1441
1442 return result;
1443}
1444
1445/// Perform an operation having the following signature:
1446/// i8* (i8**, i8*)
1447static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1448 llvm::Value *addr,
1449 llvm::Value *value,
1450 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001451 StringRef fnName,
John McCallf85e1932011-06-15 23:02:42 +00001452 bool ignored) {
1453 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1454 == value->getType());
1455
1456 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001457 std::vector<llvm::Type*> argTypes(2);
John McCallf85e1932011-06-15 23:02:42 +00001458 argTypes[0] = CGF.Int8PtrPtrTy;
1459 argTypes[1] = CGF.Int8PtrTy;
1460
Chris Lattner2acc6e32011-07-18 04:24:23 +00001461 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001462 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1463 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1464 }
1465
Chris Lattner2acc6e32011-07-18 04:24:23 +00001466 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001467
1468 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1469 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1470
1471 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value);
1472 result->setDoesNotThrow();
1473
1474 if (ignored) return 0;
1475
1476 return CGF.Builder.CreateBitCast(result, origType);
1477}
1478
1479/// Perform an operation having the following signature:
1480/// void (i8**, i8**)
1481static void emitARCCopyOperation(CodeGenFunction &CGF,
1482 llvm::Value *dst,
1483 llvm::Value *src,
1484 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001485 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001486 assert(dst->getType() == src->getType());
1487
1488 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001489 std::vector<llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001490 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001491 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1492 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1493 }
1494
1495 dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy);
1496 src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy);
1497
1498 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src);
1499 result->setDoesNotThrow();
1500}
1501
1502/// Produce the code to do a retain. Based on the type, calls one of:
1503/// call i8* @objc_retain(i8* %value)
1504/// call i8* @objc_retainBlock(i8* %value)
1505llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1506 if (type->isBlockPointerType())
1507 return EmitARCRetainBlock(value);
1508 else
1509 return EmitARCRetainNonBlock(value);
1510}
1511
1512/// Retain the given object, with normal retain semantics.
1513/// call i8* @objc_retain(i8* %value)
1514llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1515 return emitARCValueOperation(*this, value,
1516 CGM.getARCEntrypoints().objc_retain,
1517 "objc_retain");
1518}
1519
1520/// Retain the given block, with _Block_copy semantics.
1521/// call i8* @objc_retainBlock(i8* %value)
1522llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value) {
1523 return emitARCValueOperation(*this, value,
1524 CGM.getARCEntrypoints().objc_retainBlock,
1525 "objc_retainBlock");
1526}
1527
1528/// Retain the given object which is the result of a function call.
1529/// call i8* @objc_retainAutoreleasedReturnValue(i8* %value)
1530///
1531/// Yes, this function name is one character away from a different
1532/// call with completely different semantics.
1533llvm::Value *
1534CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1535 // Fetch the void(void) inline asm which marks that we're going to
1536 // retain the autoreleased return value.
1537 llvm::InlineAsm *&marker
1538 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1539 if (!marker) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001540 StringRef assembly
John McCallf85e1932011-06-15 23:02:42 +00001541 = CGM.getTargetCodeGenInfo()
1542 .getARCRetainAutoreleasedReturnValueMarker();
1543
1544 // If we have an empty assembly string, there's nothing to do.
1545 if (assembly.empty()) {
1546
1547 // Otherwise, at -O0, build an inline asm that we're going to call
1548 // in a moment.
1549 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1550 llvm::FunctionType *type =
1551 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
1552 /*variadic*/ false);
1553
1554 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1555
1556 // If we're at -O1 and above, we don't want to litter the code
1557 // with this marker yet, so leave a breadcrumb for the ARC
1558 // optimizer to pick up.
1559 } else {
1560 llvm::NamedMDNode *metadata =
1561 CGM.getModule().getOrInsertNamedMetadata(
1562 "clang.arc.retainAutoreleasedReturnValueMarker");
1563 assert(metadata->getNumOperands() <= 1);
1564 if (metadata->getNumOperands() == 0) {
1565 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
Jay Foadda549e82011-07-29 13:56:53 +00001566 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
John McCallf85e1932011-06-15 23:02:42 +00001567 }
1568 }
1569 }
1570
1571 // Call the marker asm if we made one, which we do only at -O0.
1572 if (marker) Builder.CreateCall(marker);
1573
1574 return emitARCValueOperation(*this, value,
1575 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1576 "objc_retainAutoreleasedReturnValue");
1577}
1578
1579/// Release the given object.
1580/// call void @objc_release(i8* %value)
1581void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) {
1582 if (isa<llvm::ConstantPointerNull>(value)) return;
1583
1584 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1585 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001586 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001587 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001588 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1589 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1590 }
1591
1592 // Cast the argument to 'id'.
1593 value = Builder.CreateBitCast(value, Int8PtrTy);
1594
1595 // Call objc_release.
1596 llvm::CallInst *call = Builder.CreateCall(fn, value);
1597 call->setDoesNotThrow();
1598
1599 if (!precise) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001600 SmallVector<llvm::Value*,1> args;
John McCallf85e1932011-06-15 23:02:42 +00001601 call->setMetadata("clang.imprecise_release",
1602 llvm::MDNode::get(Builder.getContext(), args));
1603 }
1604}
1605
1606/// Store into a strong object. Always calls this:
1607/// call void @objc_storeStrong(i8** %addr, i8* %value)
1608llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
1609 llvm::Value *value,
1610 bool ignored) {
1611 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1612 == value->getType());
1613
1614 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
1615 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001616 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2acc6e32011-07-18 04:24:23 +00001617 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001618 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
1619 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
1620 }
1621
1622 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1623 llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy);
1624
1625 Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow();
1626
1627 if (ignored) return 0;
1628 return value;
1629}
1630
1631/// Store into a strong object. Sometimes calls this:
1632/// call void @objc_storeStrong(i8** %addr, i8* %value)
1633/// Other times, breaks it down into components.
John McCall545d9962011-06-25 02:11:03 +00001634llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCallf85e1932011-06-15 23:02:42 +00001635 llvm::Value *newValue,
1636 bool ignored) {
John McCall545d9962011-06-25 02:11:03 +00001637 QualType type = dst.getType();
John McCallf85e1932011-06-15 23:02:42 +00001638 bool isBlock = type->isBlockPointerType();
1639
1640 // Use a store barrier at -O0 unless this is a block type or the
1641 // lvalue is inadequately aligned.
1642 if (shouldUseFusedARCCalls() &&
1643 !isBlock &&
1644 !(dst.getAlignment() && dst.getAlignment() < PointerAlignInBytes)) {
1645 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
1646 }
1647
1648 // Otherwise, split it out.
1649
1650 // Retain the new value.
1651 newValue = EmitARCRetain(type, newValue);
1652
1653 // Read the old value.
John McCall545d9962011-06-25 02:11:03 +00001654 llvm::Value *oldValue = EmitLoadOfScalar(dst);
John McCallf85e1932011-06-15 23:02:42 +00001655
1656 // Store. We do this before the release so that any deallocs won't
1657 // see the old value.
John McCall545d9962011-06-25 02:11:03 +00001658 EmitStoreOfScalar(newValue, dst);
John McCallf85e1932011-06-15 23:02:42 +00001659
1660 // Finally, release the old value.
1661 EmitARCRelease(oldValue, /*precise*/ false);
1662
1663 return newValue;
1664}
1665
1666/// Autorelease the given object.
1667/// call i8* @objc_autorelease(i8* %value)
1668llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
1669 return emitARCValueOperation(*this, value,
1670 CGM.getARCEntrypoints().objc_autorelease,
1671 "objc_autorelease");
1672}
1673
1674/// Autorelease the given object.
1675/// call i8* @objc_autoreleaseReturnValue(i8* %value)
1676llvm::Value *
1677CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
1678 return emitARCValueOperation(*this, value,
1679 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
1680 "objc_autoreleaseReturnValue");
1681}
1682
1683/// Do a fused retain/autorelease of the given object.
1684/// call i8* @objc_retainAutoreleaseReturnValue(i8* %value)
1685llvm::Value *
1686CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
1687 return emitARCValueOperation(*this, value,
1688 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
1689 "objc_retainAutoreleaseReturnValue");
1690}
1691
1692/// Do a fused retain/autorelease of the given object.
1693/// call i8* @objc_retainAutorelease(i8* %value)
1694/// or
1695/// %retain = call i8* @objc_retainBlock(i8* %value)
1696/// call i8* @objc_autorelease(i8* %retain)
1697llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
1698 llvm::Value *value) {
1699 if (!type->isBlockPointerType())
1700 return EmitARCRetainAutoreleaseNonBlock(value);
1701
1702 if (isa<llvm::ConstantPointerNull>(value)) return value;
1703
Chris Lattner2acc6e32011-07-18 04:24:23 +00001704 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001705 value = Builder.CreateBitCast(value, Int8PtrTy);
1706 value = EmitARCRetainBlock(value);
1707 value = EmitARCAutorelease(value);
1708 return Builder.CreateBitCast(value, origType);
1709}
1710
1711/// Do a fused retain/autorelease of the given object.
1712/// call i8* @objc_retainAutorelease(i8* %value)
1713llvm::Value *
1714CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
1715 return emitARCValueOperation(*this, value,
1716 CGM.getARCEntrypoints().objc_retainAutorelease,
1717 "objc_retainAutorelease");
1718}
1719
1720/// i8* @objc_loadWeak(i8** %addr)
1721/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
1722llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
1723 return emitARCLoadOperation(*this, addr,
1724 CGM.getARCEntrypoints().objc_loadWeak,
1725 "objc_loadWeak");
1726}
1727
1728/// i8* @objc_loadWeakRetained(i8** %addr)
1729llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
1730 return emitARCLoadOperation(*this, addr,
1731 CGM.getARCEntrypoints().objc_loadWeakRetained,
1732 "objc_loadWeakRetained");
1733}
1734
1735/// i8* @objc_storeWeak(i8** %addr, i8* %value)
1736/// Returns %value.
1737llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
1738 llvm::Value *value,
1739 bool ignored) {
1740 return emitARCStoreOperation(*this, addr, value,
1741 CGM.getARCEntrypoints().objc_storeWeak,
1742 "objc_storeWeak", ignored);
1743}
1744
1745/// i8* @objc_initWeak(i8** %addr, i8* %value)
1746/// Returns %value. %addr is known to not have a current weak entry.
1747/// Essentially equivalent to:
1748/// *addr = nil; objc_storeWeak(addr, value);
1749void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
1750 // If we're initializing to null, just write null to memory; no need
1751 // to get the runtime involved. But don't do this if optimization
1752 // is enabled, because accounting for this would make the optimizer
1753 // much more complicated.
1754 if (isa<llvm::ConstantPointerNull>(value) &&
1755 CGM.getCodeGenOpts().OptimizationLevel == 0) {
1756 Builder.CreateStore(value, addr);
1757 return;
1758 }
1759
1760 emitARCStoreOperation(*this, addr, value,
1761 CGM.getARCEntrypoints().objc_initWeak,
1762 "objc_initWeak", /*ignored*/ true);
1763}
1764
1765/// void @objc_destroyWeak(i8** %addr)
1766/// Essentially objc_storeWeak(addr, nil).
1767void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
1768 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
1769 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001770 std::vector<llvm::Type*> args(1, Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001771 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001772 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1773 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
1774 }
1775
1776 // Cast the argument to 'id*'.
1777 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1778
1779 llvm::CallInst *call = Builder.CreateCall(fn, addr);
1780 call->setDoesNotThrow();
1781}
1782
1783/// void @objc_moveWeak(i8** %dest, i8** %src)
1784/// Disregards the current value in %dest. Leaves %src pointing to nothing.
1785/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
1786void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
1787 emitARCCopyOperation(*this, dst, src,
1788 CGM.getARCEntrypoints().objc_moveWeak,
1789 "objc_moveWeak");
1790}
1791
1792/// void @objc_copyWeak(i8** %dest, i8** %src)
1793/// Disregards the current value in %dest. Essentially
1794/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
1795void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
1796 emitARCCopyOperation(*this, dst, src,
1797 CGM.getARCEntrypoints().objc_copyWeak,
1798 "objc_copyWeak");
1799}
1800
1801/// Produce the code to do a objc_autoreleasepool_push.
1802/// call i8* @objc_autoreleasePoolPush(void)
1803llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
1804 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
1805 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001806 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001807 llvm::FunctionType::get(Int8PtrTy, false);
1808 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
1809 }
1810
1811 llvm::CallInst *call = Builder.CreateCall(fn);
1812 call->setDoesNotThrow();
1813
1814 return call;
1815}
1816
1817/// Produce the code to do a primitive release.
1818/// call void @objc_autoreleasePoolPop(i8* %ptr)
1819void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
1820 assert(value->getType() == Int8PtrTy);
1821
1822 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
1823 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001824 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001825 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001826 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1827
1828 // We don't want to use a weak import here; instead we should not
1829 // fall into this path.
1830 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
1831 }
1832
1833 llvm::CallInst *call = Builder.CreateCall(fn, value);
1834 call->setDoesNotThrow();
1835}
1836
1837/// Produce the code to do an MRR version objc_autoreleasepool_push.
1838/// Which is: [[NSAutoreleasePool alloc] init];
1839/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
1840/// init is declared as: - (id) init; in its NSObject super class.
1841///
1842llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
1843 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
1844 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder);
1845 // [NSAutoreleasePool alloc]
1846 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
1847 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
1848 CallArgList Args;
1849 RValue AllocRV =
1850 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
1851 getContext().getObjCIdType(),
1852 AllocSel, Receiver, Args);
1853
1854 // [Receiver init]
1855 Receiver = AllocRV.getScalarVal();
1856 II = &CGM.getContext().Idents.get("init");
1857 Selector InitSel = getContext().Selectors.getSelector(0, &II);
1858 RValue InitRV =
1859 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
1860 getContext().getObjCIdType(),
1861 InitSel, Receiver, Args);
1862 return InitRV.getScalarVal();
1863}
1864
1865/// Produce the code to do a primitive release.
1866/// [tmp drain];
1867void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
1868 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
1869 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
1870 CallArgList Args;
1871 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1872 getContext().VoidTy, DrainSel, Arg, Args);
1873}
1874
John McCallbdc4d802011-07-09 01:37:26 +00001875void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
1876 llvm::Value *addr,
1877 QualType type) {
1878 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
1879 CGF.EmitARCRelease(ptr, /*precise*/ true);
1880}
1881
1882void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
1883 llvm::Value *addr,
1884 QualType type) {
1885 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
1886 CGF.EmitARCRelease(ptr, /*precise*/ false);
1887}
1888
1889void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
1890 llvm::Value *addr,
1891 QualType type) {
1892 CGF.EmitARCDestroyWeak(addr);
1893}
1894
John McCallf85e1932011-06-15 23:02:42 +00001895namespace {
John McCallf85e1932011-06-15 23:02:42 +00001896 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
1897 llvm::Value *Token;
1898
1899 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
1900
John McCallad346f42011-07-12 20:27:29 +00001901 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001902 CGF.EmitObjCAutoreleasePoolPop(Token);
1903 }
1904 };
1905 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
1906 llvm::Value *Token;
1907
1908 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
1909
John McCallad346f42011-07-12 20:27:29 +00001910 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001911 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
1912 }
1913 };
1914}
1915
1916void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
1917 if (CGM.getLangOptions().ObjCAutoRefCount)
1918 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
1919 else
1920 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
1921}
1922
John McCallf85e1932011-06-15 23:02:42 +00001923static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
1924 LValue lvalue,
1925 QualType type) {
1926 switch (type.getObjCLifetime()) {
1927 case Qualifiers::OCL_None:
1928 case Qualifiers::OCL_ExplicitNone:
1929 case Qualifiers::OCL_Strong:
1930 case Qualifiers::OCL_Autoreleasing:
John McCall545d9962011-06-25 02:11:03 +00001931 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(),
John McCallf85e1932011-06-15 23:02:42 +00001932 false);
1933
1934 case Qualifiers::OCL_Weak:
1935 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
1936 true);
1937 }
1938
1939 llvm_unreachable("impossible lifetime!");
1940 return TryEmitResult();
1941}
1942
1943static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
1944 const Expr *e) {
1945 e = e->IgnoreParens();
1946 QualType type = e->getType();
1947
John McCall21480112011-08-30 00:57:29 +00001948 // If we're loading retained from a __strong xvalue, we can avoid
1949 // an extra retain/release pair by zeroing out the source of this
1950 // "move" operation.
1951 if (e->isXValue() &&
1952 !type.isConstQualified() &&
1953 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
1954 // Emit the lvalue.
1955 LValue lv = CGF.EmitLValue(e);
1956
1957 // Load the object pointer.
1958 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal();
1959
1960 // Set the source pointer to NULL.
1961 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
1962
1963 return TryEmitResult(result, true);
1964 }
1965
John McCallf85e1932011-06-15 23:02:42 +00001966 // As a very special optimization, in ARC++, if the l-value is the
1967 // result of a non-volatile assignment, do a simple retain of the
1968 // result of the call to objc_storeWeak instead of reloading.
1969 if (CGF.getLangOptions().CPlusPlus &&
1970 !type.isVolatileQualified() &&
1971 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
1972 isa<BinaryOperator>(e) &&
1973 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
1974 return TryEmitResult(CGF.EmitScalarExpr(e), false);
1975
1976 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
1977}
1978
1979static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
1980 llvm::Value *value);
1981
1982/// Given that the given expression is some sort of call (which does
1983/// not return retained), emit a retain following it.
1984static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
1985 llvm::Value *value = CGF.EmitScalarExpr(e);
1986 return emitARCRetainAfterCall(CGF, value);
1987}
1988
1989static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
1990 llvm::Value *value) {
1991 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
1992 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
1993
1994 // Place the retain immediately following the call.
1995 CGF.Builder.SetInsertPoint(call->getParent(),
1996 ++llvm::BasicBlock::iterator(call));
1997 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1998
1999 CGF.Builder.restoreIP(ip);
2000 return value;
2001 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2002 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2003
2004 // Place the retain at the beginning of the normal destination block.
2005 llvm::BasicBlock *BB = invoke->getNormalDest();
2006 CGF.Builder.SetInsertPoint(BB, BB->begin());
2007 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2008
2009 CGF.Builder.restoreIP(ip);
2010 return value;
2011
2012 // Bitcasts can arise because of related-result returns. Rewrite
2013 // the operand.
2014 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2015 llvm::Value *operand = bitcast->getOperand(0);
2016 operand = emitARCRetainAfterCall(CGF, operand);
2017 bitcast->setOperand(0, operand);
2018 return bitcast;
2019
2020 // Generic fall-back case.
2021 } else {
2022 // Retain using the non-block variant: we never need to do a copy
2023 // of a block that's been returned to us.
2024 return CGF.EmitARCRetainNonBlock(value);
2025 }
2026}
2027
John McCalldc05b112011-09-10 01:16:55 +00002028/// Determine whether it might be important to emit a separate
2029/// objc_retain_block on the result of the given expression, or
2030/// whether it's okay to just emit it in a +1 context.
2031static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2032 assert(e->getType()->isBlockPointerType());
2033 e = e->IgnoreParens();
2034
2035 // For future goodness, emit block expressions directly in +1
2036 // contexts if we can.
2037 if (isa<BlockExpr>(e))
2038 return false;
2039
2040 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2041 switch (cast->getCastKind()) {
2042 // Emitting these operations in +1 contexts is goodness.
2043 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00002044 case CK_ARCReclaimReturnedObject:
2045 case CK_ARCConsumeObject:
2046 case CK_ARCProduceObject:
John McCalldc05b112011-09-10 01:16:55 +00002047 return false;
2048
2049 // These operations preserve a block type.
2050 case CK_NoOp:
2051 case CK_BitCast:
2052 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2053
2054 // These operations are known to be bad (or haven't been considered).
2055 case CK_AnyPointerToBlockPointerCast:
2056 default:
2057 return true;
2058 }
2059 }
2060
2061 return true;
2062}
2063
John McCallf85e1932011-06-15 23:02:42 +00002064static TryEmitResult
2065tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCall990567c2011-07-27 01:07:15 +00002066 // Look through cleanups.
2067 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2068 CodeGenFunction::RunCleanupsScope scope(CGF);
2069 return tryEmitARCRetainScalarExpr(CGF, cleanups->getSubExpr());
2070 }
2071
John McCallf85e1932011-06-15 23:02:42 +00002072 // The desired result type, if it differs from the type of the
2073 // ultimate opaque expression.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002074 llvm::Type *resultType = 0;
John McCallf85e1932011-06-15 23:02:42 +00002075
2076 while (true) {
2077 e = e->IgnoreParens();
2078
2079 // There's a break at the end of this if-chain; anything
2080 // that wants to keep looping has to explicitly continue.
2081 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2082 switch (ce->getCastKind()) {
2083 // No-op casts don't change the type, so we just ignore them.
2084 case CK_NoOp:
2085 e = ce->getSubExpr();
2086 continue;
2087
2088 case CK_LValueToRValue: {
2089 TryEmitResult loadResult
2090 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2091 if (resultType) {
2092 llvm::Value *value = loadResult.getPointer();
2093 value = CGF.Builder.CreateBitCast(value, resultType);
2094 loadResult.setPointer(value);
2095 }
2096 return loadResult;
2097 }
2098
2099 // These casts can change the type, so remember that and
2100 // soldier on. We only need to remember the outermost such
2101 // cast, though.
John McCall1d9b3b22011-09-09 05:25:32 +00002102 case CK_CPointerToObjCPointerCast:
2103 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00002104 case CK_AnyPointerToBlockPointerCast:
2105 case CK_BitCast:
2106 if (!resultType)
2107 resultType = CGF.ConvertType(ce->getType());
2108 e = ce->getSubExpr();
2109 assert(e->getType()->hasPointerRepresentation());
2110 continue;
2111
2112 // For consumptions, just emit the subexpression and thus elide
2113 // the retain/release pair.
John McCall33e56f32011-09-10 06:18:15 +00002114 case CK_ARCConsumeObject: {
John McCallf85e1932011-06-15 23:02:42 +00002115 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2116 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2117 return TryEmitResult(result, true);
2118 }
2119
John McCalldc05b112011-09-10 01:16:55 +00002120 // Block extends are net +0. Naively, we could just recurse on
2121 // the subexpression, but actually we need to ensure that the
2122 // value is copied as a block, so there's a little filter here.
John McCall33e56f32011-09-10 06:18:15 +00002123 case CK_ARCExtendBlockObject: {
John McCalldc05b112011-09-10 01:16:55 +00002124 llvm::Value *result; // will be a +0 value
2125
2126 // If we can't safely assume the sub-expression will produce a
2127 // block-copied value, emit the sub-expression at +0.
2128 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2129 result = CGF.EmitScalarExpr(ce->getSubExpr());
2130
2131 // Otherwise, try to emit the sub-expression at +1 recursively.
2132 } else {
2133 TryEmitResult subresult
2134 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2135 result = subresult.getPointer();
2136
2137 // If that produced a retained value, just use that,
2138 // possibly casting down.
2139 if (subresult.getInt()) {
2140 if (resultType)
2141 result = CGF.Builder.CreateBitCast(result, resultType);
2142 return TryEmitResult(result, true);
2143 }
2144
2145 // Otherwise it's +0.
2146 }
2147
2148 // Retain the object as a block, then cast down.
2149 result = CGF.EmitARCRetainBlock(result);
2150 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2151 return TryEmitResult(result, true);
2152 }
2153
John McCall7e5e5f42011-07-07 06:58:02 +00002154 // For reclaims, emit the subexpression as a retained call and
2155 // skip the consumption.
John McCall33e56f32011-09-10 06:18:15 +00002156 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00002157 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2158 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2159 return TryEmitResult(result, true);
2160 }
2161
John McCallf85e1932011-06-15 23:02:42 +00002162 case CK_GetObjCProperty: {
2163 llvm::Value *result = emitARCRetainCall(CGF, ce);
2164 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2165 return TryEmitResult(result, true);
2166 }
2167
2168 default:
2169 break;
2170 }
2171
2172 // Skip __extension__.
2173 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2174 if (op->getOpcode() == UO_Extension) {
2175 e = op->getSubExpr();
2176 continue;
2177 }
2178
2179 // For calls and message sends, use the retained-call logic.
2180 // Delegate inits are a special case in that they're the only
2181 // returns-retained expression that *isn't* surrounded by
2182 // a consume.
2183 } else if (isa<CallExpr>(e) ||
2184 (isa<ObjCMessageExpr>(e) &&
2185 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2186 llvm::Value *result = emitARCRetainCall(CGF, e);
2187 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2188 return TryEmitResult(result, true);
2189 }
2190
2191 // Conservatively halt the search at any other expression kind.
2192 break;
2193 }
2194
2195 // We didn't find an obvious production, so emit what we've got and
2196 // tell the caller that we didn't manage to retain.
2197 llvm::Value *result = CGF.EmitScalarExpr(e);
2198 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2199 return TryEmitResult(result, false);
2200}
2201
2202static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2203 LValue lvalue,
2204 QualType type) {
2205 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2206 llvm::Value *value = result.getPointer();
2207 if (!result.getInt())
2208 value = CGF.EmitARCRetain(type, value);
2209 return value;
2210}
2211
2212/// EmitARCRetainScalarExpr - Semantically equivalent to
2213/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2214/// best-effort attempt to peephole expressions that naturally produce
2215/// retained objects.
2216llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
2217 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2218 llvm::Value *value = result.getPointer();
2219 if (!result.getInt())
2220 value = EmitARCRetain(e->getType(), value);
2221 return value;
2222}
2223
2224llvm::Value *
2225CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
2226 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2227 llvm::Value *value = result.getPointer();
2228 if (result.getInt())
2229 value = EmitARCAutorelease(value);
2230 else
2231 value = EmitARCRetainAutorelease(e->getType(), value);
2232 return value;
2233}
2234
2235std::pair<LValue,llvm::Value*>
2236CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2237 bool ignored) {
2238 // Evaluate the RHS first.
2239 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2240 llvm::Value *value = result.getPointer();
2241
John McCallfb720812011-07-28 07:23:35 +00002242 bool hasImmediateRetain = result.getInt();
2243
2244 // If we didn't emit a retained object, and the l-value is of block
2245 // type, then we need to emit the block-retain immediately in case
2246 // it invalidates the l-value.
2247 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
2248 value = EmitARCRetainBlock(value);
2249 hasImmediateRetain = true;
2250 }
2251
John McCallf85e1932011-06-15 23:02:42 +00002252 LValue lvalue = EmitLValue(e->getLHS());
2253
2254 // If the RHS was emitted retained, expand this.
John McCallfb720812011-07-28 07:23:35 +00002255 if (hasImmediateRetain) {
John McCallf85e1932011-06-15 23:02:42 +00002256 llvm::Value *oldValue =
2257 EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatileQualified(),
2258 lvalue.getAlignment(), e->getType(),
2259 lvalue.getTBAAInfo());
2260 EmitStoreOfScalar(value, lvalue.getAddress(),
2261 lvalue.isVolatileQualified(), lvalue.getAlignment(),
2262 e->getType(), lvalue.getTBAAInfo());
2263 EmitARCRelease(oldValue, /*precise*/ false);
2264 } else {
John McCall545d9962011-06-25 02:11:03 +00002265 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCallf85e1932011-06-15 23:02:42 +00002266 }
2267
2268 return std::pair<LValue,llvm::Value*>(lvalue, value);
2269}
2270
2271std::pair<LValue,llvm::Value*>
2272CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2273 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2274 LValue lvalue = EmitLValue(e->getLHS());
2275
2276 EmitStoreOfScalar(value, lvalue.getAddress(),
2277 lvalue.isVolatileQualified(), lvalue.getAlignment(),
2278 e->getType(), lvalue.getTBAAInfo());
2279
2280 return std::pair<LValue,llvm::Value*>(lvalue, value);
2281}
2282
2283void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
2284 const ObjCAutoreleasePoolStmt &ARPS) {
2285 const Stmt *subStmt = ARPS.getSubStmt();
2286 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2287
2288 CGDebugInfo *DI = getDebugInfo();
2289 if (DI) {
2290 DI->setLocation(S.getLBracLoc());
2291 DI->EmitRegionStart(Builder);
2292 }
2293
2294 // Keep track of the current cleanup stack depth.
2295 RunCleanupsScope Scope(*this);
John McCall9f084a32011-07-06 00:26:06 +00002296 if (CGM.getCodeGenOpts().ObjCRuntimeHasARC) {
John McCallf85e1932011-06-15 23:02:42 +00002297 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2298 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2299 } else {
2300 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2301 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2302 }
2303
2304 for (CompoundStmt::const_body_iterator I = S.body_begin(),
2305 E = S.body_end(); I != E; ++I)
2306 EmitStmt(*I);
2307
2308 if (DI) {
2309 DI->setLocation(S.getRBracLoc());
2310 DI->EmitRegionEnd(Builder);
2311 }
2312}
John McCall0c24c802011-06-24 23:21:27 +00002313
2314/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2315/// make sure it survives garbage collection until this point.
2316void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2317 // We just use an inline assembly.
John McCall0c24c802011-06-24 23:21:27 +00002318 llvm::FunctionType *extenderType
Jay Foadda549e82011-07-29 13:56:53 +00002319 = llvm::FunctionType::get(VoidTy, VoidPtrTy, /*variadic*/ false);
John McCall0c24c802011-06-24 23:21:27 +00002320 llvm::Value *extender
2321 = llvm::InlineAsm::get(extenderType,
2322 /* assembly */ "",
2323 /* constraints */ "r",
2324 /* side effects */ true);
2325
2326 object = Builder.CreateBitCast(object, VoidPtrTy);
2327 Builder.CreateCall(extender, object)->setDoesNotThrow();
2328}
2329
Ted Kremenek2979ec72008-04-09 15:51:31 +00002330CGObjCRuntime::~CGObjCRuntime() {}