blob: ddf6e1f98a727b7b683e33a0259572c0e0774a0d [file] [log] [blame]
Anders Carlsson55085182007-08-21 17:43:55 +00001//===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Anders Carlsson55085182007-08-21 17:43:55 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Objective-C code as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Devang Patelbcbd03a2011-01-19 01:36:36 +000014#include "CGDebugInfo.h"
Ted Kremenek2979ec72008-04-09 15:51:31 +000015#include "CGObjCRuntime.h"
Anders Carlsson55085182007-08-21 17:43:55 +000016#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
John McCallf85e1932011-06-15 23:02:42 +000018#include "TargetInfo.h"
Daniel Dunbar85c59ed2008-08-29 08:11:39 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Chris Lattner16f00492009-04-26 01:32:48 +000021#include "clang/AST/StmtObjC.h"
Daniel Dunbare66f4e32008-09-03 00:27:26 +000022#include "clang/Basic/Diagnostic.h"
Anders Carlsson3d8400d2008-08-30 19:51:14 +000023#include "llvm/ADT/STLExtras.h"
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +000024#include "llvm/Target/TargetData.h"
John McCallf85e1932011-06-15 23:02:42 +000025#include "llvm/InlineAsm.h"
Anders Carlsson55085182007-08-21 17:43:55 +000026using namespace clang;
27using namespace CodeGen;
28
John McCallf85e1932011-06-15 23:02:42 +000029typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
30static TryEmitResult
31tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
32
33/// Given the address of a variable of pointer type, find the correct
34/// null to store into it.
35static llvm::Constant *getNullForVariable(llvm::Value *addr) {
Chris Lattner2acc6e32011-07-18 04:24:23 +000036 llvm::Type *type =
John McCallf85e1932011-06-15 23:02:42 +000037 cast<llvm::PointerType>(addr->getType())->getElementType();
38 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
39}
40
Chris Lattner8fdf3282008-06-24 17:04:18 +000041/// Emits an instance of NSConstantString representing the object.
Mike Stump1eb44332009-09-09 15:08:12 +000042llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar71fcec92008-11-25 21:53:21 +000043{
David Chisnall0d13f6f2010-01-23 02:40:42 +000044 llvm::Constant *C =
45 CGM.getObjCRuntime().GenerateConstantString(E->getString());
Daniel Dunbared7c6182008-08-20 00:28:19 +000046 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Anderson3c4972d2009-07-29 18:54:39 +000047 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattner8fdf3282008-06-24 17:04:18 +000048}
49
50/// Emit a selector.
51llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
52 // Untyped selector.
53 // Note that this implementation allows for non-constant strings to be passed
54 // as arguments to @selector(). Currently, the only thing preventing this
55 // behaviour is the type checking in the front end.
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +000056 return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
Chris Lattner8fdf3282008-06-24 17:04:18 +000057}
58
Daniel Dunbared7c6182008-08-20 00:28:19 +000059llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
60 // FIXME: This should pass the Decl not the name.
61 return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol());
62}
Chris Lattner8fdf3282008-06-24 17:04:18 +000063
Douglas Gregor926df6c2011-06-11 01:09:30 +000064/// \brief Adjust the type of the result of an Objective-C message send
65/// expression when the method has a related result type.
66static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
67 const Expr *E,
68 const ObjCMethodDecl *Method,
69 RValue Result) {
70 if (!Method)
71 return Result;
John McCallf85e1932011-06-15 23:02:42 +000072
Douglas Gregor926df6c2011-06-11 01:09:30 +000073 if (!Method->hasRelatedResultType() ||
74 CGF.getContext().hasSameType(E->getType(), Method->getResultType()) ||
75 !Result.isScalar())
76 return Result;
77
78 // We have applied a related result type. Cast the rvalue appropriately.
79 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
80 CGF.ConvertType(E->getType())));
81}
Chris Lattner8fdf3282008-06-24 17:04:18 +000082
John McCalldc7c5ad2011-07-22 08:53:00 +000083/// Decide whether to extend the lifetime of the receiver of a
84/// returns-inner-pointer message.
85static bool
86shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
87 switch (message->getReceiverKind()) {
88
89 // For a normal instance message, we should extend unless the
90 // receiver is loaded from a variable with precise lifetime.
91 case ObjCMessageExpr::Instance: {
92 const Expr *receiver = message->getInstanceReceiver();
93 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
94 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
95 receiver = ice->getSubExpr()->IgnoreParens();
96
97 // Only __strong variables.
98 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
99 return true;
100
101 // All ivars and fields have precise lifetime.
102 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
103 return false;
104
105 // Otherwise, check for variables.
106 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
107 if (!declRef) return true;
108 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
109 if (!var) return true;
110
111 // All variables have precise lifetime except local variables with
112 // automatic storage duration that aren't specially marked.
113 return (var->hasLocalStorage() &&
114 !var->hasAttr<ObjCPreciseLifetimeAttr>());
115 }
116
117 case ObjCMessageExpr::Class:
118 case ObjCMessageExpr::SuperClass:
119 // It's never necessary for class objects.
120 return false;
121
122 case ObjCMessageExpr::SuperInstance:
123 // We generally assume that 'self' lives throughout a method call.
124 return false;
125 }
126
127 llvm_unreachable("invalid receiver kind");
128}
129
John McCallef072fd2010-05-22 01:48:05 +0000130RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
131 ReturnValueSlot Return) {
Chris Lattner8fdf3282008-06-24 17:04:18 +0000132 // Only the lookup mechanism and first two arguments of the method
133 // implementation vary between runtimes. We can get the receiver and
134 // arguments in generic code.
Mike Stump1eb44332009-09-09 15:08:12 +0000135
John McCallf85e1932011-06-15 23:02:42 +0000136 bool isDelegateInit = E->isDelegateInitCall();
137
John McCalldc7c5ad2011-07-22 08:53:00 +0000138 const ObjCMethodDecl *method = E->getMethodDecl();
139
John McCallf85e1932011-06-15 23:02:42 +0000140 // We don't retain the receiver in delegate init calls, and this is
141 // safe because the receiver value is always loaded from 'self',
142 // which we zero out. We don't want to Block_copy block receivers,
143 // though.
144 bool retainSelf =
145 (!isDelegateInit &&
146 CGM.getLangOptions().ObjCAutoRefCount &&
John McCalldc7c5ad2011-07-22 08:53:00 +0000147 method &&
148 method->hasAttr<NSConsumesSelfAttr>());
John McCallf85e1932011-06-15 23:02:42 +0000149
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000150 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000151 bool isSuperMessage = false;
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000152 bool isClassMessage = false;
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000153 ObjCInterfaceDecl *OID = 0;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000154 // Find the receiver
Douglas Gregor926df6c2011-06-11 01:09:30 +0000155 QualType ReceiverType;
Daniel Dunbar0b647a62010-04-22 03:17:06 +0000156 llvm::Value *Receiver = 0;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000157 switch (E->getReceiverKind()) {
158 case ObjCMessageExpr::Instance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000159 ReceiverType = E->getInstanceReceiver()->getType();
John McCallf85e1932011-06-15 23:02:42 +0000160 if (retainSelf) {
161 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
162 E->getInstanceReceiver());
163 Receiver = ter.getPointer();
John McCalldc7c5ad2011-07-22 08:53:00 +0000164 if (ter.getInt()) retainSelf = false;
John McCallf85e1932011-06-15 23:02:42 +0000165 } else
166 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor04badcf2010-04-21 00:45:42 +0000167 break;
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000168
Douglas Gregor04badcf2010-04-21 00:45:42 +0000169 case ObjCMessageExpr::Class: {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000170 ReceiverType = E->getClassReceiver();
171 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3031c632010-05-17 20:12:43 +0000172 assert(ObjTy && "Invalid Objective-C class message send");
173 OID = ObjTy->getInterface();
174 assert(OID && "Invalid Objective-C class message send");
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000175 Receiver = Runtime.GetClass(Builder, OID);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000176 isClassMessage = true;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000177 break;
178 }
179
180 case ObjCMessageExpr::SuperInstance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000181 ReceiverType = E->getSuperType();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000182 Receiver = LoadObjCSelf();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000183 isSuperMessage = true;
184 break;
185
186 case ObjCMessageExpr::SuperClass:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000187 ReceiverType = E->getSuperType();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000188 Receiver = LoadObjCSelf();
189 isSuperMessage = true;
190 isClassMessage = true;
191 break;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000192 }
193
John McCalldc7c5ad2011-07-22 08:53:00 +0000194 if (retainSelf)
195 Receiver = EmitARCRetainNonBlock(Receiver);
196
197 // In ARC, we sometimes want to "extend the lifetime"
198 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
199 // messages.
200 if (getLangOptions().ObjCAutoRefCount && method &&
201 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
202 shouldExtendReceiverForInnerPointerMessage(E))
203 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
204
John McCallf85e1932011-06-15 23:02:42 +0000205 QualType ResultType =
John McCalldc7c5ad2011-07-22 08:53:00 +0000206 method ? method->getResultType() : E->getType();
John McCallf85e1932011-06-15 23:02:42 +0000207
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000208 CallArgList Args;
John McCalldc7c5ad2011-07-22 08:53:00 +0000209 EmitCallArgs(Args, method, E->arg_begin(), E->arg_end());
Mike Stump1eb44332009-09-09 15:08:12 +0000210
John McCallf85e1932011-06-15 23:02:42 +0000211 // For delegate init calls in ARC, do an unsafe store of null into
212 // self. This represents the call taking direct ownership of that
213 // value. We have to do this after emitting the other call
214 // arguments because they might also reference self, but we don't
215 // have to worry about any of them modifying self because that would
216 // be an undefined read and write of an object in unordered
217 // expressions.
218 if (isDelegateInit) {
219 assert(getLangOptions().ObjCAutoRefCount &&
220 "delegate init calls should only be marked in ARC");
221
222 // Do an unsafe store of null into self.
223 llvm::Value *selfAddr =
224 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
225 assert(selfAddr && "no self entry for a delegate init call?");
226
227 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
228 }
Anders Carlsson7e70fb22010-06-21 20:59:55 +0000229
Douglas Gregor926df6c2011-06-11 01:09:30 +0000230 RValue result;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000231 if (isSuperMessage) {
Chris Lattner9384c762008-06-26 04:42:20 +0000232 // super is only valid in an Objective-C method
233 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000234 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor926df6c2011-06-11 01:09:30 +0000235 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
236 E->getSelector(),
237 OMD->getClassInterface(),
238 isCategoryImpl,
239 Receiver,
240 isClassMessage,
241 Args,
John McCalldc7c5ad2011-07-22 08:53:00 +0000242 method);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000243 } else {
244 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
245 E->getSelector(),
246 Receiver, Args, OID,
John McCalldc7c5ad2011-07-22 08:53:00 +0000247 method);
Chris Lattner8fdf3282008-06-24 17:04:18 +0000248 }
John McCallf85e1932011-06-15 23:02:42 +0000249
250 // For delegate init calls in ARC, implicitly store the result of
251 // the call back into self. This takes ownership of the value.
252 if (isDelegateInit) {
253 llvm::Value *selfAddr =
254 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
255 llvm::Value *newSelf = result.getScalarVal();
256
257 // The delegate return type isn't necessarily a matching type; in
258 // fact, it's quite likely to be 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000259 llvm::Type *selfTy =
John McCallf85e1932011-06-15 23:02:42 +0000260 cast<llvm::PointerType>(selfAddr->getType())->getElementType();
261 newSelf = Builder.CreateBitCast(newSelf, selfTy);
262
263 Builder.CreateStore(newSelf, selfAddr);
264 }
265
John McCalldc7c5ad2011-07-22 08:53:00 +0000266 return AdjustRelatedResultType(*this, E, method, result);
Anders Carlsson55085182007-08-21 17:43:55 +0000267}
268
John McCallf85e1932011-06-15 23:02:42 +0000269namespace {
270struct FinishARCDealloc : EHScopeStack::Cleanup {
John McCallad346f42011-07-12 20:27:29 +0000271 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +0000272 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCall799d34e2011-07-13 18:26:47 +0000273
274 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCallf85e1932011-06-15 23:02:42 +0000275 const ObjCInterfaceDecl *iface = impl->getClassInterface();
276 if (!iface->getSuperClass()) return;
277
John McCall799d34e2011-07-13 18:26:47 +0000278 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
279
John McCallf85e1932011-06-15 23:02:42 +0000280 // Call [super dealloc] if we have a superclass.
281 llvm::Value *self = CGF.LoadObjCSelf();
282
283 CallArgList args;
284 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
285 CGF.getContext().VoidTy,
286 method->getSelector(),
287 iface,
John McCall799d34e2011-07-13 18:26:47 +0000288 isCategory,
John McCallf85e1932011-06-15 23:02:42 +0000289 self,
290 /*is class msg*/ false,
291 args,
292 method);
293 }
294};
295}
296
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000297/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
298/// the LLVM function and sets the other context used by
299/// CodeGenFunction.
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000300void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
Devang Patel8d3f8972011-05-19 23:37:41 +0000301 const ObjCContainerDecl *CD,
302 SourceLocation StartLoc) {
John McCalld26bc762011-03-09 04:27:21 +0000303 FunctionArgList args;
Devang Patel4800ea62010-04-05 21:09:15 +0000304 // Check if we should generate debug info for this method.
Devang Patelaa112892011-03-07 18:45:56 +0000305 if (CGM.getModuleDebugInfo() && !OMD->hasAttr<NoDebugAttr>())
306 DebugInfo = CGM.getModuleDebugInfo();
Devang Patel4800ea62010-04-05 21:09:15 +0000307
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000308 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000309
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000310 const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(OMD);
311 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner41110242008-06-17 18:05:57 +0000312
John McCalld26bc762011-03-09 04:27:21 +0000313 args.push_back(OMD->getSelfDecl());
314 args.push_back(OMD->getCmdDecl());
Chris Lattner41110242008-06-17 18:05:57 +0000315
Chris Lattner89951a82009-02-20 18:43:26 +0000316 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
317 E = OMD->param_end(); PI != E; ++PI)
John McCalld26bc762011-03-09 04:27:21 +0000318 args.push_back(*PI);
Chris Lattner41110242008-06-17 18:05:57 +0000319
Peter Collingbourne14110472011-01-13 18:57:25 +0000320 CurGD = OMD;
321
Devang Patel8d3f8972011-05-19 23:37:41 +0000322 StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc);
John McCallf85e1932011-06-15 23:02:42 +0000323
324 // In ARC, certain methods get an extra cleanup.
325 if (CGM.getLangOptions().ObjCAutoRefCount &&
326 OMD->isInstanceMethod() &&
327 OMD->getSelector().isUnarySelector()) {
328 const IdentifierInfo *ident =
329 OMD->getSelector().getIdentifierInfoForSlot(0);
330 if (ident->isStr("dealloc"))
331 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
332 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000333}
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000334
John McCallf85e1932011-06-15 23:02:42 +0000335static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
336 LValue lvalue, QualType type);
337
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000338/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump1eb44332009-09-09 15:08:12 +0000339/// its pointer, name, and types registered in the class struture.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000340void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
Devang Patel8d3f8972011-05-19 23:37:41 +0000341 StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000342 EmitStmt(OMD->getBody());
343 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000344}
345
John McCall41bdde92011-09-12 23:06:44 +0000346/// emitStructGetterCall - Call the runtime function to load a property
347/// into the return value slot.
348static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
349 bool isAtomic, bool hasStrong) {
350 ASTContext &Context = CGF.getContext();
351
352 llvm::Value *src =
353 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(),
354 ivar, 0).getAddress();
355
356 // objc_copyStruct (ReturnValue, &structIvar,
357 // sizeof (Type of Ivar), isAtomic, false);
358 CallArgList args;
359
360 llvm::Value *dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
361 args.add(RValue::get(dest), Context.VoidPtrTy);
362
363 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
364 args.add(RValue::get(src), Context.VoidPtrTy);
365
366 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
367 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
368 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
369 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
370
371 llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
372 CGF.EmitCall(CGF.getTypes().getFunctionInfo(Context.VoidTy, args,
373 FunctionType::ExtInfo()),
374 fn, ReturnValueSlot(), args);
375}
376
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) {
381 return (arch == llvm::Triple::x86 || arch == llvm::Triple::x86_64);
382}
383
384/// Return the maximum size that permits atomic accesses for the given
385/// architecture.
386static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
387 llvm::Triple::ArchType arch) {
388 // ARM has 8-byte atomic accesses, but it's not clear whether we
389 // want to rely on them here.
390
391 // In the default case, just assume that any size up to a pointer is
392 // fine given adequate alignment.
393 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
394}
395
396namespace {
397 class PropertyImplStrategy {
398 public:
399 enum StrategyKind {
400 /// The 'native' strategy is to use the architecture's provided
401 /// reads and writes.
402 Native,
403
404 /// Use objc_setProperty and objc_getProperty.
405 GetSetProperty,
406
407 /// Use objc_setProperty for the setter, but use expression
408 /// evaluation for the getter.
409 SetPropertyAndExpressionGet,
410
411 /// Use objc_copyStruct.
412 CopyStruct,
413
414 /// The 'expression' strategy is to emit normal assignment or
415 /// lvalue-to-rvalue expressions.
416 Expression
417 };
418
419 StrategyKind getKind() const { return StrategyKind(Kind); }
420
421 bool hasStrongMember() const { return HasStrong; }
422 bool isAtomic() const { return IsAtomic; }
423 bool isCopy() const { return IsCopy; }
424
425 CharUnits getIvarSize() const { return IvarSize; }
426 CharUnits getIvarAlignment() const { return IvarAlignment; }
427
428 PropertyImplStrategy(CodeGenModule &CGM,
429 const ObjCPropertyImplDecl *propImpl);
430
431 private:
432 unsigned Kind : 8;
433 unsigned IsAtomic : 1;
434 unsigned IsCopy : 1;
435 unsigned HasStrong : 1;
436
437 CharUnits IvarSize;
438 CharUnits IvarAlignment;
439 };
440}
441
442/// Pick an implementation strategy for the the given property synthesis.
443PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
444 const ObjCPropertyImplDecl *propImpl) {
445 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
446 ObjCPropertyDecl::PropertyAttributeKind attrs = prop->getPropertyAttributes();
447
448 IsCopy = (attrs & ObjCPropertyDecl::OBJC_PR_copy);
449 IsAtomic = !(attrs & ObjCPropertyDecl::OBJC_PR_nonatomic);
450 HasStrong = false; // doesn't matter here.
451
452 // Evaluate the ivar's size and alignment.
453 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
454 QualType ivarType = ivar->getType();
455 llvm::tie(IvarSize, IvarAlignment)
456 = CGM.getContext().getTypeInfoInChars(ivarType);
457
458 // If we have a copy property, we always have to use getProperty/setProperty.
459 if (IsCopy) {
460 Kind = GetSetProperty;
461 return;
462 }
463
464 // Handle retain/strong.
465 if (attrs & (ObjCPropertyDecl::OBJC_PR_retain
466 | ObjCPropertyDecl::OBJC_PR_strong)) {
467 // In GC-only, there's nothing special that needs to be done.
468 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly) {
469 // fallthrough
470
471 // In ARC, if the property is non-atomic, use expression emission,
472 // which translates to objc_storeStrong. This isn't required, but
473 // it's slightly nicer.
474 } else if (CGM.getLangOptions().ObjCAutoRefCount && !IsAtomic) {
475 Kind = Expression;
476 return;
477
478 // Otherwise, we need to at least use setProperty. However, if
479 // the property isn't atomic, we can use normal expression
480 // emission for the getter.
481 } else if (!IsAtomic) {
482 Kind = SetPropertyAndExpressionGet;
483 return;
484
485 // Otherwise, we have to use both setProperty and getProperty.
486 } else {
487 Kind = GetSetProperty;
488 return;
489 }
490 }
491
492 // If we're not atomic, just use expression accesses.
493 if (!IsAtomic) {
494 Kind = Expression;
495 return;
496 }
497
John McCall5889c602011-09-13 05:36:29 +0000498 // Properties on bitfield ivars need to be emitted using expression
499 // accesses even if they're nominally atomic.
500 if (ivar->isBitField()) {
501 Kind = Expression;
502 return;
503 }
504
John McCall1e1f4872011-09-13 03:34:09 +0000505 // GC-qualified or ARC-qualified ivars need to be emitted as
506 // expressions. This actually works out to being atomic anyway,
507 // except for ARC __strong, but that should trigger the above code.
508 if (ivarType.hasNonTrivialObjCLifetime() ||
509 (CGM.getLangOptions().getGCMode() &&
510 CGM.getContext().getObjCGCAttrKind(ivarType))) {
511 Kind = Expression;
512 return;
513 }
514
515 // Compute whether the ivar has strong members.
516 if (CGM.getLangOptions().getGCMode())
517 if (const RecordType *recordType = ivarType->getAs<RecordType>())
518 HasStrong = recordType->getDecl()->hasObjectMember();
519
520 // We can never access structs with object members with a native
521 // access, because we need to use write barriers. This is what
522 // objc_copyStruct is for.
523 if (HasStrong) {
524 Kind = CopyStruct;
525 return;
526 }
527
528 // Otherwise, this is target-dependent and based on the size and
529 // alignment of the ivar.
John McCallc5d9a902011-09-13 07:33:34 +0000530
531 // If the size of the ivar is not a power of two, give up. We don't
532 // want to get into the business of doing compare-and-swaps.
533 if (!IvarSize.isPowerOfTwo()) {
534 Kind = CopyStruct;
535 return;
536 }
537
John McCall1e1f4872011-09-13 03:34:09 +0000538 llvm::Triple::ArchType arch =
539 CGM.getContext().getTargetInfo().getTriple().getArch();
540
541 // Most architectures require memory to fit within a single cache
542 // line, so the alignment has to be at least the size of the access.
543 // Otherwise we have to grab a lock.
544 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
545 Kind = CopyStruct;
546 return;
547 }
548
549 // If the ivar's size exceeds the architecture's maximum atomic
550 // access size, we have to use CopyStruct.
551 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
552 Kind = CopyStruct;
553 return;
554 }
555
556 // Otherwise, we can use native loads and stores.
557 Kind = Native;
558}
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000559
560/// GenerateObjCGetter - Generate an Objective-C property getter
Steve Naroff489034c2009-01-10 22:55:25 +0000561/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
562/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000563void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
564 const ObjCPropertyImplDecl *PID) {
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000565 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
566 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
567 assert(OMD && "Invalid call to generate getter (empty method)");
Devang Patel8d3f8972011-05-19 23:37:41 +0000568 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +0000569
John McCall1e1f4872011-09-13 03:34:09 +0000570 generateObjCGetterBody(IMP, PID);
571
572 FinishFunction();
573}
574
John McCall6c11f0b2011-09-13 06:00:03 +0000575static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
576 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCall1e1f4872011-09-13 03:34:09 +0000577 if (!getter) return true;
578
579 // Sema only makes only of these when the ivar has a C++ class type,
580 // so the form is pretty constrained.
581
John McCall6c11f0b2011-09-13 06:00:03 +0000582 // If the property has a reference type, we might just be binding a
583 // reference, in which case the result will be a gl-value. We should
584 // treat this as a non-trivial operation.
585 if (getter->isGLValue())
586 return false;
587
John McCall1e1f4872011-09-13 03:34:09 +0000588 // If we selected a trivial copy-constructor, we're okay.
589 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
590 return (construct->getConstructor()->isTrivial());
591
592 // The constructor might require cleanups (in which case it's never
593 // trivial).
594 assert(isa<ExprWithCleanups>(getter));
595 return false;
596}
597
598void
599CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
600 const ObjCPropertyImplDecl *propImpl) {
601 // If there's a non-trivial 'get' expression, we just have to emit that.
602 if (!hasTrivialGetExpr(propImpl)) {
603 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
604 /*nrvo*/ 0);
605 EmitReturnStmt(ret);
606 return;
607 }
608
609 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
610 QualType propType = prop->getType();
611 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
612
613 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
614
615 // Pick an implementation strategy.
616 PropertyImplStrategy strategy(CGM, propImpl);
617 switch (strategy.getKind()) {
618 case PropertyImplStrategy::Native: {
619 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
620
621 // Currently, all atomic accesses have to be through integer
622 // types, so there's no point in trying to pick a prettier type.
623 llvm::Type *bitcastType =
624 llvm::Type::getIntNTy(getLLVMContext(),
625 getContext().toBits(strategy.getIvarSize()));
626 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
627
628 // Perform an atomic load. This does not impose ordering constraints.
629 llvm::Value *ivarAddr = LV.getAddress();
630 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
631 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
632 load->setAlignment(strategy.getIvarAlignment().getQuantity());
633 load->setAtomic(llvm::Unordered);
634
635 // Store that value into the return address. Doing this with a
636 // bitcast is likely to produce some pretty ugly IR, but it's not
637 // the *most* terrible thing in the world.
638 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
639
640 // Make sure we don't do an autorelease.
641 AutoreleaseResult = false;
642 return;
643 }
644
645 case PropertyImplStrategy::GetSetProperty: {
646 llvm::Value *getPropertyFn =
647 CGM.getObjCRuntime().GetPropertyGetFunction();
648 if (!getPropertyFn) {
649 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000650 return;
651 }
652
653 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
654 // FIXME: Can't this be simpler? This might even be worse than the
655 // corresponding gcc code.
John McCall1e1f4872011-09-13 03:34:09 +0000656 llvm::Value *cmd =
657 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
658 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
659 llvm::Value *ivarOffset =
660 EmitIvarOffset(classImpl->getClassInterface(), ivar);
661
662 CallArgList args;
663 args.add(RValue::get(self), getContext().getObjCIdType());
664 args.add(RValue::get(cmd), getContext().getObjCSelType());
665 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
666
667 assert(strategy.isAtomic());
668 args.add(RValue::get(Builder.getTrue()), getContext().BoolTy);
669
Daniel Dunbare4be5a62009-02-03 23:43:59 +0000670 // FIXME: We shouldn't need to get the function info here, the
671 // runtime already should have computed it to build the function.
John McCall1e1f4872011-09-13 03:34:09 +0000672 RValue RV = EmitCall(getTypes().getFunctionInfo(propType, args,
John McCall41bdde92011-09-12 23:06:44 +0000673 FunctionType::ExtInfo()),
John McCall1e1f4872011-09-13 03:34:09 +0000674 getPropertyFn, ReturnValueSlot(), args);
675
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000676 // We need to fix the type here. Ivars with copy & retain are
677 // always objects so we don't need to worry about complex or
678 // aggregates.
Mike Stump1eb44332009-09-09 15:08:12 +0000679 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
John McCall1e1f4872011-09-13 03:34:09 +0000680 getTypes().ConvertType(propType)));
681
682 EmitReturnOfRValue(RV, propType);
John McCallf85e1932011-06-15 23:02:42 +0000683
684 // objc_getProperty does an autorelease, so we should suppress ours.
685 AutoreleaseResult = false;
John McCallf85e1932011-06-15 23:02:42 +0000686
John McCall1e1f4872011-09-13 03:34:09 +0000687 return;
688 }
689
690 case PropertyImplStrategy::CopyStruct:
691 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
692 strategy.hasStrongMember());
693 return;
694
695 case PropertyImplStrategy::Expression:
696 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
697 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
698
699 QualType ivarType = ivar->getType();
700 if (ivarType->isAnyComplexType()) {
701 ComplexPairTy pair = LoadComplexFromAddr(LV.getAddress(),
702 LV.isVolatileQualified());
703 StoreComplexToAddr(pair, ReturnValue, LV.isVolatileQualified());
704 } else if (hasAggregateLLVMType(ivarType)) {
705 // The return value slot is guaranteed to not be aliased, but
706 // that's not necessarily the same as "on the stack", so
707 // we still potentially need objc_memmove_collectable.
708 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
709 } else {
John McCallba3dd902011-07-22 05:23:13 +0000710 llvm::Value *value;
711 if (propType->isReferenceType()) {
712 value = LV.getAddress();
713 } else {
714 // We want to load and autoreleaseReturnValue ARC __weak ivars.
715 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall1e1f4872011-09-13 03:34:09 +0000716 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
John McCallba3dd902011-07-22 05:23:13 +0000717
718 // Otherwise we want to do a simple load, suppressing the
719 // final autorelease.
John McCallf85e1932011-06-15 23:02:42 +0000720 } else {
John McCallba3dd902011-07-22 05:23:13 +0000721 value = EmitLoadOfLValue(LV).getScalarVal();
722 AutoreleaseResult = false;
Fariborz Jahanian14086762011-03-28 23:47:18 +0000723 }
John McCallf85e1932011-06-15 23:02:42 +0000724
John McCallba3dd902011-07-22 05:23:13 +0000725 value = Builder.CreateBitCast(value, ConvertType(propType));
726 }
727
728 EmitReturnOfRValue(RValue::get(value), propType);
Fariborz Jahanianed1d29d2009-03-03 18:49:40 +0000729 }
John McCall1e1f4872011-09-13 03:34:09 +0000730 return;
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000731 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000732
John McCall1e1f4872011-09-13 03:34:09 +0000733 }
734 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000735}
736
John McCall41bdde92011-09-12 23:06:44 +0000737/// emitStructSetterCall - Call the runtime function to store the value
738/// from the first formal parameter into the given ivar.
739static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
740 ObjCIvarDecl *ivar) {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000741 // objc_copyStruct (&structIvar, &Arg,
742 // sizeof (struct something), true, false);
John McCallbbb253c2011-09-10 09:30:49 +0000743 CallArgList args;
744
745 // The first argument is the address of the ivar.
John McCall41bdde92011-09-12 23:06:44 +0000746 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
747 CGF.LoadObjCSelf(), ivar, 0)
748 .getAddress();
749 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
750 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000751
752 // The second argument is the address of the parameter variable.
John McCall41bdde92011-09-12 23:06:44 +0000753 ParmVarDecl *argVar = *OMD->param_begin();
754 DeclRefExpr argRef(argVar, argVar->getType(), VK_LValue, SourceLocation());
755 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
756 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
757 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000758
759 // The third argument is the sizeof the type.
760 llvm::Value *size =
John McCall41bdde92011-09-12 23:06:44 +0000761 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
762 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCallbbb253c2011-09-10 09:30:49 +0000763
John McCall41bdde92011-09-12 23:06:44 +0000764 // The fourth argument is the 'isAtomic' flag.
765 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCallbbb253c2011-09-10 09:30:49 +0000766
John McCall41bdde92011-09-12 23:06:44 +0000767 // The fifth argument is the 'hasStrong' flag.
768 // FIXME: should this really always be false?
769 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
770
771 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
772 CGF.EmitCall(CGF.getTypes().getFunctionInfo(CGF.getContext().VoidTy, args,
773 FunctionType::ExtInfo()),
774 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000775}
776
John McCall1e1f4872011-09-13 03:34:09 +0000777static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
778 Expr *setter = PID->getSetterCXXAssignment();
779 if (!setter) return true;
780
781 // Sema only makes only of these when the ivar has a C++ class type,
782 // so the form is pretty constrained.
John McCall71c758d2011-09-10 09:17:20 +0000783
784 // An operator call is trivial if the function it calls is trivial.
John McCall1e1f4872011-09-13 03:34:09 +0000785 // This also implies that there's nothing non-trivial going on with
786 // the arguments, because operator= can only be trivial if it's a
787 // synthesized assignment operator and therefore both parameters are
788 // references.
789 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall71c758d2011-09-10 09:17:20 +0000790 if (const FunctionDecl *callee
791 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
792 if (callee->isTrivial())
793 return true;
794 return false;
Fariborz Jahanian01cb3072011-04-06 16:05:26 +0000795 }
John McCall71c758d2011-09-10 09:17:20 +0000796
John McCall1e1f4872011-09-13 03:34:09 +0000797 assert(isa<ExprWithCleanups>(setter));
John McCall71c758d2011-09-10 09:17:20 +0000798 return false;
799}
800
John McCall71c758d2011-09-10 09:17:20 +0000801void
802CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
803 const ObjCPropertyImplDecl *propImpl) {
804 // Just use the setter expression if Sema gave us one and it's
805 // non-trivial. There's no way to do this atomically.
John McCall1e1f4872011-09-13 03:34:09 +0000806 if (!hasTrivialSetExpr(propImpl)) {
John McCall71c758d2011-09-10 09:17:20 +0000807 EmitStmt(propImpl->getSetterCXXAssignment());
808 return;
809 }
810
811 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
812 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
813 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
814
John McCall1e1f4872011-09-13 03:34:09 +0000815 PropertyImplStrategy strategy(CGM, propImpl);
816 switch (strategy.getKind()) {
817 case PropertyImplStrategy::Native: {
818 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
John McCall71c758d2011-09-10 09:17:20 +0000819
John McCall1e1f4872011-09-13 03:34:09 +0000820 LValue ivarLValue =
821 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
822 llvm::Value *ivarAddr = ivarLValue.getAddress();
John McCall71c758d2011-09-10 09:17:20 +0000823
John McCall1e1f4872011-09-13 03:34:09 +0000824 // Currently, all atomic accesses have to be through integer
825 // types, so there's no point in trying to pick a prettier type.
826 llvm::Type *bitcastType =
827 llvm::Type::getIntNTy(getLLVMContext(),
828 getContext().toBits(strategy.getIvarSize()));
829 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
830
831 // Cast both arguments to the chosen operation type.
832 argAddr = Builder.CreateBitCast(argAddr, bitcastType);
833 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
834
835 // This bitcast load is likely to cause some nasty IR.
836 llvm::Value *load = Builder.CreateLoad(argAddr);
837
838 // Perform an atomic store. There are no memory ordering requirements.
839 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
840 store->setAlignment(strategy.getIvarAlignment().getQuantity());
841 store->setAtomic(llvm::Unordered);
842 return;
843 }
844
845 case PropertyImplStrategy::GetSetProperty:
846 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
John McCall71c758d2011-09-10 09:17:20 +0000847 llvm::Value *setPropertyFn =
848 CGM.getObjCRuntime().GetPropertySetFunction();
849 if (!setPropertyFn) {
850 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
851 return;
852 }
853
854 // Emit objc_setProperty((id) self, _cmd, offset, arg,
855 // <is-atomic>, <is-copy>).
856 llvm::Value *cmd =
857 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
858 llvm::Value *self =
859 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
860 llvm::Value *ivarOffset =
861 EmitIvarOffset(classImpl->getClassInterface(), ivar);
862 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
863 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
864
865 CallArgList args;
866 args.add(RValue::get(self), getContext().getObjCIdType());
867 args.add(RValue::get(cmd), getContext().getObjCSelType());
868 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
869 args.add(RValue::get(arg), getContext().getObjCIdType());
John McCall1e1f4872011-09-13 03:34:09 +0000870 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
871 getContext().BoolTy);
872 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
873 getContext().BoolTy);
John McCall71c758d2011-09-10 09:17:20 +0000874 // FIXME: We shouldn't need to get the function info here, the runtime
875 // already should have computed it to build the function.
876 EmitCall(getTypes().getFunctionInfo(getContext().VoidTy, args,
877 FunctionType::ExtInfo()),
878 setPropertyFn, ReturnValueSlot(), args);
879 return;
880 }
881
John McCall1e1f4872011-09-13 03:34:09 +0000882 case PropertyImplStrategy::CopyStruct:
John McCall41bdde92011-09-12 23:06:44 +0000883 emitStructSetterCall(*this, setterMethod, ivar);
John McCall71c758d2011-09-10 09:17:20 +0000884 return;
John McCall1e1f4872011-09-13 03:34:09 +0000885
886 case PropertyImplStrategy::Expression:
887 break;
John McCall71c758d2011-09-10 09:17:20 +0000888 }
889
890 // Otherwise, fake up some ASTs and emit a normal assignment.
891 ValueDecl *selfDecl = setterMethod->getSelfDecl();
892 DeclRefExpr self(selfDecl, selfDecl->getType(), VK_LValue, SourceLocation());
893 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
894 selfDecl->getType(), CK_LValueToRValue, &self,
895 VK_RValue);
896 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
897 SourceLocation(), &selfLoad, true, true);
898
899 ParmVarDecl *argDecl = *setterMethod->param_begin();
900 QualType argType = argDecl->getType().getNonReferenceType();
901 DeclRefExpr arg(argDecl, argType, VK_LValue, SourceLocation());
902 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
903 argType.getUnqualifiedType(), CK_LValueToRValue,
904 &arg, VK_RValue);
905
906 // The property type can differ from the ivar type in some situations with
907 // Objective-C pointer types, we can always bit cast the RHS in these cases.
908 // The following absurdity is just to ensure well-formed IR.
909 CastKind argCK = CK_NoOp;
910 if (ivarRef.getType()->isObjCObjectPointerType()) {
911 if (argLoad.getType()->isObjCObjectPointerType())
912 argCK = CK_BitCast;
913 else if (argLoad.getType()->isBlockPointerType())
914 argCK = CK_BlockPointerToObjCPointerCast;
915 else
916 argCK = CK_CPointerToObjCPointerCast;
917 } else if (ivarRef.getType()->isBlockPointerType()) {
918 if (argLoad.getType()->isBlockPointerType())
919 argCK = CK_BitCast;
920 else
921 argCK = CK_AnyPointerToBlockPointerCast;
922 } else if (ivarRef.getType()->isPointerType()) {
923 argCK = CK_BitCast;
924 }
925 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
926 ivarRef.getType(), argCK, &argLoad,
927 VK_RValue);
928 Expr *finalArg = &argLoad;
929 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
930 argLoad.getType()))
931 finalArg = &argCast;
932
933
934 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
935 ivarRef.getType(), VK_RValue, OK_Ordinary,
936 SourceLocation());
937 EmitStmt(&assign);
Fariborz Jahanian01cb3072011-04-06 16:05:26 +0000938}
939
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000940/// GenerateObjCSetter - Generate an Objective-C property setter
Steve Naroff489034c2009-01-10 22:55:25 +0000941/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
942/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000943void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
944 const ObjCPropertyImplDecl *PID) {
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000945 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
946 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
947 assert(OMD && "Invalid call to generate setter (empty method)");
Devang Patel8d3f8972011-05-19 23:37:41 +0000948 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000949
John McCall71c758d2011-09-10 09:17:20 +0000950 generateObjCSetterBody(IMP, PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000951
952 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +0000953}
954
John McCalle81ac692011-03-22 07:05:39 +0000955namespace {
John McCall9928c482011-07-12 16:41:08 +0000956 struct DestroyIvar : EHScopeStack::Cleanup {
957 private:
958 llvm::Value *addr;
John McCalle81ac692011-03-22 07:05:39 +0000959 const ObjCIvarDecl *ivar;
John McCall9928c482011-07-12 16:41:08 +0000960 CodeGenFunction::Destroyer &destroyer;
961 bool useEHCleanupForArray;
962 public:
963 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
964 CodeGenFunction::Destroyer *destroyer,
965 bool useEHCleanupForArray)
966 : addr(addr), ivar(ivar), destroyer(*destroyer),
967 useEHCleanupForArray(useEHCleanupForArray) {}
John McCalle81ac692011-03-22 07:05:39 +0000968
John McCallad346f42011-07-12 20:27:29 +0000969 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +0000970 LValue lvalue
971 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
972 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +0000973 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCalle81ac692011-03-22 07:05:39 +0000974 }
975 };
976}
977
John McCall9928c482011-07-12 16:41:08 +0000978/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
979static void destroyARCStrongWithStore(CodeGenFunction &CGF,
980 llvm::Value *addr,
981 QualType type) {
982 llvm::Value *null = getNullForVariable(addr);
983 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
984}
John McCallf85e1932011-06-15 23:02:42 +0000985
John McCalle81ac692011-03-22 07:05:39 +0000986static void emitCXXDestructMethod(CodeGenFunction &CGF,
987 ObjCImplementationDecl *impl) {
988 CodeGenFunction::RunCleanupsScope scope(CGF);
989
990 llvm::Value *self = CGF.LoadObjCSelf();
991
Jordy Rosedb8264e2011-07-22 02:08:32 +0000992 const ObjCInterfaceDecl *iface = impl->getClassInterface();
993 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +0000994 ivar; ivar = ivar->getNextIvar()) {
995 QualType type = ivar->getType();
996
John McCalle81ac692011-03-22 07:05:39 +0000997 // Check whether the ivar is a destructible type.
John McCall9928c482011-07-12 16:41:08 +0000998 QualType::DestructionKind dtorKind = type.isDestructedType();
999 if (!dtorKind) continue;
John McCalle81ac692011-03-22 07:05:39 +00001000
John McCall9928c482011-07-12 16:41:08 +00001001 CodeGenFunction::Destroyer *destroyer = 0;
John McCalle81ac692011-03-22 07:05:39 +00001002
John McCall9928c482011-07-12 16:41:08 +00001003 // Use a call to objc_storeStrong to destroy strong ivars, for the
1004 // general benefit of the tools.
1005 if (dtorKind == QualType::DK_objc_strong_lifetime) {
1006 destroyer = &destroyARCStrongWithStore;
John McCallf85e1932011-06-15 23:02:42 +00001007
John McCall9928c482011-07-12 16:41:08 +00001008 // Otherwise use the default for the destruction kind.
1009 } else {
1010 destroyer = &CGF.getDestroyer(dtorKind);
John McCalle81ac692011-03-22 07:05:39 +00001011 }
John McCall9928c482011-07-12 16:41:08 +00001012
1013 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1014
1015 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1016 cleanupKind & EHCleanup);
John McCalle81ac692011-03-22 07:05:39 +00001017 }
1018
1019 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1020}
1021
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001022void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1023 ObjCMethodDecl *MD,
1024 bool ctor) {
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001025 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Devang Patel8d3f8972011-05-19 23:37:41 +00001026 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
John McCalle81ac692011-03-22 07:05:39 +00001027
1028 // Emit .cxx_construct.
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001029 if (ctor) {
John McCallf85e1932011-06-15 23:02:42 +00001030 // Suppress the final autorelease in ARC.
1031 AutoreleaseResult = false;
1032
Chris Lattner5f9e2722011-07-23 10:55:15 +00001033 SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
John McCalle81ac692011-03-22 07:05:39 +00001034 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
1035 E = IMP->init_end(); B != E; ++B) {
1036 CXXCtorInitializer *IvarInit = (*B);
Francois Pichet00eb3f92010-12-04 09:14:42 +00001037 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001038 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian9b4d4fc2010-04-28 22:30:33 +00001039 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1040 LoadObjCSelf(), Ivar, 0);
John McCall7c2349b2011-08-25 20:40:09 +00001041 EmitAggExpr(IvarInit->getInit(),
1042 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001043 AggValueSlot::DoesNotNeedGCBarriers,
1044 AggValueSlot::IsNotAliased));
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001045 }
1046 // constructor returns 'self'.
1047 CodeGenTypes &Types = CGM.getTypes();
1048 QualType IdTy(CGM.getContext().getObjCIdType());
1049 llvm::Value *SelfAsId =
1050 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1051 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCalle81ac692011-03-22 07:05:39 +00001052
1053 // Emit .cxx_destruct.
Chandler Carruthbc397cf2010-05-06 00:20:39 +00001054 } else {
John McCalle81ac692011-03-22 07:05:39 +00001055 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001056 }
1057 FinishFunction();
1058}
1059
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +00001060bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1061 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1062 it++; it++;
1063 const ABIArgInfo &AI = it->info;
1064 // FIXME. Is this sufficient check?
1065 return (AI.getKind() == ABIArgInfo::Indirect);
1066}
1067
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001068bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
1069 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
1070 return false;
1071 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1072 return FDTTy->getDecl()->hasObjectMember();
1073 return false;
1074}
1075
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001076llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001077 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1078 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner41110242008-06-17 18:05:57 +00001079}
1080
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001081QualType CodeGenFunction::TypeOfSelfObject() {
1082 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1083 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff14108da2009-07-10 23:34:53 +00001084 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1085 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001086 return PTy->getPointeeType();
1087}
1088
John McCalle68b9842010-12-04 03:11:00 +00001089LValue
1090CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
1091 // This is a special l-value that just issues sends when we load or
1092 // store through it.
1093
1094 // For certain base kinds, we need to emit the base immediately.
1095 llvm::Value *Base;
1096 if (E->isSuperReceiver())
1097 Base = LoadObjCSelf();
1098 else if (E->isClassReceiver())
1099 Base = CGM.getObjCRuntime().GetClass(Builder, E->getClassReceiver());
1100 else
1101 Base = EmitScalarExpr(E->getBase());
1102 return LValue::MakePropertyRef(E, Base);
1103}
1104
1105static RValue GenerateMessageSendSuper(CodeGenFunction &CGF,
1106 ReturnValueSlot Return,
1107 QualType ResultType,
1108 Selector S,
1109 llvm::Value *Receiver,
1110 const CallArgList &CallArgs) {
1111 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CGF.CurFuncDecl);
Fariborz Jahanianf4695572009-03-20 19:18:21 +00001112 bool isClassMessage = OMD->isClassMethod();
1113 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
John McCalle68b9842010-12-04 03:11:00 +00001114 return CGF.CGM.getObjCRuntime()
1115 .GenerateMessageSendSuper(CGF, Return, ResultType,
1116 S, OMD->getClassInterface(),
1117 isCategoryImpl, Receiver,
1118 isClassMessage, CallArgs);
Fariborz Jahanianf4695572009-03-20 19:18:21 +00001119}
1120
John McCall119a1c62010-12-04 02:32:38 +00001121RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
1122 ReturnValueSlot Return) {
1123 const ObjCPropertyRefExpr *E = LV.getPropertyRefExpr();
Fariborz Jahanian68af13f2011-03-30 16:11:20 +00001124 QualType ResultType = E->getGetterResultType();
John McCall12f78a62010-12-02 01:19:52 +00001125 Selector S;
Douglas Gregor926df6c2011-06-11 01:09:30 +00001126 const ObjCMethodDecl *method;
John McCall12f78a62010-12-02 01:19:52 +00001127 if (E->isExplicitProperty()) {
1128 const ObjCPropertyDecl *Property = E->getExplicitProperty();
1129 S = Property->getGetterName();
Douglas Gregor926df6c2011-06-11 01:09:30 +00001130 method = Property->getGetterMethodDecl();
Mike Stumpb3589f42009-07-30 22:28:39 +00001131 } else {
Douglas Gregor926df6c2011-06-11 01:09:30 +00001132 method = E->getImplicitPropertyGetter();
1133 S = method->getSelector();
Fariborz Jahanian43f44702008-11-22 22:30:21 +00001134 }
John McCall12f78a62010-12-02 01:19:52 +00001135
John McCall119a1c62010-12-04 02:32:38 +00001136 llvm::Value *Receiver = LV.getPropertyRefBaseAddr();
John McCalle68b9842010-12-04 03:11:00 +00001137
John McCallf85e1932011-06-15 23:02:42 +00001138 if (CGM.getLangOptions().ObjCAutoRefCount) {
1139 QualType receiverType;
1140 if (E->isSuperReceiver())
1141 receiverType = E->getSuperReceiverType();
1142 else if (E->isClassReceiver())
1143 receiverType = getContext().getObjCClassType();
1144 else
1145 receiverType = E->getBase()->getType();
1146 }
1147
John McCalle68b9842010-12-04 03:11:00 +00001148 // Accesses to 'super' follow a different code path.
1149 if (E->isSuperReceiver())
Douglas Gregor926df6c2011-06-11 01:09:30 +00001150 return AdjustRelatedResultType(*this, E, method,
1151 GenerateMessageSendSuper(*this, Return,
1152 ResultType,
1153 S, Receiver,
1154 CallArgList()));
John McCall119a1c62010-12-04 02:32:38 +00001155 const ObjCInterfaceDecl *ReceiverClass
1156 = (E->isClassReceiver() ? E->getClassReceiver() : 0);
Douglas Gregor926df6c2011-06-11 01:09:30 +00001157 return AdjustRelatedResultType(*this, E, method,
John McCallf85e1932011-06-15 23:02:42 +00001158 CGM.getObjCRuntime().
1159 GenerateMessageSend(*this, Return, ResultType, S,
1160 Receiver, CallArgList(), ReceiverClass));
Daniel Dunbar9c3fc702008-08-27 06:57:25 +00001161}
1162
John McCall119a1c62010-12-04 02:32:38 +00001163void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
1164 LValue Dst) {
1165 const ObjCPropertyRefExpr *E = Dst.getPropertyRefExpr();
John McCall12f78a62010-12-02 01:19:52 +00001166 Selector S = E->getSetterSelector();
Fariborz Jahanian68af13f2011-03-30 16:11:20 +00001167 QualType ArgType = E->getSetterArgType();
1168
Fariborz Jahanianb19c76e2011-02-08 22:33:23 +00001169 // FIXME. Other than scalars, AST is not adequate for setter and
1170 // getter type mismatches which require conversion.
1171 if (Src.isScalar()) {
1172 llvm::Value *SrcVal = Src.getScalarVal();
1173 QualType DstType = getContext().getCanonicalType(ArgType);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001174 llvm::Type *DstTy = ConvertType(DstType);
Fariborz Jahanianb19c76e2011-02-08 22:33:23 +00001175 if (SrcVal->getType() != DstTy)
1176 Src =
1177 RValue::get(EmitScalarConversion(SrcVal, E->getType(), DstType));
1178 }
1179
John McCalle68b9842010-12-04 03:11:00 +00001180 CallArgList Args;
Eli Friedman04c9a492011-05-02 17:57:46 +00001181 Args.add(Src, ArgType);
John McCalle68b9842010-12-04 03:11:00 +00001182
1183 llvm::Value *Receiver = Dst.getPropertyRefBaseAddr();
1184 QualType ResultType = getContext().VoidTy;
1185
John McCall12f78a62010-12-02 01:19:52 +00001186 if (E->isSuperReceiver()) {
John McCalle68b9842010-12-04 03:11:00 +00001187 GenerateMessageSendSuper(*this, ReturnValueSlot(),
1188 ResultType, S, Receiver, Args);
John McCall12f78a62010-12-02 01:19:52 +00001189 return;
1190 }
1191
John McCall119a1c62010-12-04 02:32:38 +00001192 const ObjCInterfaceDecl *ReceiverClass
1193 = (E->isClassReceiver() ? E->getClassReceiver() : 0);
John McCall12f78a62010-12-02 01:19:52 +00001194
John McCall12f78a62010-12-02 01:19:52 +00001195 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
John McCalle68b9842010-12-04 03:11:00 +00001196 ResultType, S, Receiver, Args,
1197 ReceiverClass);
Daniel Dunbar85c59ed2008-08-29 08:11:39 +00001198}
1199
Chris Lattner74391b42009-03-22 21:03:39 +00001200void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump1eb44332009-09-09 15:08:12 +00001201 llvm::Constant *EnumerationMutationFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001202 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001204 if (!EnumerationMutationFn) {
1205 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1206 return;
1207 }
1208
Devang Patelbcbd03a2011-01-19 01:36:36 +00001209 CGDebugInfo *DI = getDebugInfo();
1210 if (DI) {
1211 DI->setLocation(S.getSourceRange().getBegin());
1212 DI->EmitRegionStart(Builder);
1213 }
1214
Devang Patel9d99f2d2011-06-13 23:15:32 +00001215 // The local variable comes into scope immediately.
1216 AutoVarEmission variable = AutoVarEmission::invalid();
1217 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1218 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1219
John McCalld88687f2011-01-07 01:49:06 +00001220 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump1eb44332009-09-09 15:08:12 +00001221
Anders Carlssonf484c312008-08-31 02:33:12 +00001222 // Fast enumeration state.
Douglas Gregor0815b572011-08-09 17:23:49 +00001223 QualType StateTy = CGM.getObjCFastEnumerationStateType();
Daniel Dunbar195337d2010-02-09 02:48:28 +00001224 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlsson1884eb02010-05-22 17:35:42 +00001225 EmitNullInitialization(StatePtr, StateTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001226
Anders Carlssonf484c312008-08-31 02:33:12 +00001227 // Number of elements in the items array.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001228 static const unsigned NumItems = 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001229
John McCalld88687f2011-01-07 01:49:06 +00001230 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramerad468862010-03-30 11:36:44 +00001231 IdentifierInfo *II[] = {
1232 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1233 &CGM.getContext().Idents.get("objects"),
1234 &CGM.getContext().Idents.get("count")
1235 };
1236 Selector FastEnumSel =
1237 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlssonf484c312008-08-31 02:33:12 +00001238
1239 QualType ItemsTy =
1240 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +00001241 llvm::APInt(32, NumItems),
Anders Carlssonf484c312008-08-31 02:33:12 +00001242 ArrayType::Normal, 0);
Daniel Dunbar195337d2010-02-09 02:48:28 +00001243 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001244
John McCall990567c2011-07-27 01:07:15 +00001245 // Emit the collection pointer. In ARC, we do a retain.
1246 llvm::Value *Collection;
1247 if (getLangOptions().ObjCAutoRefCount) {
1248 Collection = EmitARCRetainScalarExpr(S.getCollection());
1249
1250 // Enter a cleanup to do the release.
1251 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1252 } else {
1253 Collection = EmitScalarExpr(S.getCollection());
1254 }
Mike Stump1eb44332009-09-09 15:08:12 +00001255
John McCall4b302d32011-08-05 00:14:38 +00001256 // The 'continue' label needs to appear within the cleanup for the
1257 // collection object.
1258 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1259
John McCalld88687f2011-01-07 01:49:06 +00001260 // Send it our message:
Anders Carlssonf484c312008-08-31 02:33:12 +00001261 CallArgList Args;
John McCalld88687f2011-01-07 01:49:06 +00001262
1263 // The first argument is a temporary of the enumeration-state type.
Eli Friedman04c9a492011-05-02 17:57:46 +00001264 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001265
John McCalld88687f2011-01-07 01:49:06 +00001266 // The second argument is a temporary array with space for NumItems
1267 // pointers. We'll actually be loading elements from the array
1268 // pointer written into the control state; this buffer is so that
1269 // collections that *aren't* backed by arrays can still queue up
1270 // batches of elements.
Eli Friedman04c9a492011-05-02 17:57:46 +00001271 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001272
John McCalld88687f2011-01-07 01:49:06 +00001273 // The third argument is the capacity of that temporary array.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001274 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001275 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman04c9a492011-05-02 17:57:46 +00001276 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001277
John McCalld88687f2011-01-07 01:49:06 +00001278 // Start the enumeration.
Mike Stump1eb44332009-09-09 15:08:12 +00001279 RValue CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001280 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001281 getContext().UnsignedLongTy,
1282 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001283 Collection, Args);
Anders Carlssonf484c312008-08-31 02:33:12 +00001284
John McCalld88687f2011-01-07 01:49:06 +00001285 // The initial number of objects that were returned in the buffer.
1286 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump1eb44332009-09-09 15:08:12 +00001287
John McCalld88687f2011-01-07 01:49:06 +00001288 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1289 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump1eb44332009-09-09 15:08:12 +00001290
John McCalld88687f2011-01-07 01:49:06 +00001291 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlssonf484c312008-08-31 02:33:12 +00001292
John McCalld88687f2011-01-07 01:49:06 +00001293 // If the limit pointer was zero to begin with, the collection is
1294 // empty; skip all this.
1295 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1296 EmptyBB, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001297
John McCalld88687f2011-01-07 01:49:06 +00001298 // Otherwise, initialize the loop.
1299 EmitBlock(LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001300
John McCalld88687f2011-01-07 01:49:06 +00001301 // Save the initial mutations value. This is the value at an
1302 // address that was written into the state object by
1303 // countByEnumeratingWithState:objects:count:.
Mike Stump1eb44332009-09-09 15:08:12 +00001304 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001305 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001306 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001307 "mutationsptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001308
John McCalld88687f2011-01-07 01:49:06 +00001309 llvm::Value *initialMutations =
1310 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump1eb44332009-09-09 15:08:12 +00001311
John McCalld88687f2011-01-07 01:49:06 +00001312 // Start looping. This is the point we return to whenever we have a
1313 // fresh, non-empty batch of objects.
1314 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1315 EmitBlock(LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001316
John McCalld88687f2011-01-07 01:49:06 +00001317 // The current index into the buffer.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001318 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCalld88687f2011-01-07 01:49:06 +00001319 index->addIncoming(zero, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001320
John McCalld88687f2011-01-07 01:49:06 +00001321 // The current buffer size.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001322 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCalld88687f2011-01-07 01:49:06 +00001323 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001324
John McCalld88687f2011-01-07 01:49:06 +00001325 // Check whether the mutations value has changed from where it was
1326 // at start. StateMutationsPtr should actually be invariant between
1327 // refreshes.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001328 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCalld88687f2011-01-07 01:49:06 +00001329 llvm::Value *currentMutations
1330 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001331
John McCalld88687f2011-01-07 01:49:06 +00001332 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman361cf982011-03-02 22:39:34 +00001333 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump1eb44332009-09-09 15:08:12 +00001334
John McCalld88687f2011-01-07 01:49:06 +00001335 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1336 WasNotMutatedBB, WasMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001337
John McCalld88687f2011-01-07 01:49:06 +00001338 // If so, call the enumeration-mutation function.
1339 EmitBlock(WasMutatedBB);
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001340 llvm::Value *V =
Mike Stump1eb44332009-09-09 15:08:12 +00001341 Builder.CreateBitCast(Collection,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001342 ConvertType(getContext().getObjCIdType()),
1343 "tmp");
Daniel Dunbar2b2105e2009-02-03 23:55:40 +00001344 CallArgList Args2;
Eli Friedman04c9a492011-05-02 17:57:46 +00001345 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stumpf5408fe2009-05-16 07:57:57 +00001346 // FIXME: We shouldn't need to get the function info here, the runtime already
1347 // should have computed it to build the function.
John McCall04a67a62010-02-05 21:31:56 +00001348 EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2,
Rafael Espindola264ba482010-03-30 20:24:48 +00001349 FunctionType::ExtInfo()),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001350 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump1eb44332009-09-09 15:08:12 +00001351
John McCalld88687f2011-01-07 01:49:06 +00001352 // Otherwise, or if the mutation function returns, just continue.
1353 EmitBlock(WasNotMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001354
John McCalld88687f2011-01-07 01:49:06 +00001355 // Initialize the element variable.
1356 RunCleanupsScope elementVariableScope(*this);
John McCall57b3b6a2011-02-22 07:16:58 +00001357 bool elementIsVariable;
John McCalld88687f2011-01-07 01:49:06 +00001358 LValue elementLValue;
1359 QualType elementType;
1360 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall57b3b6a2011-02-22 07:16:58 +00001361 // Initialize the variable, in case it's a __block variable or something.
1362 EmitAutoVarInit(variable);
John McCalld88687f2011-01-07 01:49:06 +00001363
John McCall57b3b6a2011-02-22 07:16:58 +00001364 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCalld88687f2011-01-07 01:49:06 +00001365 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), D->getType(),
1366 VK_LValue, SourceLocation());
1367 elementLValue = EmitLValue(&tempDRE);
1368 elementType = D->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001369 elementIsVariable = true;
John McCall7acddac2011-06-17 06:42:21 +00001370
1371 if (D->isARCPseudoStrong())
1372 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCalld88687f2011-01-07 01:49:06 +00001373 } else {
1374 elementLValue = LValue(); // suppress warning
1375 elementType = cast<Expr>(S.getElement())->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001376 elementIsVariable = false;
John McCalld88687f2011-01-07 01:49:06 +00001377 }
Chris Lattner2acc6e32011-07-18 04:24:23 +00001378 llvm::Type *convertedElementType = ConvertType(elementType);
John McCalld88687f2011-01-07 01:49:06 +00001379
1380 // Fetch the buffer out of the enumeration state.
1381 // TODO: this pointer should actually be invariant between
1382 // refreshes, which would help us do certain loop optimizations.
Mike Stump1eb44332009-09-09 15:08:12 +00001383 llvm::Value *StateItemsPtr =
Anders Carlssonf484c312008-08-31 02:33:12 +00001384 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCalld88687f2011-01-07 01:49:06 +00001385 llvm::Value *EnumStateItems =
1386 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlssonf484c312008-08-31 02:33:12 +00001387
John McCalld88687f2011-01-07 01:49:06 +00001388 // Fetch the value at the current index from the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001389 llvm::Value *CurrentItemPtr =
John McCalld88687f2011-01-07 01:49:06 +00001390 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1391 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001392
John McCalld88687f2011-01-07 01:49:06 +00001393 // Cast that value to the right type.
1394 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1395 "currentitem");
Mike Stump1eb44332009-09-09 15:08:12 +00001396
John McCalld88687f2011-01-07 01:49:06 +00001397 // Make sure we have an l-value. Yes, this gets evaluated every
1398 // time through the loop.
John McCall7acddac2011-06-17 06:42:21 +00001399 if (!elementIsVariable) {
John McCalld88687f2011-01-07 01:49:06 +00001400 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001401 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCall7acddac2011-06-17 06:42:21 +00001402 } else {
1403 EmitScalarInit(CurrentItem, elementLValue);
1404 }
Mike Stump1eb44332009-09-09 15:08:12 +00001405
John McCall57b3b6a2011-02-22 07:16:58 +00001406 // If we do have an element variable, this assignment is the end of
1407 // its initialization.
1408 if (elementIsVariable)
1409 EmitAutoVarCleanups(variable);
1410
John McCalld88687f2011-01-07 01:49:06 +00001411 // Perform the loop body, setting up break and continue labels.
Anders Carlssone4b6d342009-02-10 05:52:02 +00001412 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCalld88687f2011-01-07 01:49:06 +00001413 {
1414 RunCleanupsScope Scope(*this);
1415 EmitStmt(S.getBody());
1416 }
Anders Carlssonf484c312008-08-31 02:33:12 +00001417 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001418
John McCalld88687f2011-01-07 01:49:06 +00001419 // Destroy the element variable now.
1420 elementVariableScope.ForceCleanup();
1421
1422 // Check whether there are more elements.
John McCallff8e1152010-07-23 21:56:41 +00001423 EmitBlock(AfterBody.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001424
John McCalld88687f2011-01-07 01:49:06 +00001425 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanianf0906c42009-01-06 18:56:31 +00001426
John McCalld88687f2011-01-07 01:49:06 +00001427 // First we check in the local buffer.
1428 llvm::Value *indexPlusOne
1429 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlssonf484c312008-08-31 02:33:12 +00001430
John McCalld88687f2011-01-07 01:49:06 +00001431 // If we haven't overrun the buffer yet, we can continue.
1432 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1433 LoopBodyBB, FetchMoreBB);
1434
1435 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1436 count->addIncoming(count, AfterBody.getBlock());
1437
1438 // Otherwise, we have to fetch more elements.
1439 EmitBlock(FetchMoreBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001440
1441 CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001442 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001443 getContext().UnsignedLongTy,
Mike Stump1eb44332009-09-09 15:08:12 +00001444 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001445 Collection, Args);
Mike Stump1eb44332009-09-09 15:08:12 +00001446
John McCalld88687f2011-01-07 01:49:06 +00001447 // If we got a zero count, we're done.
1448 llvm::Value *refetchCount = CountRV.getScalarVal();
1449
1450 // (note that the message send might split FetchMoreBB)
1451 index->addIncoming(zero, Builder.GetInsertBlock());
1452 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1453
1454 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1455 EmptyBB, LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001456
Anders Carlssonf484c312008-08-31 02:33:12 +00001457 // No more elements.
John McCalld88687f2011-01-07 01:49:06 +00001458 EmitBlock(EmptyBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001459
John McCall57b3b6a2011-02-22 07:16:58 +00001460 if (!elementIsVariable) {
Anders Carlssonf484c312008-08-31 02:33:12 +00001461 // If the element was not a declaration, set it to be null.
1462
John McCalld88687f2011-01-07 01:49:06 +00001463 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1464 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001465 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlssonf484c312008-08-31 02:33:12 +00001466 }
1467
Devang Patelbcbd03a2011-01-19 01:36:36 +00001468 if (DI) {
1469 DI->setLocation(S.getSourceRange().getEnd());
1470 DI->EmitRegionEnd(Builder);
1471 }
1472
John McCall990567c2011-07-27 01:07:15 +00001473 // Leave the cleanup we entered in ARC.
1474 if (getLangOptions().ObjCAutoRefCount)
1475 PopCleanupBlock();
1476
John McCallff8e1152010-07-23 21:56:41 +00001477 EmitBlock(LoopEnd.getBlock());
Anders Carlsson3d8400d2008-08-30 19:51:14 +00001478}
1479
Mike Stump1eb44332009-09-09 15:08:12 +00001480void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001481 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001482}
1483
Mike Stump1eb44332009-09-09 15:08:12 +00001484void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001485 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1486}
1487
Chris Lattner10cac6f2008-11-15 21:26:17 +00001488void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump1eb44332009-09-09 15:08:12 +00001489 const ObjCAtSynchronizedStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001490 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +00001491}
1492
John McCall33e56f32011-09-10 06:18:15 +00001493/// Produce the code for a CK_ARCProduceObject. Just does a
John McCallf85e1932011-06-15 23:02:42 +00001494/// primitive retain.
1495llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1496 llvm::Value *value) {
1497 return EmitARCRetain(type, value);
1498}
1499
1500namespace {
1501 struct CallObjCRelease : EHScopeStack::Cleanup {
John McCallbddfd872011-08-03 22:24:24 +00001502 CallObjCRelease(llvm::Value *object) : object(object) {}
1503 llvm::Value *object;
John McCallf85e1932011-06-15 23:02:42 +00001504
John McCallad346f42011-07-12 20:27:29 +00001505 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001506 CGF.EmitARCRelease(object, /*precise*/ true);
John McCallf85e1932011-06-15 23:02:42 +00001507 }
1508 };
1509}
1510
John McCall33e56f32011-09-10 06:18:15 +00001511/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCallf85e1932011-06-15 23:02:42 +00001512/// release at the end of the full-expression.
1513llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1514 llvm::Value *object) {
1515 // If we're in a conditional branch, we need to make the cleanup
John McCallbddfd872011-08-03 22:24:24 +00001516 // conditional.
1517 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCallf85e1932011-06-15 23:02:42 +00001518 return object;
1519}
1520
1521llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1522 llvm::Value *value) {
1523 return EmitARCRetainAutorelease(type, value);
1524}
1525
1526
1527static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001528 llvm::FunctionType *type,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001529 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001530 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1531
1532 // In -fobjc-no-arc-runtime, emit weak references to the runtime
1533 // support library.
John McCall9f084a32011-07-06 00:26:06 +00001534 if (!CGM.getCodeGenOpts().ObjCRuntimeHasARC)
John McCallf85e1932011-06-15 23:02:42 +00001535 if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
1536 f->setLinkage(llvm::Function::ExternalWeakLinkage);
1537
1538 return fn;
1539}
1540
1541/// Perform an operation having the signature
1542/// i8* (i8*)
1543/// where a null input causes a no-op and returns null.
1544static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1545 llvm::Value *value,
1546 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001547 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001548 if (isa<llvm::ConstantPointerNull>(value)) return value;
1549
1550 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001551 std::vector<llvm::Type*> args(1, CGF.Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001552 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001553 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1554 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1555 }
1556
1557 // Cast the argument to 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001558 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001559 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1560
1561 // Call the function.
1562 llvm::CallInst *call = CGF.Builder.CreateCall(fn, value);
1563 call->setDoesNotThrow();
1564
1565 // Cast the result back to the original type.
1566 return CGF.Builder.CreateBitCast(call, origType);
1567}
1568
1569/// Perform an operation having the following signature:
1570/// i8* (i8**)
1571static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1572 llvm::Value *addr,
1573 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001574 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001575 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001576 std::vector<llvm::Type*> args(1, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001577 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001578 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1579 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1580 }
1581
1582 // Cast the argument to 'id*'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001583 llvm::Type *origType = addr->getType();
John McCallf85e1932011-06-15 23:02:42 +00001584 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1585
1586 // Call the function.
1587 llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr);
1588 call->setDoesNotThrow();
1589
1590 // Cast the result back to a dereference of the original type.
1591 llvm::Value *result = call;
1592 if (origType != CGF.Int8PtrPtrTy)
1593 result = CGF.Builder.CreateBitCast(result,
1594 cast<llvm::PointerType>(origType)->getElementType());
1595
1596 return result;
1597}
1598
1599/// Perform an operation having the following signature:
1600/// i8* (i8**, i8*)
1601static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1602 llvm::Value *addr,
1603 llvm::Value *value,
1604 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001605 StringRef fnName,
John McCallf85e1932011-06-15 23:02:42 +00001606 bool ignored) {
1607 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1608 == value->getType());
1609
1610 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001611 std::vector<llvm::Type*> argTypes(2);
John McCallf85e1932011-06-15 23:02:42 +00001612 argTypes[0] = CGF.Int8PtrPtrTy;
1613 argTypes[1] = CGF.Int8PtrTy;
1614
Chris Lattner2acc6e32011-07-18 04:24:23 +00001615 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001616 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1617 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1618 }
1619
Chris Lattner2acc6e32011-07-18 04:24:23 +00001620 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001621
1622 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1623 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1624
1625 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value);
1626 result->setDoesNotThrow();
1627
1628 if (ignored) return 0;
1629
1630 return CGF.Builder.CreateBitCast(result, origType);
1631}
1632
1633/// Perform an operation having the following signature:
1634/// void (i8**, i8**)
1635static void emitARCCopyOperation(CodeGenFunction &CGF,
1636 llvm::Value *dst,
1637 llvm::Value *src,
1638 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001639 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001640 assert(dst->getType() == src->getType());
1641
1642 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001643 std::vector<llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001644 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001645 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1646 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1647 }
1648
1649 dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy);
1650 src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy);
1651
1652 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src);
1653 result->setDoesNotThrow();
1654}
1655
1656/// Produce the code to do a retain. Based on the type, calls one of:
1657/// call i8* @objc_retain(i8* %value)
1658/// call i8* @objc_retainBlock(i8* %value)
1659llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1660 if (type->isBlockPointerType())
1661 return EmitARCRetainBlock(value);
1662 else
1663 return EmitARCRetainNonBlock(value);
1664}
1665
1666/// Retain the given object, with normal retain semantics.
1667/// call i8* @objc_retain(i8* %value)
1668llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1669 return emitARCValueOperation(*this, value,
1670 CGM.getARCEntrypoints().objc_retain,
1671 "objc_retain");
1672}
1673
1674/// Retain the given block, with _Block_copy semantics.
1675/// call i8* @objc_retainBlock(i8* %value)
1676llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value) {
1677 return emitARCValueOperation(*this, value,
1678 CGM.getARCEntrypoints().objc_retainBlock,
1679 "objc_retainBlock");
1680}
1681
1682/// Retain the given object which is the result of a function call.
1683/// call i8* @objc_retainAutoreleasedReturnValue(i8* %value)
1684///
1685/// Yes, this function name is one character away from a different
1686/// call with completely different semantics.
1687llvm::Value *
1688CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1689 // Fetch the void(void) inline asm which marks that we're going to
1690 // retain the autoreleased return value.
1691 llvm::InlineAsm *&marker
1692 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1693 if (!marker) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001694 StringRef assembly
John McCallf85e1932011-06-15 23:02:42 +00001695 = CGM.getTargetCodeGenInfo()
1696 .getARCRetainAutoreleasedReturnValueMarker();
1697
1698 // If we have an empty assembly string, there's nothing to do.
1699 if (assembly.empty()) {
1700
1701 // Otherwise, at -O0, build an inline asm that we're going to call
1702 // in a moment.
1703 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1704 llvm::FunctionType *type =
1705 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
1706 /*variadic*/ false);
1707
1708 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1709
1710 // If we're at -O1 and above, we don't want to litter the code
1711 // with this marker yet, so leave a breadcrumb for the ARC
1712 // optimizer to pick up.
1713 } else {
1714 llvm::NamedMDNode *metadata =
1715 CGM.getModule().getOrInsertNamedMetadata(
1716 "clang.arc.retainAutoreleasedReturnValueMarker");
1717 assert(metadata->getNumOperands() <= 1);
1718 if (metadata->getNumOperands() == 0) {
1719 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
Jay Foadda549e82011-07-29 13:56:53 +00001720 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
John McCallf85e1932011-06-15 23:02:42 +00001721 }
1722 }
1723 }
1724
1725 // Call the marker asm if we made one, which we do only at -O0.
1726 if (marker) Builder.CreateCall(marker);
1727
1728 return emitARCValueOperation(*this, value,
1729 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1730 "objc_retainAutoreleasedReturnValue");
1731}
1732
1733/// Release the given object.
1734/// call void @objc_release(i8* %value)
1735void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) {
1736 if (isa<llvm::ConstantPointerNull>(value)) return;
1737
1738 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1739 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001740 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001741 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001742 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1743 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1744 }
1745
1746 // Cast the argument to 'id'.
1747 value = Builder.CreateBitCast(value, Int8PtrTy);
1748
1749 // Call objc_release.
1750 llvm::CallInst *call = Builder.CreateCall(fn, value);
1751 call->setDoesNotThrow();
1752
1753 if (!precise) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001754 SmallVector<llvm::Value*,1> args;
John McCallf85e1932011-06-15 23:02:42 +00001755 call->setMetadata("clang.imprecise_release",
1756 llvm::MDNode::get(Builder.getContext(), args));
1757 }
1758}
1759
1760/// Store into a strong object. Always calls this:
1761/// call void @objc_storeStrong(i8** %addr, i8* %value)
1762llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
1763 llvm::Value *value,
1764 bool ignored) {
1765 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1766 == value->getType());
1767
1768 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
1769 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001770 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2acc6e32011-07-18 04:24:23 +00001771 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001772 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
1773 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
1774 }
1775
1776 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1777 llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy);
1778
1779 Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow();
1780
1781 if (ignored) return 0;
1782 return value;
1783}
1784
1785/// Store into a strong object. Sometimes calls this:
1786/// call void @objc_storeStrong(i8** %addr, i8* %value)
1787/// Other times, breaks it down into components.
John McCall545d9962011-06-25 02:11:03 +00001788llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCallf85e1932011-06-15 23:02:42 +00001789 llvm::Value *newValue,
1790 bool ignored) {
John McCall545d9962011-06-25 02:11:03 +00001791 QualType type = dst.getType();
John McCallf85e1932011-06-15 23:02:42 +00001792 bool isBlock = type->isBlockPointerType();
1793
1794 // Use a store barrier at -O0 unless this is a block type or the
1795 // lvalue is inadequately aligned.
1796 if (shouldUseFusedARCCalls() &&
1797 !isBlock &&
1798 !(dst.getAlignment() && dst.getAlignment() < PointerAlignInBytes)) {
1799 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
1800 }
1801
1802 // Otherwise, split it out.
1803
1804 // Retain the new value.
1805 newValue = EmitARCRetain(type, newValue);
1806
1807 // Read the old value.
John McCall545d9962011-06-25 02:11:03 +00001808 llvm::Value *oldValue = EmitLoadOfScalar(dst);
John McCallf85e1932011-06-15 23:02:42 +00001809
1810 // Store. We do this before the release so that any deallocs won't
1811 // see the old value.
John McCall545d9962011-06-25 02:11:03 +00001812 EmitStoreOfScalar(newValue, dst);
John McCallf85e1932011-06-15 23:02:42 +00001813
1814 // Finally, release the old value.
1815 EmitARCRelease(oldValue, /*precise*/ false);
1816
1817 return newValue;
1818}
1819
1820/// Autorelease the given object.
1821/// call i8* @objc_autorelease(i8* %value)
1822llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
1823 return emitARCValueOperation(*this, value,
1824 CGM.getARCEntrypoints().objc_autorelease,
1825 "objc_autorelease");
1826}
1827
1828/// Autorelease the given object.
1829/// call i8* @objc_autoreleaseReturnValue(i8* %value)
1830llvm::Value *
1831CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
1832 return emitARCValueOperation(*this, value,
1833 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
1834 "objc_autoreleaseReturnValue");
1835}
1836
1837/// Do a fused retain/autorelease of the given object.
1838/// call i8* @objc_retainAutoreleaseReturnValue(i8* %value)
1839llvm::Value *
1840CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
1841 return emitARCValueOperation(*this, value,
1842 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
1843 "objc_retainAutoreleaseReturnValue");
1844}
1845
1846/// Do a fused retain/autorelease of the given object.
1847/// call i8* @objc_retainAutorelease(i8* %value)
1848/// or
1849/// %retain = call i8* @objc_retainBlock(i8* %value)
1850/// call i8* @objc_autorelease(i8* %retain)
1851llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
1852 llvm::Value *value) {
1853 if (!type->isBlockPointerType())
1854 return EmitARCRetainAutoreleaseNonBlock(value);
1855
1856 if (isa<llvm::ConstantPointerNull>(value)) return value;
1857
Chris Lattner2acc6e32011-07-18 04:24:23 +00001858 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001859 value = Builder.CreateBitCast(value, Int8PtrTy);
1860 value = EmitARCRetainBlock(value);
1861 value = EmitARCAutorelease(value);
1862 return Builder.CreateBitCast(value, origType);
1863}
1864
1865/// Do a fused retain/autorelease of the given object.
1866/// call i8* @objc_retainAutorelease(i8* %value)
1867llvm::Value *
1868CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
1869 return emitARCValueOperation(*this, value,
1870 CGM.getARCEntrypoints().objc_retainAutorelease,
1871 "objc_retainAutorelease");
1872}
1873
1874/// i8* @objc_loadWeak(i8** %addr)
1875/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
1876llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
1877 return emitARCLoadOperation(*this, addr,
1878 CGM.getARCEntrypoints().objc_loadWeak,
1879 "objc_loadWeak");
1880}
1881
1882/// i8* @objc_loadWeakRetained(i8** %addr)
1883llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
1884 return emitARCLoadOperation(*this, addr,
1885 CGM.getARCEntrypoints().objc_loadWeakRetained,
1886 "objc_loadWeakRetained");
1887}
1888
1889/// i8* @objc_storeWeak(i8** %addr, i8* %value)
1890/// Returns %value.
1891llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
1892 llvm::Value *value,
1893 bool ignored) {
1894 return emitARCStoreOperation(*this, addr, value,
1895 CGM.getARCEntrypoints().objc_storeWeak,
1896 "objc_storeWeak", ignored);
1897}
1898
1899/// i8* @objc_initWeak(i8** %addr, i8* %value)
1900/// Returns %value. %addr is known to not have a current weak entry.
1901/// Essentially equivalent to:
1902/// *addr = nil; objc_storeWeak(addr, value);
1903void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
1904 // If we're initializing to null, just write null to memory; no need
1905 // to get the runtime involved. But don't do this if optimization
1906 // is enabled, because accounting for this would make the optimizer
1907 // much more complicated.
1908 if (isa<llvm::ConstantPointerNull>(value) &&
1909 CGM.getCodeGenOpts().OptimizationLevel == 0) {
1910 Builder.CreateStore(value, addr);
1911 return;
1912 }
1913
1914 emitARCStoreOperation(*this, addr, value,
1915 CGM.getARCEntrypoints().objc_initWeak,
1916 "objc_initWeak", /*ignored*/ true);
1917}
1918
1919/// void @objc_destroyWeak(i8** %addr)
1920/// Essentially objc_storeWeak(addr, nil).
1921void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
1922 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
1923 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001924 std::vector<llvm::Type*> args(1, Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001925 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001926 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1927 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
1928 }
1929
1930 // Cast the argument to 'id*'.
1931 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1932
1933 llvm::CallInst *call = Builder.CreateCall(fn, addr);
1934 call->setDoesNotThrow();
1935}
1936
1937/// void @objc_moveWeak(i8** %dest, i8** %src)
1938/// Disregards the current value in %dest. Leaves %src pointing to nothing.
1939/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
1940void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
1941 emitARCCopyOperation(*this, dst, src,
1942 CGM.getARCEntrypoints().objc_moveWeak,
1943 "objc_moveWeak");
1944}
1945
1946/// void @objc_copyWeak(i8** %dest, i8** %src)
1947/// Disregards the current value in %dest. Essentially
1948/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
1949void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
1950 emitARCCopyOperation(*this, dst, src,
1951 CGM.getARCEntrypoints().objc_copyWeak,
1952 "objc_copyWeak");
1953}
1954
1955/// Produce the code to do a objc_autoreleasepool_push.
1956/// call i8* @objc_autoreleasePoolPush(void)
1957llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
1958 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
1959 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001960 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001961 llvm::FunctionType::get(Int8PtrTy, false);
1962 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
1963 }
1964
1965 llvm::CallInst *call = Builder.CreateCall(fn);
1966 call->setDoesNotThrow();
1967
1968 return call;
1969}
1970
1971/// Produce the code to do a primitive release.
1972/// call void @objc_autoreleasePoolPop(i8* %ptr)
1973void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
1974 assert(value->getType() == Int8PtrTy);
1975
1976 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
1977 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001978 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001979 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001980 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1981
1982 // We don't want to use a weak import here; instead we should not
1983 // fall into this path.
1984 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
1985 }
1986
1987 llvm::CallInst *call = Builder.CreateCall(fn, value);
1988 call->setDoesNotThrow();
1989}
1990
1991/// Produce the code to do an MRR version objc_autoreleasepool_push.
1992/// Which is: [[NSAutoreleasePool alloc] init];
1993/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
1994/// init is declared as: - (id) init; in its NSObject super class.
1995///
1996llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
1997 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
1998 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder);
1999 // [NSAutoreleasePool alloc]
2000 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2001 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2002 CallArgList Args;
2003 RValue AllocRV =
2004 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2005 getContext().getObjCIdType(),
2006 AllocSel, Receiver, Args);
2007
2008 // [Receiver init]
2009 Receiver = AllocRV.getScalarVal();
2010 II = &CGM.getContext().Idents.get("init");
2011 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2012 RValue InitRV =
2013 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2014 getContext().getObjCIdType(),
2015 InitSel, Receiver, Args);
2016 return InitRV.getScalarVal();
2017}
2018
2019/// Produce the code to do a primitive release.
2020/// [tmp drain];
2021void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2022 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2023 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2024 CallArgList Args;
2025 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2026 getContext().VoidTy, DrainSel, Arg, Args);
2027}
2028
John McCallbdc4d802011-07-09 01:37:26 +00002029void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2030 llvm::Value *addr,
2031 QualType type) {
2032 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2033 CGF.EmitARCRelease(ptr, /*precise*/ true);
2034}
2035
2036void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2037 llvm::Value *addr,
2038 QualType type) {
2039 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2040 CGF.EmitARCRelease(ptr, /*precise*/ false);
2041}
2042
2043void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2044 llvm::Value *addr,
2045 QualType type) {
2046 CGF.EmitARCDestroyWeak(addr);
2047}
2048
John McCallf85e1932011-06-15 23:02:42 +00002049namespace {
John McCallf85e1932011-06-15 23:02:42 +00002050 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2051 llvm::Value *Token;
2052
2053 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2054
John McCallad346f42011-07-12 20:27:29 +00002055 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002056 CGF.EmitObjCAutoreleasePoolPop(Token);
2057 }
2058 };
2059 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2060 llvm::Value *Token;
2061
2062 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2063
John McCallad346f42011-07-12 20:27:29 +00002064 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002065 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2066 }
2067 };
2068}
2069
2070void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
2071 if (CGM.getLangOptions().ObjCAutoRefCount)
2072 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2073 else
2074 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2075}
2076
John McCallf85e1932011-06-15 23:02:42 +00002077static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2078 LValue lvalue,
2079 QualType type) {
2080 switch (type.getObjCLifetime()) {
2081 case Qualifiers::OCL_None:
2082 case Qualifiers::OCL_ExplicitNone:
2083 case Qualifiers::OCL_Strong:
2084 case Qualifiers::OCL_Autoreleasing:
John McCall545d9962011-06-25 02:11:03 +00002085 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(),
John McCallf85e1932011-06-15 23:02:42 +00002086 false);
2087
2088 case Qualifiers::OCL_Weak:
2089 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2090 true);
2091 }
2092
2093 llvm_unreachable("impossible lifetime!");
2094 return TryEmitResult();
2095}
2096
2097static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2098 const Expr *e) {
2099 e = e->IgnoreParens();
2100 QualType type = e->getType();
2101
John McCall21480112011-08-30 00:57:29 +00002102 // If we're loading retained from a __strong xvalue, we can avoid
2103 // an extra retain/release pair by zeroing out the source of this
2104 // "move" operation.
2105 if (e->isXValue() &&
2106 !type.isConstQualified() &&
2107 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2108 // Emit the lvalue.
2109 LValue lv = CGF.EmitLValue(e);
2110
2111 // Load the object pointer.
2112 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal();
2113
2114 // Set the source pointer to NULL.
2115 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2116
2117 return TryEmitResult(result, true);
2118 }
2119
John McCallf85e1932011-06-15 23:02:42 +00002120 // As a very special optimization, in ARC++, if the l-value is the
2121 // result of a non-volatile assignment, do a simple retain of the
2122 // result of the call to objc_storeWeak instead of reloading.
2123 if (CGF.getLangOptions().CPlusPlus &&
2124 !type.isVolatileQualified() &&
2125 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2126 isa<BinaryOperator>(e) &&
2127 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2128 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2129
2130 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2131}
2132
2133static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2134 llvm::Value *value);
2135
2136/// Given that the given expression is some sort of call (which does
2137/// not return retained), emit a retain following it.
2138static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2139 llvm::Value *value = CGF.EmitScalarExpr(e);
2140 return emitARCRetainAfterCall(CGF, value);
2141}
2142
2143static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2144 llvm::Value *value) {
2145 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2146 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2147
2148 // Place the retain immediately following the call.
2149 CGF.Builder.SetInsertPoint(call->getParent(),
2150 ++llvm::BasicBlock::iterator(call));
2151 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2152
2153 CGF.Builder.restoreIP(ip);
2154 return value;
2155 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2156 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2157
2158 // Place the retain at the beginning of the normal destination block.
2159 llvm::BasicBlock *BB = invoke->getNormalDest();
2160 CGF.Builder.SetInsertPoint(BB, BB->begin());
2161 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2162
2163 CGF.Builder.restoreIP(ip);
2164 return value;
2165
2166 // Bitcasts can arise because of related-result returns. Rewrite
2167 // the operand.
2168 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2169 llvm::Value *operand = bitcast->getOperand(0);
2170 operand = emitARCRetainAfterCall(CGF, operand);
2171 bitcast->setOperand(0, operand);
2172 return bitcast;
2173
2174 // Generic fall-back case.
2175 } else {
2176 // Retain using the non-block variant: we never need to do a copy
2177 // of a block that's been returned to us.
2178 return CGF.EmitARCRetainNonBlock(value);
2179 }
2180}
2181
John McCalldc05b112011-09-10 01:16:55 +00002182/// Determine whether it might be important to emit a separate
2183/// objc_retain_block on the result of the given expression, or
2184/// whether it's okay to just emit it in a +1 context.
2185static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2186 assert(e->getType()->isBlockPointerType());
2187 e = e->IgnoreParens();
2188
2189 // For future goodness, emit block expressions directly in +1
2190 // contexts if we can.
2191 if (isa<BlockExpr>(e))
2192 return false;
2193
2194 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2195 switch (cast->getCastKind()) {
2196 // Emitting these operations in +1 contexts is goodness.
2197 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00002198 case CK_ARCReclaimReturnedObject:
2199 case CK_ARCConsumeObject:
2200 case CK_ARCProduceObject:
John McCalldc05b112011-09-10 01:16:55 +00002201 return false;
2202
2203 // These operations preserve a block type.
2204 case CK_NoOp:
2205 case CK_BitCast:
2206 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2207
2208 // These operations are known to be bad (or haven't been considered).
2209 case CK_AnyPointerToBlockPointerCast:
2210 default:
2211 return true;
2212 }
2213 }
2214
2215 return true;
2216}
2217
John McCallf85e1932011-06-15 23:02:42 +00002218static TryEmitResult
2219tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCall990567c2011-07-27 01:07:15 +00002220 // Look through cleanups.
2221 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2222 CodeGenFunction::RunCleanupsScope scope(CGF);
2223 return tryEmitARCRetainScalarExpr(CGF, cleanups->getSubExpr());
2224 }
2225
John McCallf85e1932011-06-15 23:02:42 +00002226 // The desired result type, if it differs from the type of the
2227 // ultimate opaque expression.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002228 llvm::Type *resultType = 0;
John McCallf85e1932011-06-15 23:02:42 +00002229
2230 while (true) {
2231 e = e->IgnoreParens();
2232
2233 // There's a break at the end of this if-chain; anything
2234 // that wants to keep looping has to explicitly continue.
2235 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2236 switch (ce->getCastKind()) {
2237 // No-op casts don't change the type, so we just ignore them.
2238 case CK_NoOp:
2239 e = ce->getSubExpr();
2240 continue;
2241
2242 case CK_LValueToRValue: {
2243 TryEmitResult loadResult
2244 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2245 if (resultType) {
2246 llvm::Value *value = loadResult.getPointer();
2247 value = CGF.Builder.CreateBitCast(value, resultType);
2248 loadResult.setPointer(value);
2249 }
2250 return loadResult;
2251 }
2252
2253 // These casts can change the type, so remember that and
2254 // soldier on. We only need to remember the outermost such
2255 // cast, though.
John McCall1d9b3b22011-09-09 05:25:32 +00002256 case CK_CPointerToObjCPointerCast:
2257 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00002258 case CK_AnyPointerToBlockPointerCast:
2259 case CK_BitCast:
2260 if (!resultType)
2261 resultType = CGF.ConvertType(ce->getType());
2262 e = ce->getSubExpr();
2263 assert(e->getType()->hasPointerRepresentation());
2264 continue;
2265
2266 // For consumptions, just emit the subexpression and thus elide
2267 // the retain/release pair.
John McCall33e56f32011-09-10 06:18:15 +00002268 case CK_ARCConsumeObject: {
John McCallf85e1932011-06-15 23:02:42 +00002269 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2270 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2271 return TryEmitResult(result, true);
2272 }
2273
John McCalldc05b112011-09-10 01:16:55 +00002274 // Block extends are net +0. Naively, we could just recurse on
2275 // the subexpression, but actually we need to ensure that the
2276 // value is copied as a block, so there's a little filter here.
John McCall33e56f32011-09-10 06:18:15 +00002277 case CK_ARCExtendBlockObject: {
John McCalldc05b112011-09-10 01:16:55 +00002278 llvm::Value *result; // will be a +0 value
2279
2280 // If we can't safely assume the sub-expression will produce a
2281 // block-copied value, emit the sub-expression at +0.
2282 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2283 result = CGF.EmitScalarExpr(ce->getSubExpr());
2284
2285 // Otherwise, try to emit the sub-expression at +1 recursively.
2286 } else {
2287 TryEmitResult subresult
2288 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2289 result = subresult.getPointer();
2290
2291 // If that produced a retained value, just use that,
2292 // possibly casting down.
2293 if (subresult.getInt()) {
2294 if (resultType)
2295 result = CGF.Builder.CreateBitCast(result, resultType);
2296 return TryEmitResult(result, true);
2297 }
2298
2299 // Otherwise it's +0.
2300 }
2301
2302 // Retain the object as a block, then cast down.
2303 result = CGF.EmitARCRetainBlock(result);
2304 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2305 return TryEmitResult(result, true);
2306 }
2307
John McCall7e5e5f42011-07-07 06:58:02 +00002308 // For reclaims, emit the subexpression as a retained call and
2309 // skip the consumption.
John McCall33e56f32011-09-10 06:18:15 +00002310 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00002311 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2312 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2313 return TryEmitResult(result, true);
2314 }
2315
John McCallf85e1932011-06-15 23:02:42 +00002316 case CK_GetObjCProperty: {
2317 llvm::Value *result = emitARCRetainCall(CGF, ce);
2318 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2319 return TryEmitResult(result, true);
2320 }
2321
2322 default:
2323 break;
2324 }
2325
2326 // Skip __extension__.
2327 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2328 if (op->getOpcode() == UO_Extension) {
2329 e = op->getSubExpr();
2330 continue;
2331 }
2332
2333 // For calls and message sends, use the retained-call logic.
2334 // Delegate inits are a special case in that they're the only
2335 // returns-retained expression that *isn't* surrounded by
2336 // a consume.
2337 } else if (isa<CallExpr>(e) ||
2338 (isa<ObjCMessageExpr>(e) &&
2339 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2340 llvm::Value *result = emitARCRetainCall(CGF, e);
2341 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2342 return TryEmitResult(result, true);
2343 }
2344
2345 // Conservatively halt the search at any other expression kind.
2346 break;
2347 }
2348
2349 // We didn't find an obvious production, so emit what we've got and
2350 // tell the caller that we didn't manage to retain.
2351 llvm::Value *result = CGF.EmitScalarExpr(e);
2352 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2353 return TryEmitResult(result, false);
2354}
2355
2356static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2357 LValue lvalue,
2358 QualType type) {
2359 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2360 llvm::Value *value = result.getPointer();
2361 if (!result.getInt())
2362 value = CGF.EmitARCRetain(type, value);
2363 return value;
2364}
2365
2366/// EmitARCRetainScalarExpr - Semantically equivalent to
2367/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2368/// best-effort attempt to peephole expressions that naturally produce
2369/// retained objects.
2370llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
2371 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2372 llvm::Value *value = result.getPointer();
2373 if (!result.getInt())
2374 value = EmitARCRetain(e->getType(), value);
2375 return value;
2376}
2377
2378llvm::Value *
2379CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
2380 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2381 llvm::Value *value = result.getPointer();
2382 if (result.getInt())
2383 value = EmitARCAutorelease(value);
2384 else
2385 value = EmitARCRetainAutorelease(e->getType(), value);
2386 return value;
2387}
2388
2389std::pair<LValue,llvm::Value*>
2390CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2391 bool ignored) {
2392 // Evaluate the RHS first.
2393 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2394 llvm::Value *value = result.getPointer();
2395
John McCallfb720812011-07-28 07:23:35 +00002396 bool hasImmediateRetain = result.getInt();
2397
2398 // If we didn't emit a retained object, and the l-value is of block
2399 // type, then we need to emit the block-retain immediately in case
2400 // it invalidates the l-value.
2401 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
2402 value = EmitARCRetainBlock(value);
2403 hasImmediateRetain = true;
2404 }
2405
John McCallf85e1932011-06-15 23:02:42 +00002406 LValue lvalue = EmitLValue(e->getLHS());
2407
2408 // If the RHS was emitted retained, expand this.
John McCallfb720812011-07-28 07:23:35 +00002409 if (hasImmediateRetain) {
John McCallf85e1932011-06-15 23:02:42 +00002410 llvm::Value *oldValue =
2411 EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatileQualified(),
2412 lvalue.getAlignment(), e->getType(),
2413 lvalue.getTBAAInfo());
2414 EmitStoreOfScalar(value, lvalue.getAddress(),
2415 lvalue.isVolatileQualified(), lvalue.getAlignment(),
2416 e->getType(), lvalue.getTBAAInfo());
2417 EmitARCRelease(oldValue, /*precise*/ false);
2418 } else {
John McCall545d9962011-06-25 02:11:03 +00002419 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCallf85e1932011-06-15 23:02:42 +00002420 }
2421
2422 return std::pair<LValue,llvm::Value*>(lvalue, value);
2423}
2424
2425std::pair<LValue,llvm::Value*>
2426CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2427 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2428 LValue lvalue = EmitLValue(e->getLHS());
2429
2430 EmitStoreOfScalar(value, lvalue.getAddress(),
2431 lvalue.isVolatileQualified(), lvalue.getAlignment(),
2432 e->getType(), lvalue.getTBAAInfo());
2433
2434 return std::pair<LValue,llvm::Value*>(lvalue, value);
2435}
2436
2437void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
2438 const ObjCAutoreleasePoolStmt &ARPS) {
2439 const Stmt *subStmt = ARPS.getSubStmt();
2440 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2441
2442 CGDebugInfo *DI = getDebugInfo();
2443 if (DI) {
2444 DI->setLocation(S.getLBracLoc());
2445 DI->EmitRegionStart(Builder);
2446 }
2447
2448 // Keep track of the current cleanup stack depth.
2449 RunCleanupsScope Scope(*this);
John McCall9f084a32011-07-06 00:26:06 +00002450 if (CGM.getCodeGenOpts().ObjCRuntimeHasARC) {
John McCallf85e1932011-06-15 23:02:42 +00002451 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2452 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2453 } else {
2454 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2455 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2456 }
2457
2458 for (CompoundStmt::const_body_iterator I = S.body_begin(),
2459 E = S.body_end(); I != E; ++I)
2460 EmitStmt(*I);
2461
2462 if (DI) {
2463 DI->setLocation(S.getRBracLoc());
2464 DI->EmitRegionEnd(Builder);
2465 }
2466}
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() {}