blob: 58319cf579183b8d8eee058e54a61bbbf115ca3d [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
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +0000316 for (ObjCMethodDecl::param_const_iterator PI = OMD->param_begin(),
Chris Lattner89951a82009-02-20 18:43:26 +0000317 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
John McCall1e1f4872011-09-13 03:34:09 +0000377/// Determine whether the given architecture supports unaligned atomic
378/// accesses. They don't have to be fast, just faster than a function
379/// call and a mutex.
380static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedmande24d442011-09-13 20:48:30 +0000381 // FIXME: Allow unaligned atomic load/store on x86. (It is not
382 // currently supported by the backend.)
383 return 0;
John McCall1e1f4872011-09-13 03:34:09 +0000384}
385
386/// Return the maximum size that permits atomic accesses for the given
387/// architecture.
388static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
389 llvm::Triple::ArchType arch) {
390 // ARM has 8-byte atomic accesses, but it's not clear whether we
391 // want to rely on them here.
392
393 // In the default case, just assume that any size up to a pointer is
394 // fine given adequate alignment.
395 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
396}
397
398namespace {
399 class PropertyImplStrategy {
400 public:
401 enum StrategyKind {
402 /// The 'native' strategy is to use the architecture's provided
403 /// reads and writes.
404 Native,
405
406 /// Use objc_setProperty and objc_getProperty.
407 GetSetProperty,
408
409 /// Use objc_setProperty for the setter, but use expression
410 /// evaluation for the getter.
411 SetPropertyAndExpressionGet,
412
413 /// Use objc_copyStruct.
414 CopyStruct,
415
416 /// The 'expression' strategy is to emit normal assignment or
417 /// lvalue-to-rvalue expressions.
418 Expression
419 };
420
421 StrategyKind getKind() const { return StrategyKind(Kind); }
422
423 bool hasStrongMember() const { return HasStrong; }
424 bool isAtomic() const { return IsAtomic; }
425 bool isCopy() const { return IsCopy; }
426
427 CharUnits getIvarSize() const { return IvarSize; }
428 CharUnits getIvarAlignment() const { return IvarAlignment; }
429
430 PropertyImplStrategy(CodeGenModule &CGM,
431 const ObjCPropertyImplDecl *propImpl);
432
433 private:
434 unsigned Kind : 8;
435 unsigned IsAtomic : 1;
436 unsigned IsCopy : 1;
437 unsigned HasStrong : 1;
438
439 CharUnits IvarSize;
440 CharUnits IvarAlignment;
441 };
442}
443
444/// Pick an implementation strategy for the the given property synthesis.
445PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
446 const ObjCPropertyImplDecl *propImpl) {
447 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall265941b2011-09-13 18:31:23 +0000448 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCall1e1f4872011-09-13 03:34:09 +0000449
John McCall265941b2011-09-13 18:31:23 +0000450 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
451 IsAtomic = prop->isAtomic();
John McCall1e1f4872011-09-13 03:34:09 +0000452 HasStrong = false; // doesn't matter here.
453
454 // Evaluate the ivar's size and alignment.
455 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
456 QualType ivarType = ivar->getType();
457 llvm::tie(IvarSize, IvarAlignment)
458 = CGM.getContext().getTypeInfoInChars(ivarType);
459
460 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall265941b2011-09-13 18:31:23 +0000461 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCall1e1f4872011-09-13 03:34:09 +0000462 if (IsCopy) {
463 Kind = GetSetProperty;
464 return;
465 }
466
John McCall265941b2011-09-13 18:31:23 +0000467 // Handle retain.
468 if (setterKind == ObjCPropertyDecl::Retain) {
John McCall1e1f4872011-09-13 03:34:09 +0000469 // In GC-only, there's nothing special that needs to be done.
Douglas Gregore289d812011-09-13 17:21:33 +0000470 if (CGM.getLangOptions().getGC() == LangOptions::GCOnly) {
John McCall1e1f4872011-09-13 03:34:09 +0000471 // fallthrough
472
473 // In ARC, if the property is non-atomic, use expression emission,
474 // which translates to objc_storeStrong. This isn't required, but
475 // it's slightly nicer.
476 } else if (CGM.getLangOptions().ObjCAutoRefCount && !IsAtomic) {
477 Kind = Expression;
478 return;
479
480 // Otherwise, we need to at least use setProperty. However, if
481 // the property isn't atomic, we can use normal expression
482 // emission for the getter.
483 } else if (!IsAtomic) {
484 Kind = SetPropertyAndExpressionGet;
485 return;
486
487 // Otherwise, we have to use both setProperty and getProperty.
488 } else {
489 Kind = GetSetProperty;
490 return;
491 }
492 }
493
494 // If we're not atomic, just use expression accesses.
495 if (!IsAtomic) {
496 Kind = Expression;
497 return;
498 }
499
John McCall5889c602011-09-13 05:36:29 +0000500 // Properties on bitfield ivars need to be emitted using expression
501 // accesses even if they're nominally atomic.
502 if (ivar->isBitField()) {
503 Kind = Expression;
504 return;
505 }
506
John McCall1e1f4872011-09-13 03:34:09 +0000507 // GC-qualified or ARC-qualified ivars need to be emitted as
508 // expressions. This actually works out to being atomic anyway,
509 // except for ARC __strong, but that should trigger the above code.
510 if (ivarType.hasNonTrivialObjCLifetime() ||
Douglas Gregore289d812011-09-13 17:21:33 +0000511 (CGM.getLangOptions().getGC() &&
John McCall1e1f4872011-09-13 03:34:09 +0000512 CGM.getContext().getObjCGCAttrKind(ivarType))) {
513 Kind = Expression;
514 return;
515 }
516
517 // Compute whether the ivar has strong members.
Douglas Gregore289d812011-09-13 17:21:33 +0000518 if (CGM.getLangOptions().getGC())
John McCall1e1f4872011-09-13 03:34:09 +0000519 if (const RecordType *recordType = ivarType->getAs<RecordType>())
520 HasStrong = recordType->getDecl()->hasObjectMember();
521
522 // We can never access structs with object members with a native
523 // access, because we need to use write barriers. This is what
524 // objc_copyStruct is for.
525 if (HasStrong) {
526 Kind = CopyStruct;
527 return;
528 }
529
530 // Otherwise, this is target-dependent and based on the size and
531 // alignment of the ivar.
John McCallc5d9a902011-09-13 07:33:34 +0000532
533 // If the size of the ivar is not a power of two, give up. We don't
534 // want to get into the business of doing compare-and-swaps.
535 if (!IvarSize.isPowerOfTwo()) {
536 Kind = CopyStruct;
537 return;
538 }
539
John McCall1e1f4872011-09-13 03:34:09 +0000540 llvm::Triple::ArchType arch =
541 CGM.getContext().getTargetInfo().getTriple().getArch();
542
543 // Most architectures require memory to fit within a single cache
544 // line, so the alignment has to be at least the size of the access.
545 // Otherwise we have to grab a lock.
546 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
547 Kind = CopyStruct;
548 return;
549 }
550
551 // If the ivar's size exceeds the architecture's maximum atomic
552 // access size, we have to use CopyStruct.
553 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
554 Kind = CopyStruct;
555 return;
556 }
557
558 // Otherwise, we can use native loads and stores.
559 Kind = Native;
560}
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000561
562/// GenerateObjCGetter - Generate an Objective-C property getter
Steve Naroff489034c2009-01-10 22:55:25 +0000563/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
564/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000565void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
566 const ObjCPropertyImplDecl *PID) {
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000567 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
568 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
569 assert(OMD && "Invalid call to generate getter (empty method)");
Devang Patel8d3f8972011-05-19 23:37:41 +0000570 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +0000571
John McCall1e1f4872011-09-13 03:34:09 +0000572 generateObjCGetterBody(IMP, PID);
573
574 FinishFunction();
575}
576
John McCall6c11f0b2011-09-13 06:00:03 +0000577static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
578 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCall1e1f4872011-09-13 03:34:09 +0000579 if (!getter) return true;
580
581 // Sema only makes only of these when the ivar has a C++ class type,
582 // so the form is pretty constrained.
583
John McCall6c11f0b2011-09-13 06:00:03 +0000584 // If the property has a reference type, we might just be binding a
585 // reference, in which case the result will be a gl-value. We should
586 // treat this as a non-trivial operation.
587 if (getter->isGLValue())
588 return false;
589
John McCall1e1f4872011-09-13 03:34:09 +0000590 // If we selected a trivial copy-constructor, we're okay.
591 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
592 return (construct->getConstructor()->isTrivial());
593
594 // The constructor might require cleanups (in which case it's never
595 // trivial).
596 assert(isa<ExprWithCleanups>(getter));
597 return false;
598}
599
600void
601CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
602 const ObjCPropertyImplDecl *propImpl) {
603 // If there's a non-trivial 'get' expression, we just have to emit that.
604 if (!hasTrivialGetExpr(propImpl)) {
605 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
606 /*nrvo*/ 0);
607 EmitReturnStmt(ret);
608 return;
609 }
610
611 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
612 QualType propType = prop->getType();
613 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
614
615 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
616
617 // Pick an implementation strategy.
618 PropertyImplStrategy strategy(CGM, propImpl);
619 switch (strategy.getKind()) {
620 case PropertyImplStrategy::Native: {
621 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
622
623 // Currently, all atomic accesses have to be through integer
624 // types, so there's no point in trying to pick a prettier type.
625 llvm::Type *bitcastType =
626 llvm::Type::getIntNTy(getLLVMContext(),
627 getContext().toBits(strategy.getIvarSize()));
628 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
629
630 // Perform an atomic load. This does not impose ordering constraints.
631 llvm::Value *ivarAddr = LV.getAddress();
632 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
633 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
634 load->setAlignment(strategy.getIvarAlignment().getQuantity());
635 load->setAtomic(llvm::Unordered);
636
637 // Store that value into the return address. Doing this with a
638 // bitcast is likely to produce some pretty ugly IR, but it's not
639 // the *most* terrible thing in the world.
640 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
641
642 // Make sure we don't do an autorelease.
643 AutoreleaseResult = false;
644 return;
645 }
646
647 case PropertyImplStrategy::GetSetProperty: {
648 llvm::Value *getPropertyFn =
649 CGM.getObjCRuntime().GetPropertyGetFunction();
650 if (!getPropertyFn) {
651 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000652 return;
653 }
654
655 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
656 // FIXME: Can't this be simpler? This might even be worse than the
657 // corresponding gcc code.
John McCall1e1f4872011-09-13 03:34:09 +0000658 llvm::Value *cmd =
659 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
660 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
661 llvm::Value *ivarOffset =
662 EmitIvarOffset(classImpl->getClassInterface(), ivar);
663
664 CallArgList args;
665 args.add(RValue::get(self), getContext().getObjCIdType());
666 args.add(RValue::get(cmd), getContext().getObjCSelType());
667 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall265941b2011-09-13 18:31:23 +0000668 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
669 getContext().BoolTy);
John McCall1e1f4872011-09-13 03:34:09 +0000670
Daniel Dunbare4be5a62009-02-03 23:43:59 +0000671 // FIXME: We shouldn't need to get the function info here, the
672 // runtime already should have computed it to build the function.
John McCall1e1f4872011-09-13 03:34:09 +0000673 RValue RV = EmitCall(getTypes().getFunctionInfo(propType, args,
John McCall41bdde92011-09-12 23:06:44 +0000674 FunctionType::ExtInfo()),
John McCall1e1f4872011-09-13 03:34:09 +0000675 getPropertyFn, ReturnValueSlot(), args);
676
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000677 // We need to fix the type here. Ivars with copy & retain are
678 // always objects so we don't need to worry about complex or
679 // aggregates.
Mike Stump1eb44332009-09-09 15:08:12 +0000680 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
John McCall1e1f4872011-09-13 03:34:09 +0000681 getTypes().ConvertType(propType)));
682
683 EmitReturnOfRValue(RV, propType);
John McCallf85e1932011-06-15 23:02:42 +0000684
685 // objc_getProperty does an autorelease, so we should suppress ours.
686 AutoreleaseResult = false;
John McCallf85e1932011-06-15 23:02:42 +0000687
John McCall1e1f4872011-09-13 03:34:09 +0000688 return;
689 }
690
691 case PropertyImplStrategy::CopyStruct:
692 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
693 strategy.hasStrongMember());
694 return;
695
696 case PropertyImplStrategy::Expression:
697 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
698 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
699
700 QualType ivarType = ivar->getType();
701 if (ivarType->isAnyComplexType()) {
702 ComplexPairTy pair = LoadComplexFromAddr(LV.getAddress(),
703 LV.isVolatileQualified());
704 StoreComplexToAddr(pair, ReturnValue, LV.isVolatileQualified());
705 } else if (hasAggregateLLVMType(ivarType)) {
706 // The return value slot is guaranteed to not be aliased, but
707 // that's not necessarily the same as "on the stack", so
708 // we still potentially need objc_memmove_collectable.
709 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
710 } else {
John McCallba3dd902011-07-22 05:23:13 +0000711 llvm::Value *value;
712 if (propType->isReferenceType()) {
713 value = LV.getAddress();
714 } else {
715 // We want to load and autoreleaseReturnValue ARC __weak ivars.
716 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall1e1f4872011-09-13 03:34:09 +0000717 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
John McCallba3dd902011-07-22 05:23:13 +0000718
719 // Otherwise we want to do a simple load, suppressing the
720 // final autorelease.
John McCallf85e1932011-06-15 23:02:42 +0000721 } else {
John McCallba3dd902011-07-22 05:23:13 +0000722 value = EmitLoadOfLValue(LV).getScalarVal();
723 AutoreleaseResult = false;
Fariborz Jahanian14086762011-03-28 23:47:18 +0000724 }
John McCallf85e1932011-06-15 23:02:42 +0000725
John McCallba3dd902011-07-22 05:23:13 +0000726 value = Builder.CreateBitCast(value, ConvertType(propType));
727 }
728
729 EmitReturnOfRValue(RValue::get(value), propType);
Fariborz Jahanianed1d29d2009-03-03 18:49:40 +0000730 }
John McCall1e1f4872011-09-13 03:34:09 +0000731 return;
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000732 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000733
John McCall1e1f4872011-09-13 03:34:09 +0000734 }
735 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000736}
737
John McCall41bdde92011-09-12 23:06:44 +0000738/// emitStructSetterCall - Call the runtime function to store the value
739/// from the first formal parameter into the given ivar.
740static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
741 ObjCIvarDecl *ivar) {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000742 // objc_copyStruct (&structIvar, &Arg,
743 // sizeof (struct something), true, false);
John McCallbbb253c2011-09-10 09:30:49 +0000744 CallArgList args;
745
746 // The first argument is the address of the ivar.
John McCall41bdde92011-09-12 23:06:44 +0000747 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
748 CGF.LoadObjCSelf(), ivar, 0)
749 .getAddress();
750 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
751 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000752
753 // The second argument is the address of the parameter variable.
John McCall41bdde92011-09-12 23:06:44 +0000754 ParmVarDecl *argVar = *OMD->param_begin();
Fariborz Jahanianc3953aa2012-01-05 00:10:16 +0000755 DeclRefExpr argRef(argVar, argVar->getType().getNonReferenceType(),
756 VK_LValue, SourceLocation());
John McCall41bdde92011-09-12 23:06:44 +0000757 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
758 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
759 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000760
761 // The third argument is the sizeof the type.
762 llvm::Value *size =
John McCall41bdde92011-09-12 23:06:44 +0000763 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
764 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCallbbb253c2011-09-10 09:30:49 +0000765
John McCall41bdde92011-09-12 23:06:44 +0000766 // The fourth argument is the 'isAtomic' flag.
767 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCallbbb253c2011-09-10 09:30:49 +0000768
John McCall41bdde92011-09-12 23:06:44 +0000769 // The fifth argument is the 'hasStrong' flag.
770 // FIXME: should this really always be false?
771 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
772
773 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
774 CGF.EmitCall(CGF.getTypes().getFunctionInfo(CGF.getContext().VoidTy, args,
775 FunctionType::ExtInfo()),
776 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000777}
778
John McCall1e1f4872011-09-13 03:34:09 +0000779static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
780 Expr *setter = PID->getSetterCXXAssignment();
781 if (!setter) return true;
782
783 // Sema only makes only of these when the ivar has a C++ class type,
784 // so the form is pretty constrained.
John McCall71c758d2011-09-10 09:17:20 +0000785
786 // An operator call is trivial if the function it calls is trivial.
John McCall1e1f4872011-09-13 03:34:09 +0000787 // This also implies that there's nothing non-trivial going on with
788 // the arguments, because operator= can only be trivial if it's a
789 // synthesized assignment operator and therefore both parameters are
790 // references.
791 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall71c758d2011-09-10 09:17:20 +0000792 if (const FunctionDecl *callee
793 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
794 if (callee->isTrivial())
795 return true;
796 return false;
Fariborz Jahanian01cb3072011-04-06 16:05:26 +0000797 }
John McCall71c758d2011-09-10 09:17:20 +0000798
John McCall1e1f4872011-09-13 03:34:09 +0000799 assert(isa<ExprWithCleanups>(setter));
John McCall71c758d2011-09-10 09:17:20 +0000800 return false;
801}
802
John McCall71c758d2011-09-10 09:17:20 +0000803void
804CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
805 const ObjCPropertyImplDecl *propImpl) {
806 // Just use the setter expression if Sema gave us one and it's
807 // non-trivial. There's no way to do this atomically.
John McCall1e1f4872011-09-13 03:34:09 +0000808 if (!hasTrivialSetExpr(propImpl)) {
John McCall71c758d2011-09-10 09:17:20 +0000809 EmitStmt(propImpl->getSetterCXXAssignment());
810 return;
811 }
812
813 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
814 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
815 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
816
John McCall1e1f4872011-09-13 03:34:09 +0000817 PropertyImplStrategy strategy(CGM, propImpl);
818 switch (strategy.getKind()) {
819 case PropertyImplStrategy::Native: {
820 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
John McCall71c758d2011-09-10 09:17:20 +0000821
John McCall1e1f4872011-09-13 03:34:09 +0000822 LValue ivarLValue =
823 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
824 llvm::Value *ivarAddr = ivarLValue.getAddress();
John McCall71c758d2011-09-10 09:17:20 +0000825
John McCall1e1f4872011-09-13 03:34:09 +0000826 // Currently, all atomic accesses have to be through integer
827 // types, so there's no point in trying to pick a prettier type.
828 llvm::Type *bitcastType =
829 llvm::Type::getIntNTy(getLLVMContext(),
830 getContext().toBits(strategy.getIvarSize()));
831 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
832
833 // Cast both arguments to the chosen operation type.
834 argAddr = Builder.CreateBitCast(argAddr, bitcastType);
835 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
836
837 // This bitcast load is likely to cause some nasty IR.
838 llvm::Value *load = Builder.CreateLoad(argAddr);
839
840 // Perform an atomic store. There are no memory ordering requirements.
841 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
842 store->setAlignment(strategy.getIvarAlignment().getQuantity());
843 store->setAtomic(llvm::Unordered);
844 return;
845 }
846
847 case PropertyImplStrategy::GetSetProperty:
848 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
John McCall71c758d2011-09-10 09:17:20 +0000849 llvm::Value *setPropertyFn =
850 CGM.getObjCRuntime().GetPropertySetFunction();
851 if (!setPropertyFn) {
852 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
853 return;
854 }
855
856 // Emit objc_setProperty((id) self, _cmd, offset, arg,
857 // <is-atomic>, <is-copy>).
858 llvm::Value *cmd =
859 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
860 llvm::Value *self =
861 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
862 llvm::Value *ivarOffset =
863 EmitIvarOffset(classImpl->getClassInterface(), ivar);
864 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
865 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
866
867 CallArgList args;
868 args.add(RValue::get(self), getContext().getObjCIdType());
869 args.add(RValue::get(cmd), getContext().getObjCSelType());
870 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
871 args.add(RValue::get(arg), getContext().getObjCIdType());
John McCall1e1f4872011-09-13 03:34:09 +0000872 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
873 getContext().BoolTy);
874 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
875 getContext().BoolTy);
John McCall71c758d2011-09-10 09:17:20 +0000876 // FIXME: We shouldn't need to get the function info here, the runtime
877 // already should have computed it to build the function.
878 EmitCall(getTypes().getFunctionInfo(getContext().VoidTy, args,
879 FunctionType::ExtInfo()),
880 setPropertyFn, ReturnValueSlot(), args);
881 return;
882 }
883
John McCall1e1f4872011-09-13 03:34:09 +0000884 case PropertyImplStrategy::CopyStruct:
John McCall41bdde92011-09-12 23:06:44 +0000885 emitStructSetterCall(*this, setterMethod, ivar);
John McCall71c758d2011-09-10 09:17:20 +0000886 return;
John McCall1e1f4872011-09-13 03:34:09 +0000887
888 case PropertyImplStrategy::Expression:
889 break;
John McCall71c758d2011-09-10 09:17:20 +0000890 }
891
892 // Otherwise, fake up some ASTs and emit a normal assignment.
893 ValueDecl *selfDecl = setterMethod->getSelfDecl();
894 DeclRefExpr self(selfDecl, selfDecl->getType(), VK_LValue, SourceLocation());
895 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
896 selfDecl->getType(), CK_LValueToRValue, &self,
897 VK_RValue);
898 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
899 SourceLocation(), &selfLoad, true, true);
900
901 ParmVarDecl *argDecl = *setterMethod->param_begin();
902 QualType argType = argDecl->getType().getNonReferenceType();
903 DeclRefExpr arg(argDecl, argType, VK_LValue, SourceLocation());
904 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
905 argType.getUnqualifiedType(), CK_LValueToRValue,
906 &arg, VK_RValue);
907
908 // The property type can differ from the ivar type in some situations with
909 // Objective-C pointer types, we can always bit cast the RHS in these cases.
910 // The following absurdity is just to ensure well-formed IR.
911 CastKind argCK = CK_NoOp;
912 if (ivarRef.getType()->isObjCObjectPointerType()) {
913 if (argLoad.getType()->isObjCObjectPointerType())
914 argCK = CK_BitCast;
915 else if (argLoad.getType()->isBlockPointerType())
916 argCK = CK_BlockPointerToObjCPointerCast;
917 else
918 argCK = CK_CPointerToObjCPointerCast;
919 } else if (ivarRef.getType()->isBlockPointerType()) {
920 if (argLoad.getType()->isBlockPointerType())
921 argCK = CK_BitCast;
922 else
923 argCK = CK_AnyPointerToBlockPointerCast;
924 } else if (ivarRef.getType()->isPointerType()) {
925 argCK = CK_BitCast;
926 }
927 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
928 ivarRef.getType(), argCK, &argLoad,
929 VK_RValue);
930 Expr *finalArg = &argLoad;
931 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
932 argLoad.getType()))
933 finalArg = &argCast;
934
935
936 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
937 ivarRef.getType(), VK_RValue, OK_Ordinary,
938 SourceLocation());
939 EmitStmt(&assign);
Fariborz Jahanian01cb3072011-04-06 16:05:26 +0000940}
941
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000942/// GenerateObjCSetter - Generate an Objective-C property setter
Steve Naroff489034c2009-01-10 22:55:25 +0000943/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
944/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000945void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
946 const ObjCPropertyImplDecl *PID) {
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000947 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
948 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
949 assert(OMD && "Invalid call to generate setter (empty method)");
Devang Patel8d3f8972011-05-19 23:37:41 +0000950 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000951
John McCall71c758d2011-09-10 09:17:20 +0000952 generateObjCSetterBody(IMP, PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000953
954 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +0000955}
956
John McCalle81ac692011-03-22 07:05:39 +0000957namespace {
John McCall9928c482011-07-12 16:41:08 +0000958 struct DestroyIvar : EHScopeStack::Cleanup {
959 private:
960 llvm::Value *addr;
John McCalle81ac692011-03-22 07:05:39 +0000961 const ObjCIvarDecl *ivar;
John McCall9928c482011-07-12 16:41:08 +0000962 CodeGenFunction::Destroyer &destroyer;
963 bool useEHCleanupForArray;
964 public:
965 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
966 CodeGenFunction::Destroyer *destroyer,
967 bool useEHCleanupForArray)
968 : addr(addr), ivar(ivar), destroyer(*destroyer),
969 useEHCleanupForArray(useEHCleanupForArray) {}
John McCalle81ac692011-03-22 07:05:39 +0000970
John McCallad346f42011-07-12 20:27:29 +0000971 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +0000972 LValue lvalue
973 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
974 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +0000975 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCalle81ac692011-03-22 07:05:39 +0000976 }
977 };
978}
979
John McCall9928c482011-07-12 16:41:08 +0000980/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
981static void destroyARCStrongWithStore(CodeGenFunction &CGF,
982 llvm::Value *addr,
983 QualType type) {
984 llvm::Value *null = getNullForVariable(addr);
985 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
986}
John McCallf85e1932011-06-15 23:02:42 +0000987
John McCalle81ac692011-03-22 07:05:39 +0000988static void emitCXXDestructMethod(CodeGenFunction &CGF,
989 ObjCImplementationDecl *impl) {
990 CodeGenFunction::RunCleanupsScope scope(CGF);
991
992 llvm::Value *self = CGF.LoadObjCSelf();
993
Jordy Rosedb8264e2011-07-22 02:08:32 +0000994 const ObjCInterfaceDecl *iface = impl->getClassInterface();
995 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +0000996 ivar; ivar = ivar->getNextIvar()) {
997 QualType type = ivar->getType();
998
John McCalle81ac692011-03-22 07:05:39 +0000999 // Check whether the ivar is a destructible type.
John McCall9928c482011-07-12 16:41:08 +00001000 QualType::DestructionKind dtorKind = type.isDestructedType();
1001 if (!dtorKind) continue;
John McCalle81ac692011-03-22 07:05:39 +00001002
John McCall9928c482011-07-12 16:41:08 +00001003 CodeGenFunction::Destroyer *destroyer = 0;
John McCalle81ac692011-03-22 07:05:39 +00001004
John McCall9928c482011-07-12 16:41:08 +00001005 // Use a call to objc_storeStrong to destroy strong ivars, for the
1006 // general benefit of the tools.
1007 if (dtorKind == QualType::DK_objc_strong_lifetime) {
1008 destroyer = &destroyARCStrongWithStore;
John McCallf85e1932011-06-15 23:02:42 +00001009
John McCall9928c482011-07-12 16:41:08 +00001010 // Otherwise use the default for the destruction kind.
1011 } else {
1012 destroyer = &CGF.getDestroyer(dtorKind);
John McCalle81ac692011-03-22 07:05:39 +00001013 }
John McCall9928c482011-07-12 16:41:08 +00001014
1015 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1016
1017 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1018 cleanupKind & EHCleanup);
John McCalle81ac692011-03-22 07:05:39 +00001019 }
1020
1021 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1022}
1023
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001024void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1025 ObjCMethodDecl *MD,
1026 bool ctor) {
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001027 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Devang Patel8d3f8972011-05-19 23:37:41 +00001028 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
John McCalle81ac692011-03-22 07:05:39 +00001029
1030 // Emit .cxx_construct.
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001031 if (ctor) {
John McCallf85e1932011-06-15 23:02:42 +00001032 // Suppress the final autorelease in ARC.
1033 AutoreleaseResult = false;
1034
Chris Lattner5f9e2722011-07-23 10:55:15 +00001035 SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
John McCalle81ac692011-03-22 07:05:39 +00001036 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
1037 E = IMP->init_end(); B != E; ++B) {
1038 CXXCtorInitializer *IvarInit = (*B);
Francois Pichet00eb3f92010-12-04 09:14:42 +00001039 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001040 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian9b4d4fc2010-04-28 22:30:33 +00001041 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1042 LoadObjCSelf(), Ivar, 0);
John McCall7c2349b2011-08-25 20:40:09 +00001043 EmitAggExpr(IvarInit->getInit(),
1044 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001045 AggValueSlot::DoesNotNeedGCBarriers,
1046 AggValueSlot::IsNotAliased));
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001047 }
1048 // constructor returns 'self'.
1049 CodeGenTypes &Types = CGM.getTypes();
1050 QualType IdTy(CGM.getContext().getObjCIdType());
1051 llvm::Value *SelfAsId =
1052 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1053 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCalle81ac692011-03-22 07:05:39 +00001054
1055 // Emit .cxx_destruct.
Chandler Carruthbc397cf2010-05-06 00:20:39 +00001056 } else {
John McCalle81ac692011-03-22 07:05:39 +00001057 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001058 }
1059 FinishFunction();
1060}
1061
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +00001062bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1063 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1064 it++; it++;
1065 const ABIArgInfo &AI = it->info;
1066 // FIXME. Is this sufficient check?
1067 return (AI.getKind() == ABIArgInfo::Indirect);
1068}
1069
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001070bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
Douglas Gregore289d812011-09-13 17:21:33 +00001071 if (CGM.getLangOptions().getGC() == LangOptions::NonGC)
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001072 return false;
1073 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1074 return FDTTy->getDecl()->hasObjectMember();
1075 return false;
1076}
1077
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001078llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001079 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1080 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner41110242008-06-17 18:05:57 +00001081}
1082
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001083QualType CodeGenFunction::TypeOfSelfObject() {
1084 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1085 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff14108da2009-07-10 23:34:53 +00001086 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1087 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001088 return PTy->getPointeeType();
1089}
1090
Chris Lattner74391b42009-03-22 21:03:39 +00001091void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump1eb44332009-09-09 15:08:12 +00001092 llvm::Constant *EnumerationMutationFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001093 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +00001094
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001095 if (!EnumerationMutationFn) {
1096 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1097 return;
1098 }
1099
Devang Patelbcbd03a2011-01-19 01:36:36 +00001100 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00001101 if (DI)
1102 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001103
Devang Patel9d99f2d2011-06-13 23:15:32 +00001104 // The local variable comes into scope immediately.
1105 AutoVarEmission variable = AutoVarEmission::invalid();
1106 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1107 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1108
John McCalld88687f2011-01-07 01:49:06 +00001109 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump1eb44332009-09-09 15:08:12 +00001110
Anders Carlssonf484c312008-08-31 02:33:12 +00001111 // Fast enumeration state.
Douglas Gregor0815b572011-08-09 17:23:49 +00001112 QualType StateTy = CGM.getObjCFastEnumerationStateType();
Daniel Dunbar195337d2010-02-09 02:48:28 +00001113 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlsson1884eb02010-05-22 17:35:42 +00001114 EmitNullInitialization(StatePtr, StateTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Anders Carlssonf484c312008-08-31 02:33:12 +00001116 // Number of elements in the items array.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001117 static const unsigned NumItems = 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001118
John McCalld88687f2011-01-07 01:49:06 +00001119 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramerad468862010-03-30 11:36:44 +00001120 IdentifierInfo *II[] = {
1121 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1122 &CGM.getContext().Idents.get("objects"),
1123 &CGM.getContext().Idents.get("count")
1124 };
1125 Selector FastEnumSel =
1126 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlssonf484c312008-08-31 02:33:12 +00001127
1128 QualType ItemsTy =
1129 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +00001130 llvm::APInt(32, NumItems),
Anders Carlssonf484c312008-08-31 02:33:12 +00001131 ArrayType::Normal, 0);
Daniel Dunbar195337d2010-02-09 02:48:28 +00001132 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001133
John McCall990567c2011-07-27 01:07:15 +00001134 // Emit the collection pointer. In ARC, we do a retain.
1135 llvm::Value *Collection;
1136 if (getLangOptions().ObjCAutoRefCount) {
1137 Collection = EmitARCRetainScalarExpr(S.getCollection());
1138
1139 // Enter a cleanup to do the release.
1140 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1141 } else {
1142 Collection = EmitScalarExpr(S.getCollection());
1143 }
Mike Stump1eb44332009-09-09 15:08:12 +00001144
John McCall4b302d32011-08-05 00:14:38 +00001145 // The 'continue' label needs to appear within the cleanup for the
1146 // collection object.
1147 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1148
John McCalld88687f2011-01-07 01:49:06 +00001149 // Send it our message:
Anders Carlssonf484c312008-08-31 02:33:12 +00001150 CallArgList Args;
John McCalld88687f2011-01-07 01:49:06 +00001151
1152 // The first argument is a temporary of the enumeration-state type.
Eli Friedman04c9a492011-05-02 17:57:46 +00001153 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001154
John McCalld88687f2011-01-07 01:49:06 +00001155 // The second argument is a temporary array with space for NumItems
1156 // pointers. We'll actually be loading elements from the array
1157 // pointer written into the control state; this buffer is so that
1158 // collections that *aren't* backed by arrays can still queue up
1159 // batches of elements.
Eli Friedman04c9a492011-05-02 17:57:46 +00001160 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001161
John McCalld88687f2011-01-07 01:49:06 +00001162 // The third argument is the capacity of that temporary array.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001163 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001164 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman04c9a492011-05-02 17:57:46 +00001165 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001166
John McCalld88687f2011-01-07 01:49:06 +00001167 // Start the enumeration.
Mike Stump1eb44332009-09-09 15:08:12 +00001168 RValue CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001169 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001170 getContext().UnsignedLongTy,
1171 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001172 Collection, Args);
Anders Carlssonf484c312008-08-31 02:33:12 +00001173
John McCalld88687f2011-01-07 01:49:06 +00001174 // The initial number of objects that were returned in the buffer.
1175 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump1eb44332009-09-09 15:08:12 +00001176
John McCalld88687f2011-01-07 01:49:06 +00001177 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1178 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump1eb44332009-09-09 15:08:12 +00001179
John McCalld88687f2011-01-07 01:49:06 +00001180 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlssonf484c312008-08-31 02:33:12 +00001181
John McCalld88687f2011-01-07 01:49:06 +00001182 // If the limit pointer was zero to begin with, the collection is
1183 // empty; skip all this.
1184 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1185 EmptyBB, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001186
John McCalld88687f2011-01-07 01:49:06 +00001187 // Otherwise, initialize the loop.
1188 EmitBlock(LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001189
John McCalld88687f2011-01-07 01:49:06 +00001190 // Save the initial mutations value. This is the value at an
1191 // address that was written into the state object by
1192 // countByEnumeratingWithState:objects:count:.
Mike Stump1eb44332009-09-09 15:08:12 +00001193 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001194 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001195 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001196 "mutationsptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001197
John McCalld88687f2011-01-07 01:49:06 +00001198 llvm::Value *initialMutations =
1199 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump1eb44332009-09-09 15:08:12 +00001200
John McCalld88687f2011-01-07 01:49:06 +00001201 // Start looping. This is the point we return to whenever we have a
1202 // fresh, non-empty batch of objects.
1203 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1204 EmitBlock(LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001205
John McCalld88687f2011-01-07 01:49:06 +00001206 // The current index into the buffer.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001207 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCalld88687f2011-01-07 01:49:06 +00001208 index->addIncoming(zero, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001209
John McCalld88687f2011-01-07 01:49:06 +00001210 // The current buffer size.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001211 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCalld88687f2011-01-07 01:49:06 +00001212 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001213
John McCalld88687f2011-01-07 01:49:06 +00001214 // Check whether the mutations value has changed from where it was
1215 // at start. StateMutationsPtr should actually be invariant between
1216 // refreshes.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001217 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCalld88687f2011-01-07 01:49:06 +00001218 llvm::Value *currentMutations
1219 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001220
John McCalld88687f2011-01-07 01:49:06 +00001221 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman361cf982011-03-02 22:39:34 +00001222 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump1eb44332009-09-09 15:08:12 +00001223
John McCalld88687f2011-01-07 01:49:06 +00001224 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1225 WasNotMutatedBB, WasMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001226
John McCalld88687f2011-01-07 01:49:06 +00001227 // If so, call the enumeration-mutation function.
1228 EmitBlock(WasMutatedBB);
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001229 llvm::Value *V =
Mike Stump1eb44332009-09-09 15:08:12 +00001230 Builder.CreateBitCast(Collection,
Benjamin Kramer578faa82011-09-27 21:06:10 +00001231 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar2b2105e2009-02-03 23:55:40 +00001232 CallArgList Args2;
Eli Friedman04c9a492011-05-02 17:57:46 +00001233 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stumpf5408fe2009-05-16 07:57:57 +00001234 // FIXME: We shouldn't need to get the function info here, the runtime already
1235 // should have computed it to build the function.
John McCall04a67a62010-02-05 21:31:56 +00001236 EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2,
Rafael Espindola264ba482010-03-30 20:24:48 +00001237 FunctionType::ExtInfo()),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001238 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump1eb44332009-09-09 15:08:12 +00001239
John McCalld88687f2011-01-07 01:49:06 +00001240 // Otherwise, or if the mutation function returns, just continue.
1241 EmitBlock(WasNotMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001242
John McCalld88687f2011-01-07 01:49:06 +00001243 // Initialize the element variable.
1244 RunCleanupsScope elementVariableScope(*this);
John McCall57b3b6a2011-02-22 07:16:58 +00001245 bool elementIsVariable;
John McCalld88687f2011-01-07 01:49:06 +00001246 LValue elementLValue;
1247 QualType elementType;
1248 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall57b3b6a2011-02-22 07:16:58 +00001249 // Initialize the variable, in case it's a __block variable or something.
1250 EmitAutoVarInit(variable);
John McCalld88687f2011-01-07 01:49:06 +00001251
John McCall57b3b6a2011-02-22 07:16:58 +00001252 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCalld88687f2011-01-07 01:49:06 +00001253 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), D->getType(),
1254 VK_LValue, SourceLocation());
1255 elementLValue = EmitLValue(&tempDRE);
1256 elementType = D->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001257 elementIsVariable = true;
John McCall7acddac2011-06-17 06:42:21 +00001258
1259 if (D->isARCPseudoStrong())
1260 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCalld88687f2011-01-07 01:49:06 +00001261 } else {
1262 elementLValue = LValue(); // suppress warning
1263 elementType = cast<Expr>(S.getElement())->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001264 elementIsVariable = false;
John McCalld88687f2011-01-07 01:49:06 +00001265 }
Chris Lattner2acc6e32011-07-18 04:24:23 +00001266 llvm::Type *convertedElementType = ConvertType(elementType);
John McCalld88687f2011-01-07 01:49:06 +00001267
1268 // Fetch the buffer out of the enumeration state.
1269 // TODO: this pointer should actually be invariant between
1270 // refreshes, which would help us do certain loop optimizations.
Mike Stump1eb44332009-09-09 15:08:12 +00001271 llvm::Value *StateItemsPtr =
Anders Carlssonf484c312008-08-31 02:33:12 +00001272 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCalld88687f2011-01-07 01:49:06 +00001273 llvm::Value *EnumStateItems =
1274 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlssonf484c312008-08-31 02:33:12 +00001275
John McCalld88687f2011-01-07 01:49:06 +00001276 // Fetch the value at the current index from the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001277 llvm::Value *CurrentItemPtr =
John McCalld88687f2011-01-07 01:49:06 +00001278 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1279 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001280
John McCalld88687f2011-01-07 01:49:06 +00001281 // Cast that value to the right type.
1282 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1283 "currentitem");
Mike Stump1eb44332009-09-09 15:08:12 +00001284
John McCalld88687f2011-01-07 01:49:06 +00001285 // Make sure we have an l-value. Yes, this gets evaluated every
1286 // time through the loop.
John McCall7acddac2011-06-17 06:42:21 +00001287 if (!elementIsVariable) {
John McCalld88687f2011-01-07 01:49:06 +00001288 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001289 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCall7acddac2011-06-17 06:42:21 +00001290 } else {
1291 EmitScalarInit(CurrentItem, elementLValue);
1292 }
Mike Stump1eb44332009-09-09 15:08:12 +00001293
John McCall57b3b6a2011-02-22 07:16:58 +00001294 // If we do have an element variable, this assignment is the end of
1295 // its initialization.
1296 if (elementIsVariable)
1297 EmitAutoVarCleanups(variable);
1298
John McCalld88687f2011-01-07 01:49:06 +00001299 // Perform the loop body, setting up break and continue labels.
Anders Carlssone4b6d342009-02-10 05:52:02 +00001300 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCalld88687f2011-01-07 01:49:06 +00001301 {
1302 RunCleanupsScope Scope(*this);
1303 EmitStmt(S.getBody());
1304 }
Anders Carlssonf484c312008-08-31 02:33:12 +00001305 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001306
John McCalld88687f2011-01-07 01:49:06 +00001307 // Destroy the element variable now.
1308 elementVariableScope.ForceCleanup();
1309
1310 // Check whether there are more elements.
John McCallff8e1152010-07-23 21:56:41 +00001311 EmitBlock(AfterBody.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001312
John McCalld88687f2011-01-07 01:49:06 +00001313 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanianf0906c42009-01-06 18:56:31 +00001314
John McCalld88687f2011-01-07 01:49:06 +00001315 // First we check in the local buffer.
1316 llvm::Value *indexPlusOne
1317 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlssonf484c312008-08-31 02:33:12 +00001318
John McCalld88687f2011-01-07 01:49:06 +00001319 // If we haven't overrun the buffer yet, we can continue.
1320 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1321 LoopBodyBB, FetchMoreBB);
1322
1323 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1324 count->addIncoming(count, AfterBody.getBlock());
1325
1326 // Otherwise, we have to fetch more elements.
1327 EmitBlock(FetchMoreBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001328
1329 CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001330 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001331 getContext().UnsignedLongTy,
Mike Stump1eb44332009-09-09 15:08:12 +00001332 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001333 Collection, Args);
Mike Stump1eb44332009-09-09 15:08:12 +00001334
John McCalld88687f2011-01-07 01:49:06 +00001335 // If we got a zero count, we're done.
1336 llvm::Value *refetchCount = CountRV.getScalarVal();
1337
1338 // (note that the message send might split FetchMoreBB)
1339 index->addIncoming(zero, Builder.GetInsertBlock());
1340 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1341
1342 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1343 EmptyBB, LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001344
Anders Carlssonf484c312008-08-31 02:33:12 +00001345 // No more elements.
John McCalld88687f2011-01-07 01:49:06 +00001346 EmitBlock(EmptyBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001347
John McCall57b3b6a2011-02-22 07:16:58 +00001348 if (!elementIsVariable) {
Anders Carlssonf484c312008-08-31 02:33:12 +00001349 // If the element was not a declaration, set it to be null.
1350
John McCalld88687f2011-01-07 01:49:06 +00001351 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1352 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001353 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlssonf484c312008-08-31 02:33:12 +00001354 }
1355
Eric Christopher73fb3502011-10-13 21:45:18 +00001356 if (DI)
1357 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001358
John McCall990567c2011-07-27 01:07:15 +00001359 // Leave the cleanup we entered in ARC.
1360 if (getLangOptions().ObjCAutoRefCount)
1361 PopCleanupBlock();
1362
John McCallff8e1152010-07-23 21:56:41 +00001363 EmitBlock(LoopEnd.getBlock());
Anders Carlsson3d8400d2008-08-30 19:51:14 +00001364}
1365
Mike Stump1eb44332009-09-09 15:08:12 +00001366void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001367 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001368}
1369
Mike Stump1eb44332009-09-09 15:08:12 +00001370void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001371 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1372}
1373
Chris Lattner10cac6f2008-11-15 21:26:17 +00001374void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump1eb44332009-09-09 15:08:12 +00001375 const ObjCAtSynchronizedStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001376 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +00001377}
1378
John McCall33e56f32011-09-10 06:18:15 +00001379/// Produce the code for a CK_ARCProduceObject. Just does a
John McCallf85e1932011-06-15 23:02:42 +00001380/// primitive retain.
1381llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1382 llvm::Value *value) {
1383 return EmitARCRetain(type, value);
1384}
1385
1386namespace {
1387 struct CallObjCRelease : EHScopeStack::Cleanup {
John McCallbddfd872011-08-03 22:24:24 +00001388 CallObjCRelease(llvm::Value *object) : object(object) {}
1389 llvm::Value *object;
John McCallf85e1932011-06-15 23:02:42 +00001390
John McCallad346f42011-07-12 20:27:29 +00001391 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001392 CGF.EmitARCRelease(object, /*precise*/ true);
John McCallf85e1932011-06-15 23:02:42 +00001393 }
1394 };
1395}
1396
John McCall33e56f32011-09-10 06:18:15 +00001397/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCallf85e1932011-06-15 23:02:42 +00001398/// release at the end of the full-expression.
1399llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1400 llvm::Value *object) {
1401 // If we're in a conditional branch, we need to make the cleanup
John McCallbddfd872011-08-03 22:24:24 +00001402 // conditional.
1403 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCallf85e1932011-06-15 23:02:42 +00001404 return object;
1405}
1406
1407llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1408 llvm::Value *value) {
1409 return EmitARCRetainAutorelease(type, value);
1410}
1411
1412
1413static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001414 llvm::FunctionType *type,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001415 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001416 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1417
1418 // In -fobjc-no-arc-runtime, emit weak references to the runtime
1419 // support library.
John McCall9f084a32011-07-06 00:26:06 +00001420 if (!CGM.getCodeGenOpts().ObjCRuntimeHasARC)
John McCallf85e1932011-06-15 23:02:42 +00001421 if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
1422 f->setLinkage(llvm::Function::ExternalWeakLinkage);
1423
1424 return fn;
1425}
1426
1427/// Perform an operation having the signature
1428/// i8* (i8*)
1429/// where a null input causes a no-op and returns null.
1430static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1431 llvm::Value *value,
1432 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001433 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001434 if (isa<llvm::ConstantPointerNull>(value)) return value;
1435
1436 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001437 std::vector<llvm::Type*> args(1, CGF.Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001438 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001439 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1440 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1441 }
1442
1443 // Cast the argument to 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001444 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001445 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1446
1447 // Call the function.
1448 llvm::CallInst *call = CGF.Builder.CreateCall(fn, value);
1449 call->setDoesNotThrow();
1450
1451 // Cast the result back to the original type.
1452 return CGF.Builder.CreateBitCast(call, origType);
1453}
1454
1455/// Perform an operation having the following signature:
1456/// i8* (i8**)
1457static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1458 llvm::Value *addr,
1459 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001460 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001461 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001462 std::vector<llvm::Type*> args(1, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001463 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001464 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1465 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1466 }
1467
1468 // Cast the argument to 'id*'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001469 llvm::Type *origType = addr->getType();
John McCallf85e1932011-06-15 23:02:42 +00001470 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1471
1472 // Call the function.
1473 llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr);
1474 call->setDoesNotThrow();
1475
1476 // Cast the result back to a dereference of the original type.
1477 llvm::Value *result = call;
1478 if (origType != CGF.Int8PtrPtrTy)
1479 result = CGF.Builder.CreateBitCast(result,
1480 cast<llvm::PointerType>(origType)->getElementType());
1481
1482 return result;
1483}
1484
1485/// Perform an operation having the following signature:
1486/// i8* (i8**, i8*)
1487static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1488 llvm::Value *addr,
1489 llvm::Value *value,
1490 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001491 StringRef fnName,
John McCallf85e1932011-06-15 23:02:42 +00001492 bool ignored) {
1493 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1494 == value->getType());
1495
1496 if (!fn) {
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00001497 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
John McCallf85e1932011-06-15 23:02:42 +00001498
Chris Lattner2acc6e32011-07-18 04:24:23 +00001499 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001500 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1501 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1502 }
1503
Chris Lattner2acc6e32011-07-18 04:24:23 +00001504 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001505
1506 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1507 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1508
1509 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value);
1510 result->setDoesNotThrow();
1511
1512 if (ignored) return 0;
1513
1514 return CGF.Builder.CreateBitCast(result, origType);
1515}
1516
1517/// Perform an operation having the following signature:
1518/// void (i8**, i8**)
1519static void emitARCCopyOperation(CodeGenFunction &CGF,
1520 llvm::Value *dst,
1521 llvm::Value *src,
1522 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001523 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001524 assert(dst->getType() == src->getType());
1525
1526 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001527 std::vector<llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001528 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001529 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1530 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1531 }
1532
1533 dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy);
1534 src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy);
1535
1536 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src);
1537 result->setDoesNotThrow();
1538}
1539
1540/// Produce the code to do a retain. Based on the type, calls one of:
1541/// call i8* @objc_retain(i8* %value)
1542/// call i8* @objc_retainBlock(i8* %value)
1543llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1544 if (type->isBlockPointerType())
John McCall348f16f2011-10-04 06:23:45 +00001545 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallf85e1932011-06-15 23:02:42 +00001546 else
1547 return EmitARCRetainNonBlock(value);
1548}
1549
1550/// Retain the given object, with normal retain semantics.
1551/// call i8* @objc_retain(i8* %value)
1552llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1553 return emitARCValueOperation(*this, value,
1554 CGM.getARCEntrypoints().objc_retain,
1555 "objc_retain");
1556}
1557
1558/// Retain the given block, with _Block_copy semantics.
1559/// call i8* @objc_retainBlock(i8* %value)
John McCall348f16f2011-10-04 06:23:45 +00001560///
1561/// \param mandatory - If false, emit the call with metadata
1562/// indicating that it's okay for the optimizer to eliminate this call
1563/// if it can prove that the block never escapes except down the stack.
1564llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1565 bool mandatory) {
1566 llvm::Value *result
1567 = emitARCValueOperation(*this, value,
1568 CGM.getARCEntrypoints().objc_retainBlock,
1569 "objc_retainBlock");
1570
1571 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1572 // tell the optimizer that it doesn't need to do this copy if the
1573 // block doesn't escape, where being passed as an argument doesn't
1574 // count as escaping.
1575 if (!mandatory && isa<llvm::Instruction>(result)) {
1576 llvm::CallInst *call
1577 = cast<llvm::CallInst>(result->stripPointerCasts());
1578 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
1579
1580 SmallVector<llvm::Value*,1> args;
1581 call->setMetadata("clang.arc.copy_on_escape",
1582 llvm::MDNode::get(Builder.getContext(), args));
1583 }
1584
1585 return result;
John McCallf85e1932011-06-15 23:02:42 +00001586}
1587
1588/// Retain the given object which is the result of a function call.
1589/// call i8* @objc_retainAutoreleasedReturnValue(i8* %value)
1590///
1591/// Yes, this function name is one character away from a different
1592/// call with completely different semantics.
1593llvm::Value *
1594CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1595 // Fetch the void(void) inline asm which marks that we're going to
1596 // retain the autoreleased return value.
1597 llvm::InlineAsm *&marker
1598 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1599 if (!marker) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001600 StringRef assembly
John McCallf85e1932011-06-15 23:02:42 +00001601 = CGM.getTargetCodeGenInfo()
1602 .getARCRetainAutoreleasedReturnValueMarker();
1603
1604 // If we have an empty assembly string, there's nothing to do.
1605 if (assembly.empty()) {
1606
1607 // Otherwise, at -O0, build an inline asm that we're going to call
1608 // in a moment.
1609 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1610 llvm::FunctionType *type =
1611 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
1612 /*variadic*/ false);
1613
1614 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1615
1616 // If we're at -O1 and above, we don't want to litter the code
1617 // with this marker yet, so leave a breadcrumb for the ARC
1618 // optimizer to pick up.
1619 } else {
1620 llvm::NamedMDNode *metadata =
1621 CGM.getModule().getOrInsertNamedMetadata(
1622 "clang.arc.retainAutoreleasedReturnValueMarker");
1623 assert(metadata->getNumOperands() <= 1);
1624 if (metadata->getNumOperands() == 0) {
1625 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
Jay Foadda549e82011-07-29 13:56:53 +00001626 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
John McCallf85e1932011-06-15 23:02:42 +00001627 }
1628 }
1629 }
1630
1631 // Call the marker asm if we made one, which we do only at -O0.
1632 if (marker) Builder.CreateCall(marker);
1633
1634 return emitARCValueOperation(*this, value,
1635 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1636 "objc_retainAutoreleasedReturnValue");
1637}
1638
1639/// Release the given object.
1640/// call void @objc_release(i8* %value)
1641void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) {
1642 if (isa<llvm::ConstantPointerNull>(value)) return;
1643
1644 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1645 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001646 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001647 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001648 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1649 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1650 }
1651
1652 // Cast the argument to 'id'.
1653 value = Builder.CreateBitCast(value, Int8PtrTy);
1654
1655 // Call objc_release.
1656 llvm::CallInst *call = Builder.CreateCall(fn, value);
1657 call->setDoesNotThrow();
1658
1659 if (!precise) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001660 SmallVector<llvm::Value*,1> args;
John McCallf85e1932011-06-15 23:02:42 +00001661 call->setMetadata("clang.imprecise_release",
1662 llvm::MDNode::get(Builder.getContext(), args));
1663 }
1664}
1665
1666/// Store into a strong object. Always calls this:
1667/// call void @objc_storeStrong(i8** %addr, i8* %value)
1668llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
1669 llvm::Value *value,
1670 bool ignored) {
1671 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1672 == value->getType());
1673
1674 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
1675 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001676 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2acc6e32011-07-18 04:24:23 +00001677 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001678 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
1679 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
1680 }
1681
1682 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1683 llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy);
1684
1685 Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow();
1686
1687 if (ignored) return 0;
1688 return value;
1689}
1690
1691/// Store into a strong object. Sometimes calls this:
1692/// call void @objc_storeStrong(i8** %addr, i8* %value)
1693/// Other times, breaks it down into components.
John McCall545d9962011-06-25 02:11:03 +00001694llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCallf85e1932011-06-15 23:02:42 +00001695 llvm::Value *newValue,
1696 bool ignored) {
John McCall545d9962011-06-25 02:11:03 +00001697 QualType type = dst.getType();
John McCallf85e1932011-06-15 23:02:42 +00001698 bool isBlock = type->isBlockPointerType();
1699
1700 // Use a store barrier at -O0 unless this is a block type or the
1701 // lvalue is inadequately aligned.
1702 if (shouldUseFusedARCCalls() &&
1703 !isBlock &&
Eli Friedman6da2c712011-12-03 04:14:32 +00001704 (dst.getAlignment().isZero() ||
1705 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCallf85e1932011-06-15 23:02:42 +00001706 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
1707 }
1708
1709 // Otherwise, split it out.
1710
1711 // Retain the new value.
1712 newValue = EmitARCRetain(type, newValue);
1713
1714 // Read the old value.
John McCall545d9962011-06-25 02:11:03 +00001715 llvm::Value *oldValue = EmitLoadOfScalar(dst);
John McCallf85e1932011-06-15 23:02:42 +00001716
1717 // Store. We do this before the release so that any deallocs won't
1718 // see the old value.
John McCall545d9962011-06-25 02:11:03 +00001719 EmitStoreOfScalar(newValue, dst);
John McCallf85e1932011-06-15 23:02:42 +00001720
1721 // Finally, release the old value.
1722 EmitARCRelease(oldValue, /*precise*/ false);
1723
1724 return newValue;
1725}
1726
1727/// Autorelease the given object.
1728/// call i8* @objc_autorelease(i8* %value)
1729llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
1730 return emitARCValueOperation(*this, value,
1731 CGM.getARCEntrypoints().objc_autorelease,
1732 "objc_autorelease");
1733}
1734
1735/// Autorelease the given object.
1736/// call i8* @objc_autoreleaseReturnValue(i8* %value)
1737llvm::Value *
1738CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
1739 return emitARCValueOperation(*this, value,
1740 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
1741 "objc_autoreleaseReturnValue");
1742}
1743
1744/// Do a fused retain/autorelease of the given object.
1745/// call i8* @objc_retainAutoreleaseReturnValue(i8* %value)
1746llvm::Value *
1747CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
1748 return emitARCValueOperation(*this, value,
1749 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
1750 "objc_retainAutoreleaseReturnValue");
1751}
1752
1753/// Do a fused retain/autorelease of the given object.
1754/// call i8* @objc_retainAutorelease(i8* %value)
1755/// or
1756/// %retain = call i8* @objc_retainBlock(i8* %value)
1757/// call i8* @objc_autorelease(i8* %retain)
1758llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
1759 llvm::Value *value) {
1760 if (!type->isBlockPointerType())
1761 return EmitARCRetainAutoreleaseNonBlock(value);
1762
1763 if (isa<llvm::ConstantPointerNull>(value)) return value;
1764
Chris Lattner2acc6e32011-07-18 04:24:23 +00001765 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001766 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCall348f16f2011-10-04 06:23:45 +00001767 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCallf85e1932011-06-15 23:02:42 +00001768 value = EmitARCAutorelease(value);
1769 return Builder.CreateBitCast(value, origType);
1770}
1771
1772/// Do a fused retain/autorelease of the given object.
1773/// call i8* @objc_retainAutorelease(i8* %value)
1774llvm::Value *
1775CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
1776 return emitARCValueOperation(*this, value,
1777 CGM.getARCEntrypoints().objc_retainAutorelease,
1778 "objc_retainAutorelease");
1779}
1780
1781/// i8* @objc_loadWeak(i8** %addr)
1782/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
1783llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
1784 return emitARCLoadOperation(*this, addr,
1785 CGM.getARCEntrypoints().objc_loadWeak,
1786 "objc_loadWeak");
1787}
1788
1789/// i8* @objc_loadWeakRetained(i8** %addr)
1790llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
1791 return emitARCLoadOperation(*this, addr,
1792 CGM.getARCEntrypoints().objc_loadWeakRetained,
1793 "objc_loadWeakRetained");
1794}
1795
1796/// i8* @objc_storeWeak(i8** %addr, i8* %value)
1797/// Returns %value.
1798llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
1799 llvm::Value *value,
1800 bool ignored) {
1801 return emitARCStoreOperation(*this, addr, value,
1802 CGM.getARCEntrypoints().objc_storeWeak,
1803 "objc_storeWeak", ignored);
1804}
1805
1806/// i8* @objc_initWeak(i8** %addr, i8* %value)
1807/// Returns %value. %addr is known to not have a current weak entry.
1808/// Essentially equivalent to:
1809/// *addr = nil; objc_storeWeak(addr, value);
1810void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
1811 // If we're initializing to null, just write null to memory; no need
1812 // to get the runtime involved. But don't do this if optimization
1813 // is enabled, because accounting for this would make the optimizer
1814 // much more complicated.
1815 if (isa<llvm::ConstantPointerNull>(value) &&
1816 CGM.getCodeGenOpts().OptimizationLevel == 0) {
1817 Builder.CreateStore(value, addr);
1818 return;
1819 }
1820
1821 emitARCStoreOperation(*this, addr, value,
1822 CGM.getARCEntrypoints().objc_initWeak,
1823 "objc_initWeak", /*ignored*/ true);
1824}
1825
1826/// void @objc_destroyWeak(i8** %addr)
1827/// Essentially objc_storeWeak(addr, nil).
1828void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
1829 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
1830 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001831 std::vector<llvm::Type*> args(1, Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001832 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001833 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1834 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
1835 }
1836
1837 // Cast the argument to 'id*'.
1838 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1839
1840 llvm::CallInst *call = Builder.CreateCall(fn, addr);
1841 call->setDoesNotThrow();
1842}
1843
1844/// void @objc_moveWeak(i8** %dest, i8** %src)
1845/// Disregards the current value in %dest. Leaves %src pointing to nothing.
1846/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
1847void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
1848 emitARCCopyOperation(*this, dst, src,
1849 CGM.getARCEntrypoints().objc_moveWeak,
1850 "objc_moveWeak");
1851}
1852
1853/// void @objc_copyWeak(i8** %dest, i8** %src)
1854/// Disregards the current value in %dest. Essentially
1855/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
1856void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
1857 emitARCCopyOperation(*this, dst, src,
1858 CGM.getARCEntrypoints().objc_copyWeak,
1859 "objc_copyWeak");
1860}
1861
1862/// Produce the code to do a objc_autoreleasepool_push.
1863/// call i8* @objc_autoreleasePoolPush(void)
1864llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
1865 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
1866 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001867 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001868 llvm::FunctionType::get(Int8PtrTy, false);
1869 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
1870 }
1871
1872 llvm::CallInst *call = Builder.CreateCall(fn);
1873 call->setDoesNotThrow();
1874
1875 return call;
1876}
1877
1878/// Produce the code to do a primitive release.
1879/// call void @objc_autoreleasePoolPop(i8* %ptr)
1880void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
1881 assert(value->getType() == Int8PtrTy);
1882
1883 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
1884 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001885 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001886 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001887 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1888
1889 // We don't want to use a weak import here; instead we should not
1890 // fall into this path.
1891 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
1892 }
1893
1894 llvm::CallInst *call = Builder.CreateCall(fn, value);
1895 call->setDoesNotThrow();
1896}
1897
1898/// Produce the code to do an MRR version objc_autoreleasepool_push.
1899/// Which is: [[NSAutoreleasePool alloc] init];
1900/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
1901/// init is declared as: - (id) init; in its NSObject super class.
1902///
1903llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
1904 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
1905 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder);
1906 // [NSAutoreleasePool alloc]
1907 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
1908 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
1909 CallArgList Args;
1910 RValue AllocRV =
1911 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
1912 getContext().getObjCIdType(),
1913 AllocSel, Receiver, Args);
1914
1915 // [Receiver init]
1916 Receiver = AllocRV.getScalarVal();
1917 II = &CGM.getContext().Idents.get("init");
1918 Selector InitSel = getContext().Selectors.getSelector(0, &II);
1919 RValue InitRV =
1920 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
1921 getContext().getObjCIdType(),
1922 InitSel, Receiver, Args);
1923 return InitRV.getScalarVal();
1924}
1925
1926/// Produce the code to do a primitive release.
1927/// [tmp drain];
1928void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
1929 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
1930 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
1931 CallArgList Args;
1932 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1933 getContext().VoidTy, DrainSel, Arg, Args);
1934}
1935
John McCallbdc4d802011-07-09 01:37:26 +00001936void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
1937 llvm::Value *addr,
1938 QualType type) {
1939 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
1940 CGF.EmitARCRelease(ptr, /*precise*/ true);
1941}
1942
1943void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
1944 llvm::Value *addr,
1945 QualType type) {
1946 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
1947 CGF.EmitARCRelease(ptr, /*precise*/ false);
1948}
1949
1950void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
1951 llvm::Value *addr,
1952 QualType type) {
1953 CGF.EmitARCDestroyWeak(addr);
1954}
1955
John McCallf85e1932011-06-15 23:02:42 +00001956namespace {
John McCallf85e1932011-06-15 23:02:42 +00001957 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
1958 llvm::Value *Token;
1959
1960 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
1961
John McCallad346f42011-07-12 20:27:29 +00001962 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001963 CGF.EmitObjCAutoreleasePoolPop(Token);
1964 }
1965 };
1966 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
1967 llvm::Value *Token;
1968
1969 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
1970
John McCallad346f42011-07-12 20:27:29 +00001971 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001972 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
1973 }
1974 };
1975}
1976
1977void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
1978 if (CGM.getLangOptions().ObjCAutoRefCount)
1979 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
1980 else
1981 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
1982}
1983
John McCallf85e1932011-06-15 23:02:42 +00001984static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
1985 LValue lvalue,
1986 QualType type) {
1987 switch (type.getObjCLifetime()) {
1988 case Qualifiers::OCL_None:
1989 case Qualifiers::OCL_ExplicitNone:
1990 case Qualifiers::OCL_Strong:
1991 case Qualifiers::OCL_Autoreleasing:
John McCall545d9962011-06-25 02:11:03 +00001992 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(),
John McCallf85e1932011-06-15 23:02:42 +00001993 false);
1994
1995 case Qualifiers::OCL_Weak:
1996 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
1997 true);
1998 }
1999
2000 llvm_unreachable("impossible lifetime!");
2001 return TryEmitResult();
2002}
2003
2004static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2005 const Expr *e) {
2006 e = e->IgnoreParens();
2007 QualType type = e->getType();
2008
John McCall21480112011-08-30 00:57:29 +00002009 // If we're loading retained from a __strong xvalue, we can avoid
2010 // an extra retain/release pair by zeroing out the source of this
2011 // "move" operation.
2012 if (e->isXValue() &&
2013 !type.isConstQualified() &&
2014 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2015 // Emit the lvalue.
2016 LValue lv = CGF.EmitLValue(e);
2017
2018 // Load the object pointer.
2019 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal();
2020
2021 // Set the source pointer to NULL.
2022 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2023
2024 return TryEmitResult(result, true);
2025 }
2026
John McCallf85e1932011-06-15 23:02:42 +00002027 // As a very special optimization, in ARC++, if the l-value is the
2028 // result of a non-volatile assignment, do a simple retain of the
2029 // result of the call to objc_storeWeak instead of reloading.
2030 if (CGF.getLangOptions().CPlusPlus &&
2031 !type.isVolatileQualified() &&
2032 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2033 isa<BinaryOperator>(e) &&
2034 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2035 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2036
2037 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2038}
2039
2040static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2041 llvm::Value *value);
2042
2043/// Given that the given expression is some sort of call (which does
2044/// not return retained), emit a retain following it.
2045static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2046 llvm::Value *value = CGF.EmitScalarExpr(e);
2047 return emitARCRetainAfterCall(CGF, value);
2048}
2049
2050static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2051 llvm::Value *value) {
2052 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2053 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2054
2055 // Place the retain immediately following the call.
2056 CGF.Builder.SetInsertPoint(call->getParent(),
2057 ++llvm::BasicBlock::iterator(call));
2058 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2059
2060 CGF.Builder.restoreIP(ip);
2061 return value;
2062 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2063 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2064
2065 // Place the retain at the beginning of the normal destination block.
2066 llvm::BasicBlock *BB = invoke->getNormalDest();
2067 CGF.Builder.SetInsertPoint(BB, BB->begin());
2068 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2069
2070 CGF.Builder.restoreIP(ip);
2071 return value;
2072
2073 // Bitcasts can arise because of related-result returns. Rewrite
2074 // the operand.
2075 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2076 llvm::Value *operand = bitcast->getOperand(0);
2077 operand = emitARCRetainAfterCall(CGF, operand);
2078 bitcast->setOperand(0, operand);
2079 return bitcast;
2080
2081 // Generic fall-back case.
2082 } else {
2083 // Retain using the non-block variant: we never need to do a copy
2084 // of a block that's been returned to us.
2085 return CGF.EmitARCRetainNonBlock(value);
2086 }
2087}
2088
John McCalldc05b112011-09-10 01:16:55 +00002089/// Determine whether it might be important to emit a separate
2090/// objc_retain_block on the result of the given expression, or
2091/// whether it's okay to just emit it in a +1 context.
2092static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2093 assert(e->getType()->isBlockPointerType());
2094 e = e->IgnoreParens();
2095
2096 // For future goodness, emit block expressions directly in +1
2097 // contexts if we can.
2098 if (isa<BlockExpr>(e))
2099 return false;
2100
2101 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2102 switch (cast->getCastKind()) {
2103 // Emitting these operations in +1 contexts is goodness.
2104 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00002105 case CK_ARCReclaimReturnedObject:
2106 case CK_ARCConsumeObject:
2107 case CK_ARCProduceObject:
John McCalldc05b112011-09-10 01:16:55 +00002108 return false;
2109
2110 // These operations preserve a block type.
2111 case CK_NoOp:
2112 case CK_BitCast:
2113 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2114
2115 // These operations are known to be bad (or haven't been considered).
2116 case CK_AnyPointerToBlockPointerCast:
2117 default:
2118 return true;
2119 }
2120 }
2121
2122 return true;
2123}
2124
John McCall4b9c2d22011-11-06 09:01:30 +00002125/// Try to emit a PseudoObjectExpr at +1.
2126///
2127/// This massively duplicates emitPseudoObjectRValue.
2128static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
2129 const PseudoObjectExpr *E) {
2130 llvm::SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
2131
2132 // Find the result expression.
2133 const Expr *resultExpr = E->getResultExpr();
2134 assert(resultExpr);
2135 TryEmitResult result;
2136
2137 for (PseudoObjectExpr::const_semantics_iterator
2138 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2139 const Expr *semantic = *i;
2140
2141 // If this semantic expression is an opaque value, bind it
2142 // to the result of its source expression.
2143 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2144 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2145 OVMA opaqueData;
2146
2147 // If this semantic is the result of the pseudo-object
2148 // expression, try to evaluate the source as +1.
2149 if (ov == resultExpr) {
2150 assert(!OVMA::shouldBindAsLValue(ov));
2151 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
2152 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
2153
2154 // Otherwise, just bind it.
2155 } else {
2156 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2157 }
2158 opaques.push_back(opaqueData);
2159
2160 // Otherwise, if the expression is the result, evaluate it
2161 // and remember the result.
2162 } else if (semantic == resultExpr) {
2163 result = tryEmitARCRetainScalarExpr(CGF, semantic);
2164
2165 // Otherwise, evaluate the expression in an ignored context.
2166 } else {
2167 CGF.EmitIgnoredExpr(semantic);
2168 }
2169 }
2170
2171 // Unbind all the opaques now.
2172 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2173 opaques[i].unbind(CGF);
2174
2175 return result;
2176}
2177
John McCallf85e1932011-06-15 23:02:42 +00002178static TryEmitResult
2179tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCall990567c2011-07-27 01:07:15 +00002180 // Look through cleanups.
2181 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
John McCall1a343eb2011-11-10 08:15:53 +00002182 CGF.enterFullExpression(cleanups);
John McCall990567c2011-07-27 01:07:15 +00002183 CodeGenFunction::RunCleanupsScope scope(CGF);
2184 return tryEmitARCRetainScalarExpr(CGF, cleanups->getSubExpr());
2185 }
2186
John McCallf85e1932011-06-15 23:02:42 +00002187 // The desired result type, if it differs from the type of the
2188 // ultimate opaque expression.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002189 llvm::Type *resultType = 0;
John McCallf85e1932011-06-15 23:02:42 +00002190
2191 while (true) {
2192 e = e->IgnoreParens();
2193
2194 // There's a break at the end of this if-chain; anything
2195 // that wants to keep looping has to explicitly continue.
2196 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2197 switch (ce->getCastKind()) {
2198 // No-op casts don't change the type, so we just ignore them.
2199 case CK_NoOp:
2200 e = ce->getSubExpr();
2201 continue;
2202
2203 case CK_LValueToRValue: {
2204 TryEmitResult loadResult
2205 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2206 if (resultType) {
2207 llvm::Value *value = loadResult.getPointer();
2208 value = CGF.Builder.CreateBitCast(value, resultType);
2209 loadResult.setPointer(value);
2210 }
2211 return loadResult;
2212 }
2213
2214 // These casts can change the type, so remember that and
2215 // soldier on. We only need to remember the outermost such
2216 // cast, though.
John McCall1d9b3b22011-09-09 05:25:32 +00002217 case CK_CPointerToObjCPointerCast:
2218 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00002219 case CK_AnyPointerToBlockPointerCast:
2220 case CK_BitCast:
2221 if (!resultType)
2222 resultType = CGF.ConvertType(ce->getType());
2223 e = ce->getSubExpr();
2224 assert(e->getType()->hasPointerRepresentation());
2225 continue;
2226
2227 // For consumptions, just emit the subexpression and thus elide
2228 // the retain/release pair.
John McCall33e56f32011-09-10 06:18:15 +00002229 case CK_ARCConsumeObject: {
John McCallf85e1932011-06-15 23:02:42 +00002230 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2231 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2232 return TryEmitResult(result, true);
2233 }
2234
John McCalldc05b112011-09-10 01:16:55 +00002235 // Block extends are net +0. Naively, we could just recurse on
2236 // the subexpression, but actually we need to ensure that the
2237 // value is copied as a block, so there's a little filter here.
John McCall33e56f32011-09-10 06:18:15 +00002238 case CK_ARCExtendBlockObject: {
John McCalldc05b112011-09-10 01:16:55 +00002239 llvm::Value *result; // will be a +0 value
2240
2241 // If we can't safely assume the sub-expression will produce a
2242 // block-copied value, emit the sub-expression at +0.
2243 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2244 result = CGF.EmitScalarExpr(ce->getSubExpr());
2245
2246 // Otherwise, try to emit the sub-expression at +1 recursively.
2247 } else {
2248 TryEmitResult subresult
2249 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2250 result = subresult.getPointer();
2251
2252 // If that produced a retained value, just use that,
2253 // possibly casting down.
2254 if (subresult.getInt()) {
2255 if (resultType)
2256 result = CGF.Builder.CreateBitCast(result, resultType);
2257 return TryEmitResult(result, true);
2258 }
2259
2260 // Otherwise it's +0.
2261 }
2262
2263 // Retain the object as a block, then cast down.
John McCall348f16f2011-10-04 06:23:45 +00002264 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
John McCalldc05b112011-09-10 01:16:55 +00002265 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2266 return TryEmitResult(result, true);
2267 }
2268
John McCall7e5e5f42011-07-07 06:58:02 +00002269 // For reclaims, emit the subexpression as a retained call and
2270 // skip the consumption.
John McCall33e56f32011-09-10 06:18:15 +00002271 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00002272 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2273 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2274 return TryEmitResult(result, true);
2275 }
2276
John McCallf85e1932011-06-15 23:02:42 +00002277 default:
2278 break;
2279 }
2280
2281 // Skip __extension__.
2282 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2283 if (op->getOpcode() == UO_Extension) {
2284 e = op->getSubExpr();
2285 continue;
2286 }
2287
2288 // For calls and message sends, use the retained-call logic.
2289 // Delegate inits are a special case in that they're the only
2290 // returns-retained expression that *isn't* surrounded by
2291 // a consume.
2292 } else if (isa<CallExpr>(e) ||
2293 (isa<ObjCMessageExpr>(e) &&
2294 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2295 llvm::Value *result = emitARCRetainCall(CGF, e);
2296 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2297 return TryEmitResult(result, true);
John McCall4b9c2d22011-11-06 09:01:30 +00002298
2299 // Look through pseudo-object expressions.
2300 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2301 TryEmitResult result
2302 = tryEmitARCRetainPseudoObject(CGF, pseudo);
2303 if (resultType) {
2304 llvm::Value *value = result.getPointer();
2305 value = CGF.Builder.CreateBitCast(value, resultType);
2306 result.setPointer(value);
2307 }
2308 return result;
John McCallf85e1932011-06-15 23:02:42 +00002309 }
2310
2311 // Conservatively halt the search at any other expression kind.
2312 break;
2313 }
2314
2315 // We didn't find an obvious production, so emit what we've got and
2316 // tell the caller that we didn't manage to retain.
2317 llvm::Value *result = CGF.EmitScalarExpr(e);
2318 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2319 return TryEmitResult(result, false);
2320}
2321
2322static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2323 LValue lvalue,
2324 QualType type) {
2325 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2326 llvm::Value *value = result.getPointer();
2327 if (!result.getInt())
2328 value = CGF.EmitARCRetain(type, value);
2329 return value;
2330}
2331
2332/// EmitARCRetainScalarExpr - Semantically equivalent to
2333/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2334/// best-effort attempt to peephole expressions that naturally produce
2335/// retained objects.
2336llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
2337 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2338 llvm::Value *value = result.getPointer();
2339 if (!result.getInt())
2340 value = EmitARCRetain(e->getType(), value);
2341 return value;
2342}
2343
2344llvm::Value *
2345CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
2346 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2347 llvm::Value *value = result.getPointer();
2348 if (result.getInt())
2349 value = EmitARCAutorelease(value);
2350 else
2351 value = EmitARCRetainAutorelease(e->getType(), value);
2352 return value;
2353}
2354
John McCall348f16f2011-10-04 06:23:45 +00002355llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2356 llvm::Value *result;
2357 bool doRetain;
2358
2359 if (shouldEmitSeparateBlockRetain(e)) {
2360 result = EmitScalarExpr(e);
2361 doRetain = true;
2362 } else {
2363 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2364 result = subresult.getPointer();
2365 doRetain = !subresult.getInt();
2366 }
2367
2368 if (doRetain)
2369 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2370 return EmitObjCConsumeObject(e->getType(), result);
2371}
2372
John McCall2b014d62011-10-01 10:32:24 +00002373llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2374 // In ARC, retain and autorelease the expression.
2375 if (getLangOptions().ObjCAutoRefCount) {
2376 // Do so before running any cleanups for the full-expression.
2377 // tryEmitARCRetainScalarExpr does make an effort to do things
2378 // inside cleanups, but there are crazy cases like
2379 // @throw A().foo;
2380 // where a full retain+autorelease is required and would
2381 // otherwise happen after the destructor for the temporary.
John McCall1a343eb2011-11-10 08:15:53 +00002382 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(expr)) {
2383 enterFullExpression(ewc);
John McCall2b014d62011-10-01 10:32:24 +00002384 expr = ewc->getSubExpr();
John McCall1a343eb2011-11-10 08:15:53 +00002385 }
John McCall2b014d62011-10-01 10:32:24 +00002386
John McCall1a343eb2011-11-10 08:15:53 +00002387 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall2b014d62011-10-01 10:32:24 +00002388 return EmitARCRetainAutoreleaseScalarExpr(expr);
2389 }
2390
2391 // Otherwise, use the normal scalar-expression emission. The
2392 // exception machinery doesn't do anything special with the
2393 // exception like retaining it, so there's no safety associated with
2394 // only running cleanups after the throw has started, and when it
2395 // matters it tends to be substantially inferior code.
2396 return EmitScalarExpr(expr);
2397}
2398
John McCallf85e1932011-06-15 23:02:42 +00002399std::pair<LValue,llvm::Value*>
2400CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2401 bool ignored) {
2402 // Evaluate the RHS first.
2403 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2404 llvm::Value *value = result.getPointer();
2405
John McCallfb720812011-07-28 07:23:35 +00002406 bool hasImmediateRetain = result.getInt();
2407
2408 // If we didn't emit a retained object, and the l-value is of block
2409 // type, then we need to emit the block-retain immediately in case
2410 // it invalidates the l-value.
2411 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCall348f16f2011-10-04 06:23:45 +00002412 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallfb720812011-07-28 07:23:35 +00002413 hasImmediateRetain = true;
2414 }
2415
John McCallf85e1932011-06-15 23:02:42 +00002416 LValue lvalue = EmitLValue(e->getLHS());
2417
2418 // If the RHS was emitted retained, expand this.
John McCallfb720812011-07-28 07:23:35 +00002419 if (hasImmediateRetain) {
John McCallf85e1932011-06-15 23:02:42 +00002420 llvm::Value *oldValue =
Eli Friedman6da2c712011-12-03 04:14:32 +00002421 EmitLoadOfScalar(lvalue);
2422 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +00002423 EmitARCRelease(oldValue, /*precise*/ false);
2424 } else {
John McCall545d9962011-06-25 02:11:03 +00002425 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCallf85e1932011-06-15 23:02:42 +00002426 }
2427
2428 return std::pair<LValue,llvm::Value*>(lvalue, value);
2429}
2430
2431std::pair<LValue,llvm::Value*>
2432CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2433 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2434 LValue lvalue = EmitLValue(e->getLHS());
2435
Eli Friedman6da2c712011-12-03 04:14:32 +00002436 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +00002437
2438 return std::pair<LValue,llvm::Value*>(lvalue, value);
2439}
2440
2441void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
2442 const ObjCAutoreleasePoolStmt &ARPS) {
2443 const Stmt *subStmt = ARPS.getSubStmt();
2444 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2445
2446 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00002447 if (DI)
2448 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002449
2450 // Keep track of the current cleanup stack depth.
2451 RunCleanupsScope Scope(*this);
John McCall9f084a32011-07-06 00:26:06 +00002452 if (CGM.getCodeGenOpts().ObjCRuntimeHasARC) {
John McCallf85e1932011-06-15 23:02:42 +00002453 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2454 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2455 } else {
2456 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2457 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2458 }
2459
2460 for (CompoundStmt::const_body_iterator I = S.body_begin(),
2461 E = S.body_end(); I != E; ++I)
2462 EmitStmt(*I);
2463
Eric Christopher73fb3502011-10-13 21:45:18 +00002464 if (DI)
2465 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002466}
John McCall0c24c802011-06-24 23:21:27 +00002467
2468/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2469/// make sure it survives garbage collection until this point.
2470void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2471 // We just use an inline assembly.
John McCall0c24c802011-06-24 23:21:27 +00002472 llvm::FunctionType *extenderType
Jay Foadda549e82011-07-29 13:56:53 +00002473 = llvm::FunctionType::get(VoidTy, VoidPtrTy, /*variadic*/ false);
John McCall0c24c802011-06-24 23:21:27 +00002474 llvm::Value *extender
2475 = llvm::InlineAsm::get(extenderType,
2476 /* assembly */ "",
2477 /* constraints */ "r",
2478 /* side effects */ true);
2479
2480 object = Builder.CreateBitCast(object, VoidPtrTy);
2481 Builder.CreateCall(extender, object)->setDoesNotThrow();
2482}
2483
Ted Kremenek2979ec72008-04-09 15:51:31 +00002484CGObjCRuntime::~CGObjCRuntime() {}