blob: 9fc2add875c3fe8356a8bd9ec907fcb676ecfa93 [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 McCallef072fd2010-05-22 01:48:05 +000083RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
84 ReturnValueSlot Return) {
Chris Lattner8fdf3282008-06-24 17:04:18 +000085 // Only the lookup mechanism and first two arguments of the method
86 // implementation vary between runtimes. We can get the receiver and
87 // arguments in generic code.
Mike Stump1eb44332009-09-09 15:08:12 +000088
John McCallf85e1932011-06-15 23:02:42 +000089 bool isDelegateInit = E->isDelegateInitCall();
90
91 // We don't retain the receiver in delegate init calls, and this is
92 // safe because the receiver value is always loaded from 'self',
93 // which we zero out. We don't want to Block_copy block receivers,
94 // though.
95 bool retainSelf =
96 (!isDelegateInit &&
97 CGM.getLangOptions().ObjCAutoRefCount &&
98 E->getMethodDecl() &&
99 E->getMethodDecl()->hasAttr<NSConsumesSelfAttr>());
100
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000101 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000102 bool isSuperMessage = false;
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000103 bool isClassMessage = false;
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000104 ObjCInterfaceDecl *OID = 0;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000105 // Find the receiver
Douglas Gregor926df6c2011-06-11 01:09:30 +0000106 QualType ReceiverType;
Daniel Dunbar0b647a62010-04-22 03:17:06 +0000107 llvm::Value *Receiver = 0;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000108 switch (E->getReceiverKind()) {
109 case ObjCMessageExpr::Instance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000110 ReceiverType = E->getInstanceReceiver()->getType();
John McCallf85e1932011-06-15 23:02:42 +0000111 if (retainSelf) {
112 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
113 E->getInstanceReceiver());
114 Receiver = ter.getPointer();
115 if (!ter.getInt())
116 Receiver = EmitARCRetainNonBlock(Receiver);
117 } else
118 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor04badcf2010-04-21 00:45:42 +0000119 break;
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000120
Douglas Gregor04badcf2010-04-21 00:45:42 +0000121 case ObjCMessageExpr::Class: {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000122 ReceiverType = E->getClassReceiver();
123 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3031c632010-05-17 20:12:43 +0000124 assert(ObjTy && "Invalid Objective-C class message send");
125 OID = ObjTy->getInterface();
126 assert(OID && "Invalid Objective-C class message send");
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000127 Receiver = Runtime.GetClass(Builder, OID);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000128 isClassMessage = true;
John McCallf85e1932011-06-15 23:02:42 +0000129
130 if (retainSelf)
131 Receiver = EmitARCRetainNonBlock(Receiver);
Douglas Gregor04badcf2010-04-21 00:45:42 +0000132 break;
133 }
134
135 case ObjCMessageExpr::SuperInstance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000136 ReceiverType = E->getSuperType();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000137 Receiver = LoadObjCSelf();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000138 isSuperMessage = true;
John McCallf85e1932011-06-15 23:02:42 +0000139
140 if (retainSelf)
141 Receiver = EmitARCRetainNonBlock(Receiver);
Douglas Gregor04badcf2010-04-21 00:45:42 +0000142 break;
143
144 case ObjCMessageExpr::SuperClass:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000145 ReceiverType = E->getSuperType();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000146 Receiver = LoadObjCSelf();
147 isSuperMessage = true;
148 isClassMessage = true;
John McCallf85e1932011-06-15 23:02:42 +0000149
150 if (retainSelf)
151 Receiver = EmitARCRetainNonBlock(Receiver);
Douglas Gregor04badcf2010-04-21 00:45:42 +0000152 break;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000153 }
154
John McCallf85e1932011-06-15 23:02:42 +0000155 QualType ResultType =
156 E->getMethodDecl() ? E->getMethodDecl()->getResultType() : E->getType();
157
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000158 CallArgList Args;
Anders Carlsson131038e2009-04-18 20:29:27 +0000159 EmitCallArgs(Args, E->getMethodDecl(), E->arg_begin(), E->arg_end());
Mike Stump1eb44332009-09-09 15:08:12 +0000160
John McCallf85e1932011-06-15 23:02:42 +0000161 // For delegate init calls in ARC, do an unsafe store of null into
162 // self. This represents the call taking direct ownership of that
163 // value. We have to do this after emitting the other call
164 // arguments because they might also reference self, but we don't
165 // have to worry about any of them modifying self because that would
166 // be an undefined read and write of an object in unordered
167 // expressions.
168 if (isDelegateInit) {
169 assert(getLangOptions().ObjCAutoRefCount &&
170 "delegate init calls should only be marked in ARC");
171
172 // Do an unsafe store of null into self.
173 llvm::Value *selfAddr =
174 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
175 assert(selfAddr && "no self entry for a delegate init call?");
176
177 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
178 }
Anders Carlsson7e70fb22010-06-21 20:59:55 +0000179
Douglas Gregor926df6c2011-06-11 01:09:30 +0000180 RValue result;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000181 if (isSuperMessage) {
Chris Lattner9384c762008-06-26 04:42:20 +0000182 // super is only valid in an Objective-C method
183 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000184 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor926df6c2011-06-11 01:09:30 +0000185 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
186 E->getSelector(),
187 OMD->getClassInterface(),
188 isCategoryImpl,
189 Receiver,
190 isClassMessage,
191 Args,
192 E->getMethodDecl());
193 } else {
194 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
195 E->getSelector(),
196 Receiver, Args, OID,
197 E->getMethodDecl());
Chris Lattner8fdf3282008-06-24 17:04:18 +0000198 }
John McCallf85e1932011-06-15 23:02:42 +0000199
200 // For delegate init calls in ARC, implicitly store the result of
201 // the call back into self. This takes ownership of the value.
202 if (isDelegateInit) {
203 llvm::Value *selfAddr =
204 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
205 llvm::Value *newSelf = result.getScalarVal();
206
207 // The delegate return type isn't necessarily a matching type; in
208 // fact, it's quite likely to be 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000209 llvm::Type *selfTy =
John McCallf85e1932011-06-15 23:02:42 +0000210 cast<llvm::PointerType>(selfAddr->getType())->getElementType();
211 newSelf = Builder.CreateBitCast(newSelf, selfTy);
212
213 Builder.CreateStore(newSelf, selfAddr);
214 }
215
Douglas Gregor926df6c2011-06-11 01:09:30 +0000216 return AdjustRelatedResultType(*this, E, E->getMethodDecl(), result);
Anders Carlsson55085182007-08-21 17:43:55 +0000217}
218
John McCallf85e1932011-06-15 23:02:42 +0000219namespace {
220struct FinishARCDealloc : EHScopeStack::Cleanup {
John McCallad346f42011-07-12 20:27:29 +0000221 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +0000222 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCall799d34e2011-07-13 18:26:47 +0000223
224 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCallf85e1932011-06-15 23:02:42 +0000225 const ObjCInterfaceDecl *iface = impl->getClassInterface();
226 if (!iface->getSuperClass()) return;
227
John McCall799d34e2011-07-13 18:26:47 +0000228 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
229
John McCallf85e1932011-06-15 23:02:42 +0000230 // Call [super dealloc] if we have a superclass.
231 llvm::Value *self = CGF.LoadObjCSelf();
232
233 CallArgList args;
234 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
235 CGF.getContext().VoidTy,
236 method->getSelector(),
237 iface,
John McCall799d34e2011-07-13 18:26:47 +0000238 isCategory,
John McCallf85e1932011-06-15 23:02:42 +0000239 self,
240 /*is class msg*/ false,
241 args,
242 method);
243 }
244};
245}
246
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000247/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
248/// the LLVM function and sets the other context used by
249/// CodeGenFunction.
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000250void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
Devang Patel8d3f8972011-05-19 23:37:41 +0000251 const ObjCContainerDecl *CD,
252 SourceLocation StartLoc) {
John McCalld26bc762011-03-09 04:27:21 +0000253 FunctionArgList args;
Devang Patel4800ea62010-04-05 21:09:15 +0000254 // Check if we should generate debug info for this method.
Devang Patelaa112892011-03-07 18:45:56 +0000255 if (CGM.getModuleDebugInfo() && !OMD->hasAttr<NoDebugAttr>())
256 DebugInfo = CGM.getModuleDebugInfo();
Devang Patel4800ea62010-04-05 21:09:15 +0000257
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000258 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000259
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000260 const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(OMD);
261 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner41110242008-06-17 18:05:57 +0000262
John McCalld26bc762011-03-09 04:27:21 +0000263 args.push_back(OMD->getSelfDecl());
264 args.push_back(OMD->getCmdDecl());
Chris Lattner41110242008-06-17 18:05:57 +0000265
Chris Lattner89951a82009-02-20 18:43:26 +0000266 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
267 E = OMD->param_end(); PI != E; ++PI)
John McCalld26bc762011-03-09 04:27:21 +0000268 args.push_back(*PI);
Chris Lattner41110242008-06-17 18:05:57 +0000269
Peter Collingbourne14110472011-01-13 18:57:25 +0000270 CurGD = OMD;
271
Devang Patel8d3f8972011-05-19 23:37:41 +0000272 StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc);
John McCallf85e1932011-06-15 23:02:42 +0000273
274 // In ARC, certain methods get an extra cleanup.
275 if (CGM.getLangOptions().ObjCAutoRefCount &&
276 OMD->isInstanceMethod() &&
277 OMD->getSelector().isUnarySelector()) {
278 const IdentifierInfo *ident =
279 OMD->getSelector().getIdentifierInfoForSlot(0);
280 if (ident->isStr("dealloc"))
281 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
282 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000283}
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000284
John McCallf85e1932011-06-15 23:02:42 +0000285static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
286 LValue lvalue, QualType type);
287
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000288void CodeGenFunction::GenerateObjCGetterBody(ObjCIvarDecl *Ivar,
289 bool IsAtomic, bool IsStrong) {
290 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
291 Ivar, 0);
292 llvm::Value *GetCopyStructFn =
293 CGM.getObjCRuntime().GetGetStructFunction();
294 CodeGenTypes &Types = CGM.getTypes();
295 // objc_copyStruct (ReturnValue, &structIvar,
296 // sizeof (Type of Ivar), isAtomic, false);
297 CallArgList Args;
John McCall0774cb82011-05-15 01:53:33 +0000298 RValue RV = RValue::get(Builder.CreateBitCast(ReturnValue, VoidPtrTy));
Eli Friedman04c9a492011-05-02 17:57:46 +0000299 Args.add(RV, getContext().VoidPtrTy);
John McCall0774cb82011-05-15 01:53:33 +0000300 RV = RValue::get(Builder.CreateBitCast(LV.getAddress(), VoidPtrTy));
Eli Friedman04c9a492011-05-02 17:57:46 +0000301 Args.add(RV, getContext().VoidPtrTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000302 // sizeof (Type of Ivar)
303 CharUnits Size = getContext().getTypeSizeInChars(Ivar->getType());
304 llvm::Value *SizeVal =
John McCall0774cb82011-05-15 01:53:33 +0000305 llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy),
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000306 Size.getQuantity());
Eli Friedman04c9a492011-05-02 17:57:46 +0000307 Args.add(RValue::get(SizeVal), getContext().LongTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000308 llvm::Value *isAtomic =
309 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy),
310 IsAtomic ? 1 : 0);
Eli Friedman04c9a492011-05-02 17:57:46 +0000311 Args.add(RValue::get(isAtomic), getContext().BoolTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000312 llvm::Value *hasStrong =
313 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy),
314 IsStrong ? 1 : 0);
Eli Friedman04c9a492011-05-02 17:57:46 +0000315 Args.add(RValue::get(hasStrong), getContext().BoolTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000316 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
317 FunctionType::ExtInfo()),
318 GetCopyStructFn, ReturnValueSlot(), Args);
319}
320
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000321/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump1eb44332009-09-09 15:08:12 +0000322/// its pointer, name, and types registered in the class struture.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000323void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
Devang Patel8d3f8972011-05-19 23:37:41 +0000324 StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000325 EmitStmt(OMD->getBody());
326 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000327}
328
Mike Stumpf5408fe2009-05-16 07:57:57 +0000329// FIXME: I wasn't sure about the synthesis approach. If we end up generating an
330// AST for the whole body we can just fall back to having a GenerateFunction
331// which takes the body Stmt.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000332
333/// GenerateObjCGetter - Generate an Objective-C property getter
Steve Naroff489034c2009-01-10 22:55:25 +0000334/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
335/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000336void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
337 const ObjCPropertyImplDecl *PID) {
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000338 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000339 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000340 bool IsAtomic =
341 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000342 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
343 assert(OMD && "Invalid call to generate getter (empty method)");
Devang Patel8d3f8972011-05-19 23:37:41 +0000344 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000345
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000346 // Determine if we should use an objc_getProperty call for
Fariborz Jahanian447d7ae2008-12-08 23:56:17 +0000347 // this. Non-atomic properties are directly evaluated.
348 // atomic 'copy' and 'retain' properties are also directly
349 // evaluated in gc-only mode.
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000350 if (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000351 IsAtomic &&
Fariborz Jahanian447d7ae2008-12-08 23:56:17 +0000352 (PD->getSetterKind() == ObjCPropertyDecl::Copy ||
353 PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000354 llvm::Value *GetPropertyFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000355 CGM.getObjCRuntime().GetPropertyGetFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000357 if (!GetPropertyFn) {
358 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
359 FinishFunction();
360 return;
361 }
362
363 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
364 // FIXME: Can't this be simpler? This might even be worse than the
365 // corresponding gcc code.
366 CodeGenTypes &Types = CGM.getTypes();
367 ValueDecl *Cmd = OMD->getCmdDecl();
368 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
369 QualType IdTy = getContext().getObjCIdType();
Mike Stump1eb44332009-09-09 15:08:12 +0000370 llvm::Value *SelfAsId =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000371 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000372 llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000373 llvm::Value *True =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000374 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000375 CallArgList Args;
Eli Friedman04c9a492011-05-02 17:57:46 +0000376 Args.add(RValue::get(SelfAsId), IdTy);
377 Args.add(RValue::get(CmdVal), Cmd->getType());
378 Args.add(RValue::get(Offset), getContext().getPointerDiffType());
379 Args.add(RValue::get(True), getContext().BoolTy);
Daniel Dunbare4be5a62009-02-03 23:43:59 +0000380 // FIXME: We shouldn't need to get the function info here, the
381 // runtime already should have computed it to build the function.
John McCall04a67a62010-02-05 21:31:56 +0000382 RValue RV = EmitCall(Types.getFunctionInfo(PD->getType(), Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000383 FunctionType::ExtInfo()),
Anders Carlssonf3c47c92009-12-24 19:25:24 +0000384 GetPropertyFn, ReturnValueSlot(), Args);
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000385 // We need to fix the type here. Ivars with copy & retain are
386 // always objects so we don't need to worry about complex or
387 // aggregates.
Mike Stump1eb44332009-09-09 15:08:12 +0000388 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000389 Types.ConvertType(PD->getType())));
390 EmitReturnOfRValue(RV, PD->getType());
John McCallf85e1932011-06-15 23:02:42 +0000391
392 // objc_getProperty does an autorelease, so we should suppress ours.
393 AutoreleaseResult = false;
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000394 } else {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000395 const llvm::Triple &Triple = getContext().Target.getTriple();
396 QualType IVART = Ivar->getType();
397 if (IsAtomic &&
398 IVART->isScalarType() &&
399 (Triple.getArch() == llvm::Triple::arm ||
400 Triple.getArch() == llvm::Triple::thumb) &&
401 (getContext().getTypeSizeInChars(IVART)
402 > CharUnits::fromQuantity(4)) &&
403 CGM.getObjCRuntime().GetGetStructFunction()) {
404 GenerateObjCGetterBody(Ivar, true, false);
405 }
Fariborz Jahanian1d3a61a2011-04-05 21:41:23 +0000406 else if (IsAtomic &&
407 (IVART->isScalarType() && !IVART->isRealFloatingType()) &&
408 Triple.getArch() == llvm::Triple::x86 &&
409 (getContext().getTypeSizeInChars(IVART)
410 > CharUnits::fromQuantity(4)) &&
411 CGM.getObjCRuntime().GetGetStructFunction()) {
412 GenerateObjCGetterBody(Ivar, true, false);
413 }
414 else if (IsAtomic &&
415 (IVART->isScalarType() && !IVART->isRealFloatingType()) &&
416 Triple.getArch() == llvm::Triple::x86_64 &&
417 (getContext().getTypeSizeInChars(IVART)
418 > CharUnits::fromQuantity(8)) &&
419 CGM.getObjCRuntime().GetGetStructFunction()) {
420 GenerateObjCGetterBody(Ivar, true, false);
421 }
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000422 else if (IVART->isAnyComplexType()) {
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000423 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
424 Ivar, 0);
Fariborz Jahanian1b23fe62010-03-25 21:56:43 +0000425 ComplexPairTy Pair = LoadComplexFromAddr(LV.getAddress(),
426 LV.isVolatileQualified());
427 StoreComplexToAddr(Pair, ReturnValue, LV.isVolatileQualified());
428 }
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000429 else if (hasAggregateLLVMType(IVART)) {
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000430 bool IsStrong = false;
Fariborz Jahanian5fb65092011-04-05 23:01:27 +0000431 if ((IsStrong = IvarTypeWithAggrGCObjects(IVART))
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000432 && CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect
David Chisnall8fac25d2010-12-26 22:13:16 +0000433 && CGM.getObjCRuntime().GetGetStructFunction()) {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000434 GenerateObjCGetterBody(Ivar, IsAtomic, IsStrong);
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000435 }
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000436 else {
Fariborz Jahanian01cb3072011-04-06 16:05:26 +0000437 const CXXRecordDecl *classDecl = IVART->getAsCXXRecordDecl();
438
439 if (PID->getGetterCXXConstructor() &&
Sean Hunt023df372011-05-09 18:22:59 +0000440 classDecl && !classDecl->hasTrivialDefaultConstructor()) {
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000441 ReturnStmt *Stmt =
442 new (getContext()) ReturnStmt(SourceLocation(),
Douglas Gregor5077c382010-05-15 06:01:05 +0000443 PID->getGetterCXXConstructor(),
444 0);
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000445 EmitReturnStmt(*Stmt);
Fariborz Jahanian1d3a61a2011-04-05 21:41:23 +0000446 } else if (IsAtomic &&
447 !IVART->isAnyComplexType() &&
448 Triple.getArch() == llvm::Triple::x86 &&
449 (getContext().getTypeSizeInChars(IVART)
450 > CharUnits::fromQuantity(4)) &&
451 CGM.getObjCRuntime().GetGetStructFunction()) {
452 GenerateObjCGetterBody(Ivar, true, false);
453 }
454 else if (IsAtomic &&
455 !IVART->isAnyComplexType() &&
456 Triple.getArch() == llvm::Triple::x86_64 &&
457 (getContext().getTypeSizeInChars(IVART)
458 > CharUnits::fromQuantity(8)) &&
459 CGM.getObjCRuntime().GetGetStructFunction()) {
460 GenerateObjCGetterBody(Ivar, true, false);
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000461 }
462 else {
463 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
464 Ivar, 0);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000465 EmitAggregateCopy(ReturnValue, LV.getAddress(), IVART);
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000466 }
467 }
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000468 }
469 else {
470 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
John McCall545d9962011-06-25 02:11:03 +0000471 Ivar, 0);
John McCallf85e1932011-06-15 23:02:42 +0000472 QualType propType = PD->getType();
473
474 llvm::Value *value;
475 if (propType->isReferenceType()) {
476 value = LV.getAddress();
477 } else {
478 // In ARC, we want to emit this retained.
479 if (getLangOptions().ObjCAutoRefCount &&
480 PD->getType()->isObjCRetainableType())
481 value = emitARCRetainLoadOfScalar(*this, LV, IVART);
482 else
John McCall545d9962011-06-25 02:11:03 +0000483 value = EmitLoadOfLValue(LV).getScalarVal();
John McCallf85e1932011-06-15 23:02:42 +0000484
485 value = Builder.CreateBitCast(value, ConvertType(propType));
Fariborz Jahanian14086762011-03-28 23:47:18 +0000486 }
John McCallf85e1932011-06-15 23:02:42 +0000487
488 EmitReturnOfRValue(RValue::get(value), propType);
Fariborz Jahanianed1d29d2009-03-03 18:49:40 +0000489 }
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000490 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000491
492 FinishFunction();
493}
494
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000495void CodeGenFunction::GenerateObjCAtomicSetterBody(ObjCMethodDecl *OMD,
496 ObjCIvarDecl *Ivar) {
497 // objc_copyStruct (&structIvar, &Arg,
498 // sizeof (struct something), true, false);
499 llvm::Value *GetCopyStructFn =
500 CGM.getObjCRuntime().GetSetStructFunction();
501 CodeGenTypes &Types = CGM.getTypes();
502 CallArgList Args;
503 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), Ivar, 0);
504 RValue RV =
505 RValue::get(Builder.CreateBitCast(LV.getAddress(),
506 Types.ConvertType(getContext().VoidPtrTy)));
Eli Friedman04c9a492011-05-02 17:57:46 +0000507 Args.add(RV, getContext().VoidPtrTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000508 llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()];
509 llvm::Value *ArgAsPtrTy =
510 Builder.CreateBitCast(Arg,
511 Types.ConvertType(getContext().VoidPtrTy));
512 RV = RValue::get(ArgAsPtrTy);
Eli Friedman04c9a492011-05-02 17:57:46 +0000513 Args.add(RV, getContext().VoidPtrTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000514 // sizeof (Type of Ivar)
515 CharUnits Size = getContext().getTypeSizeInChars(Ivar->getType());
516 llvm::Value *SizeVal =
517 llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy),
518 Size.getQuantity());
Eli Friedman04c9a492011-05-02 17:57:46 +0000519 Args.add(RValue::get(SizeVal), getContext().LongTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000520 llvm::Value *True =
521 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
Eli Friedman04c9a492011-05-02 17:57:46 +0000522 Args.add(RValue::get(True), getContext().BoolTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000523 llvm::Value *False =
524 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0);
Eli Friedman04c9a492011-05-02 17:57:46 +0000525 Args.add(RValue::get(False), getContext().BoolTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000526 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
527 FunctionType::ExtInfo()),
528 GetCopyStructFn, ReturnValueSlot(), Args);
529}
530
Fariborz Jahanian01cb3072011-04-06 16:05:26 +0000531static bool
532IvarAssignHasTrvialAssignment(const ObjCPropertyImplDecl *PID,
533 QualType IvarT) {
534 bool HasTrvialAssignment = true;
535 if (PID->getSetterCXXAssignment()) {
536 const CXXRecordDecl *classDecl = IvarT->getAsCXXRecordDecl();
537 HasTrvialAssignment =
538 (!classDecl || classDecl->hasTrivialCopyAssignment());
539 }
540 return HasTrvialAssignment;
541}
542
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000543/// GenerateObjCSetter - Generate an Objective-C property setter
Steve Naroff489034c2009-01-10 22:55:25 +0000544/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
545/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000546void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
547 const ObjCPropertyImplDecl *PID) {
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000548 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000549 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
550 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
551 assert(OMD && "Invalid call to generate setter (empty method)");
Devang Patel8d3f8972011-05-19 23:37:41 +0000552 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Fariborz Jahanian1d3a61a2011-04-05 21:41:23 +0000553 const llvm::Triple &Triple = getContext().Target.getTriple();
554 QualType IVART = Ivar->getType();
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000555 bool IsCopy = PD->getSetterKind() == ObjCPropertyDecl::Copy;
Mike Stump1eb44332009-09-09 15:08:12 +0000556 bool IsAtomic =
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000557 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
558
559 // Determine if we should use an objc_setProperty call for
560 // this. Properties with 'copy' semantics always use it, as do
561 // non-atomic properties with 'release' semantics as long as we are
562 // not in gc-only mode.
563 if (IsCopy ||
564 (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
565 PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000566 llvm::Value *SetPropertyFn =
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000567 CGM.getObjCRuntime().GetPropertySetFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000569 if (!SetPropertyFn) {
570 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
571 FinishFunction();
572 return;
573 }
Mike Stump1eb44332009-09-09 15:08:12 +0000574
575 // Emit objc_setProperty((id) self, _cmd, offset, arg,
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000576 // <is-atomic>, <is-copy>).
577 // FIXME: Can't this be simpler? This might even be worse than the
578 // corresponding gcc code.
579 CodeGenTypes &Types = CGM.getTypes();
580 ValueDecl *Cmd = OMD->getCmdDecl();
581 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
582 QualType IdTy = getContext().getObjCIdType();
Mike Stump1eb44332009-09-09 15:08:12 +0000583 llvm::Value *SelfAsId =
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000584 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000585 llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
Chris Lattner89951a82009-02-20 18:43:26 +0000586 llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()];
Mike Stump1eb44332009-09-09 15:08:12 +0000587 llvm::Value *ArgAsId =
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000588 Builder.CreateBitCast(Builder.CreateLoad(Arg, "arg"),
589 Types.ConvertType(IdTy));
590 llvm::Value *True =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000591 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000592 llvm::Value *False =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000593 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0);
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000594 CallArgList Args;
Eli Friedman04c9a492011-05-02 17:57:46 +0000595 Args.add(RValue::get(SelfAsId), IdTy);
596 Args.add(RValue::get(CmdVal), Cmd->getType());
597 Args.add(RValue::get(Offset), getContext().getPointerDiffType());
598 Args.add(RValue::get(ArgAsId), IdTy);
599 Args.add(RValue::get(IsAtomic ? True : False), getContext().BoolTy);
600 Args.add(RValue::get(IsCopy ? True : False), getContext().BoolTy);
Mike Stumpf5408fe2009-05-16 07:57:57 +0000601 // FIXME: We shouldn't need to get the function info here, the runtime
602 // already should have computed it to build the function.
John McCall04a67a62010-02-05 21:31:56 +0000603 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000604 FunctionType::ExtInfo()),
605 SetPropertyFn,
Anders Carlssonf3c47c92009-12-24 19:25:24 +0000606 ReturnValueSlot(), Args);
Fariborz Jahanian1d3a61a2011-04-05 21:41:23 +0000607 } else if (IsAtomic && hasAggregateLLVMType(IVART) &&
608 !IVART->isAnyComplexType() &&
Fariborz Jahanian01cb3072011-04-06 16:05:26 +0000609 IvarAssignHasTrvialAssignment(PID, IVART) &&
Fariborz Jahanian1d3a61a2011-04-05 21:41:23 +0000610 ((Triple.getArch() == llvm::Triple::x86 &&
611 (getContext().getTypeSizeInChars(IVART)
612 > CharUnits::fromQuantity(4))) ||
613 (Triple.getArch() == llvm::Triple::x86_64 &&
614 (getContext().getTypeSizeInChars(IVART)
615 > CharUnits::fromQuantity(8))))
David Chisnall8fac25d2010-12-26 22:13:16 +0000616 && CGM.getObjCRuntime().GetSetStructFunction()) {
Fariborz Jahanian1d3a61a2011-04-05 21:41:23 +0000617 // objc_copyStruct (&structIvar, &Arg,
618 // sizeof (struct something), true, false);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000619 GenerateObjCAtomicSetterBody(OMD, Ivar);
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000620 } else if (PID->getSetterCXXAssignment()) {
John McCall2a416372010-12-05 02:00:02 +0000621 EmitIgnoredExpr(PID->getSetterCXXAssignment());
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000622 } else {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000623 if (IsAtomic &&
624 IVART->isScalarType() &&
625 (Triple.getArch() == llvm::Triple::arm ||
626 Triple.getArch() == llvm::Triple::thumb) &&
627 (getContext().getTypeSizeInChars(IVART)
628 > CharUnits::fromQuantity(4)) &&
629 CGM.getObjCRuntime().GetGetStructFunction()) {
630 GenerateObjCAtomicSetterBody(OMD, Ivar);
631 }
Fariborz Jahanian1d3a61a2011-04-05 21:41:23 +0000632 else if (IsAtomic &&
633 (IVART->isScalarType() && !IVART->isRealFloatingType()) &&
634 Triple.getArch() == llvm::Triple::x86 &&
635 (getContext().getTypeSizeInChars(IVART)
636 > CharUnits::fromQuantity(4)) &&
637 CGM.getObjCRuntime().GetGetStructFunction()) {
638 GenerateObjCAtomicSetterBody(OMD, Ivar);
639 }
640 else if (IsAtomic &&
641 (IVART->isScalarType() && !IVART->isRealFloatingType()) &&
642 Triple.getArch() == llvm::Triple::x86_64 &&
643 (getContext().getTypeSizeInChars(IVART)
644 > CharUnits::fromQuantity(8)) &&
645 CGM.getObjCRuntime().GetGetStructFunction()) {
646 GenerateObjCAtomicSetterBody(OMD, Ivar);
647 }
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000648 else {
649 // FIXME: Find a clean way to avoid AST node creation.
Devang Patel8d3f8972011-05-19 23:37:41 +0000650 SourceLocation Loc = PID->getLocStart();
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000651 ValueDecl *Self = OMD->getSelfDecl();
652 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
653 DeclRefExpr Base(Self, Self->getType(), VK_RValue, Loc);
654 ParmVarDecl *ArgDecl = *OMD->param_begin();
Fariborz Jahanian14086762011-03-28 23:47:18 +0000655 QualType T = ArgDecl->getType();
656 if (T->isReferenceType())
657 T = cast<ReferenceType>(T)->getPointeeType();
658 DeclRefExpr Arg(ArgDecl, T, VK_LValue, Loc);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000659 ObjCIvarRefExpr IvarRef(Ivar, Ivar->getType(), Loc, &Base, true, true);
Daniel Dunbar45e84232009-10-27 19:21:30 +0000660
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000661 // The property type can differ from the ivar type in some situations with
662 // Objective-C pointer types, we can always bit cast the RHS in these cases.
663 if (getContext().getCanonicalType(Ivar->getType()) !=
664 getContext().getCanonicalType(ArgDecl->getType())) {
665 ImplicitCastExpr ArgCasted(ImplicitCastExpr::OnStack,
666 Ivar->getType(), CK_BitCast, &Arg,
667 VK_RValue);
668 BinaryOperator Assign(&IvarRef, &ArgCasted, BO_Assign,
669 Ivar->getType(), VK_RValue, OK_Ordinary, Loc);
670 EmitStmt(&Assign);
671 } else {
672 BinaryOperator Assign(&IvarRef, &Arg, BO_Assign,
673 Ivar->getType(), VK_RValue, OK_Ordinary, Loc);
674 EmitStmt(&Assign);
675 }
Daniel Dunbar45e84232009-10-27 19:21:30 +0000676 }
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000677 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000678
679 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +0000680}
681
John McCalle81ac692011-03-22 07:05:39 +0000682namespace {
John McCall9928c482011-07-12 16:41:08 +0000683 struct DestroyIvar : EHScopeStack::Cleanup {
684 private:
685 llvm::Value *addr;
John McCalle81ac692011-03-22 07:05:39 +0000686 const ObjCIvarDecl *ivar;
John McCall9928c482011-07-12 16:41:08 +0000687 CodeGenFunction::Destroyer &destroyer;
688 bool useEHCleanupForArray;
689 public:
690 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
691 CodeGenFunction::Destroyer *destroyer,
692 bool useEHCleanupForArray)
693 : addr(addr), ivar(ivar), destroyer(*destroyer),
694 useEHCleanupForArray(useEHCleanupForArray) {}
John McCalle81ac692011-03-22 07:05:39 +0000695
John McCallad346f42011-07-12 20:27:29 +0000696 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +0000697 LValue lvalue
698 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
699 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +0000700 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCalle81ac692011-03-22 07:05:39 +0000701 }
702 };
703}
704
John McCall9928c482011-07-12 16:41:08 +0000705/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
706static void destroyARCStrongWithStore(CodeGenFunction &CGF,
707 llvm::Value *addr,
708 QualType type) {
709 llvm::Value *null = getNullForVariable(addr);
710 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
711}
John McCallf85e1932011-06-15 23:02:42 +0000712
John McCalle81ac692011-03-22 07:05:39 +0000713static void emitCXXDestructMethod(CodeGenFunction &CGF,
714 ObjCImplementationDecl *impl) {
715 CodeGenFunction::RunCleanupsScope scope(CGF);
716
717 llvm::Value *self = CGF.LoadObjCSelf();
718
719 ObjCInterfaceDecl *iface
720 = const_cast<ObjCInterfaceDecl*>(impl->getClassInterface());
721 for (ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
722 ivar; ivar = ivar->getNextIvar()) {
723 QualType type = ivar->getType();
724
John McCalle81ac692011-03-22 07:05:39 +0000725 // Check whether the ivar is a destructible type.
John McCall9928c482011-07-12 16:41:08 +0000726 QualType::DestructionKind dtorKind = type.isDestructedType();
727 if (!dtorKind) continue;
John McCalle81ac692011-03-22 07:05:39 +0000728
John McCall9928c482011-07-12 16:41:08 +0000729 CodeGenFunction::Destroyer *destroyer = 0;
John McCalle81ac692011-03-22 07:05:39 +0000730
John McCall9928c482011-07-12 16:41:08 +0000731 // Use a call to objc_storeStrong to destroy strong ivars, for the
732 // general benefit of the tools.
733 if (dtorKind == QualType::DK_objc_strong_lifetime) {
734 destroyer = &destroyARCStrongWithStore;
John McCallf85e1932011-06-15 23:02:42 +0000735
John McCall9928c482011-07-12 16:41:08 +0000736 // Otherwise use the default for the destruction kind.
737 } else {
738 destroyer = &CGF.getDestroyer(dtorKind);
John McCalle81ac692011-03-22 07:05:39 +0000739 }
John McCall9928c482011-07-12 16:41:08 +0000740
741 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
742
743 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
744 cleanupKind & EHCleanup);
John McCalle81ac692011-03-22 07:05:39 +0000745 }
746
747 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
748}
749
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000750void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
751 ObjCMethodDecl *MD,
752 bool ctor) {
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000753 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Devang Patel8d3f8972011-05-19 23:37:41 +0000754 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
John McCalle81ac692011-03-22 07:05:39 +0000755
756 // Emit .cxx_construct.
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000757 if (ctor) {
John McCallf85e1932011-06-15 23:02:42 +0000758 // Suppress the final autorelease in ARC.
759 AutoreleaseResult = false;
760
John McCalle81ac692011-03-22 07:05:39 +0000761 llvm::SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
762 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
763 E = IMP->init_end(); B != E; ++B) {
764 CXXCtorInitializer *IvarInit = (*B);
Francois Pichet00eb3f92010-12-04 09:14:42 +0000765 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000766 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian9b4d4fc2010-04-28 22:30:33 +0000767 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
768 LoadObjCSelf(), Ivar, 0);
John McCall558d2ab2010-09-15 10:14:12 +0000769 EmitAggExpr(IvarInit->getInit(), AggValueSlot::forLValue(LV, true));
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000770 }
771 // constructor returns 'self'.
772 CodeGenTypes &Types = CGM.getTypes();
773 QualType IdTy(CGM.getContext().getObjCIdType());
774 llvm::Value *SelfAsId =
775 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
776 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCalle81ac692011-03-22 07:05:39 +0000777
778 // Emit .cxx_destruct.
Chandler Carruthbc397cf2010-05-06 00:20:39 +0000779 } else {
John McCalle81ac692011-03-22 07:05:39 +0000780 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000781 }
782 FinishFunction();
783}
784
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000785bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
786 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
787 it++; it++;
788 const ABIArgInfo &AI = it->info;
789 // FIXME. Is this sufficient check?
790 return (AI.getKind() == ABIArgInfo::Indirect);
791}
792
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000793bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
794 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
795 return false;
796 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
797 return FDTTy->getDecl()->hasObjectMember();
798 return false;
799}
800
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000801llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000802 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
803 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner41110242008-06-17 18:05:57 +0000804}
805
Fariborz Jahanian45012a72009-02-03 00:09:52 +0000806QualType CodeGenFunction::TypeOfSelfObject() {
807 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
808 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff14108da2009-07-10 23:34:53 +0000809 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
810 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanian45012a72009-02-03 00:09:52 +0000811 return PTy->getPointeeType();
812}
813
John McCalle68b9842010-12-04 03:11:00 +0000814LValue
815CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
816 // This is a special l-value that just issues sends when we load or
817 // store through it.
818
819 // For certain base kinds, we need to emit the base immediately.
820 llvm::Value *Base;
821 if (E->isSuperReceiver())
822 Base = LoadObjCSelf();
823 else if (E->isClassReceiver())
824 Base = CGM.getObjCRuntime().GetClass(Builder, E->getClassReceiver());
825 else
826 Base = EmitScalarExpr(E->getBase());
827 return LValue::MakePropertyRef(E, Base);
828}
829
830static RValue GenerateMessageSendSuper(CodeGenFunction &CGF,
831 ReturnValueSlot Return,
832 QualType ResultType,
833 Selector S,
834 llvm::Value *Receiver,
835 const CallArgList &CallArgs) {
836 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CGF.CurFuncDecl);
Fariborz Jahanianf4695572009-03-20 19:18:21 +0000837 bool isClassMessage = OMD->isClassMethod();
838 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
John McCalle68b9842010-12-04 03:11:00 +0000839 return CGF.CGM.getObjCRuntime()
840 .GenerateMessageSendSuper(CGF, Return, ResultType,
841 S, OMD->getClassInterface(),
842 isCategoryImpl, Receiver,
843 isClassMessage, CallArgs);
Fariborz Jahanianf4695572009-03-20 19:18:21 +0000844}
845
John McCall119a1c62010-12-04 02:32:38 +0000846RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
847 ReturnValueSlot Return) {
848 const ObjCPropertyRefExpr *E = LV.getPropertyRefExpr();
Fariborz Jahanian68af13f2011-03-30 16:11:20 +0000849 QualType ResultType = E->getGetterResultType();
John McCall12f78a62010-12-02 01:19:52 +0000850 Selector S;
Douglas Gregor926df6c2011-06-11 01:09:30 +0000851 const ObjCMethodDecl *method;
John McCall12f78a62010-12-02 01:19:52 +0000852 if (E->isExplicitProperty()) {
853 const ObjCPropertyDecl *Property = E->getExplicitProperty();
854 S = Property->getGetterName();
Douglas Gregor926df6c2011-06-11 01:09:30 +0000855 method = Property->getGetterMethodDecl();
Mike Stumpb3589f42009-07-30 22:28:39 +0000856 } else {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000857 method = E->getImplicitPropertyGetter();
858 S = method->getSelector();
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000859 }
John McCall12f78a62010-12-02 01:19:52 +0000860
John McCall119a1c62010-12-04 02:32:38 +0000861 llvm::Value *Receiver = LV.getPropertyRefBaseAddr();
John McCalle68b9842010-12-04 03:11:00 +0000862
John McCallf85e1932011-06-15 23:02:42 +0000863 if (CGM.getLangOptions().ObjCAutoRefCount) {
864 QualType receiverType;
865 if (E->isSuperReceiver())
866 receiverType = E->getSuperReceiverType();
867 else if (E->isClassReceiver())
868 receiverType = getContext().getObjCClassType();
869 else
870 receiverType = E->getBase()->getType();
871 }
872
John McCalle68b9842010-12-04 03:11:00 +0000873 // Accesses to 'super' follow a different code path.
874 if (E->isSuperReceiver())
Douglas Gregor926df6c2011-06-11 01:09:30 +0000875 return AdjustRelatedResultType(*this, E, method,
876 GenerateMessageSendSuper(*this, Return,
877 ResultType,
878 S, Receiver,
879 CallArgList()));
John McCall119a1c62010-12-04 02:32:38 +0000880 const ObjCInterfaceDecl *ReceiverClass
881 = (E->isClassReceiver() ? E->getClassReceiver() : 0);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000882 return AdjustRelatedResultType(*this, E, method,
John McCallf85e1932011-06-15 23:02:42 +0000883 CGM.getObjCRuntime().
884 GenerateMessageSend(*this, Return, ResultType, S,
885 Receiver, CallArgList(), ReceiverClass));
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000886}
887
John McCall119a1c62010-12-04 02:32:38 +0000888void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
889 LValue Dst) {
890 const ObjCPropertyRefExpr *E = Dst.getPropertyRefExpr();
John McCall12f78a62010-12-02 01:19:52 +0000891 Selector S = E->getSetterSelector();
Fariborz Jahanian68af13f2011-03-30 16:11:20 +0000892 QualType ArgType = E->getSetterArgType();
893
Fariborz Jahanianb19c76e2011-02-08 22:33:23 +0000894 // FIXME. Other than scalars, AST is not adequate for setter and
895 // getter type mismatches which require conversion.
896 if (Src.isScalar()) {
897 llvm::Value *SrcVal = Src.getScalarVal();
898 QualType DstType = getContext().getCanonicalType(ArgType);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000899 llvm::Type *DstTy = ConvertType(DstType);
Fariborz Jahanianb19c76e2011-02-08 22:33:23 +0000900 if (SrcVal->getType() != DstTy)
901 Src =
902 RValue::get(EmitScalarConversion(SrcVal, E->getType(), DstType));
903 }
904
John McCalle68b9842010-12-04 03:11:00 +0000905 CallArgList Args;
Eli Friedman04c9a492011-05-02 17:57:46 +0000906 Args.add(Src, ArgType);
John McCalle68b9842010-12-04 03:11:00 +0000907
908 llvm::Value *Receiver = Dst.getPropertyRefBaseAddr();
909 QualType ResultType = getContext().VoidTy;
910
John McCall12f78a62010-12-02 01:19:52 +0000911 if (E->isSuperReceiver()) {
John McCalle68b9842010-12-04 03:11:00 +0000912 GenerateMessageSendSuper(*this, ReturnValueSlot(),
913 ResultType, S, Receiver, Args);
John McCall12f78a62010-12-02 01:19:52 +0000914 return;
915 }
916
John McCall119a1c62010-12-04 02:32:38 +0000917 const ObjCInterfaceDecl *ReceiverClass
918 = (E->isClassReceiver() ? E->getClassReceiver() : 0);
John McCall12f78a62010-12-02 01:19:52 +0000919
John McCall12f78a62010-12-02 01:19:52 +0000920 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
John McCalle68b9842010-12-04 03:11:00 +0000921 ResultType, S, Receiver, Args,
922 ReceiverClass);
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000923}
924
Chris Lattner74391b42009-03-22 21:03:39 +0000925void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump1eb44332009-09-09 15:08:12 +0000926 llvm::Constant *EnumerationMutationFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000927 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000928
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000929 if (!EnumerationMutationFn) {
930 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
931 return;
932 }
933
Devang Patelbcbd03a2011-01-19 01:36:36 +0000934 CGDebugInfo *DI = getDebugInfo();
935 if (DI) {
936 DI->setLocation(S.getSourceRange().getBegin());
937 DI->EmitRegionStart(Builder);
938 }
939
Devang Patel9d99f2d2011-06-13 23:15:32 +0000940 // The local variable comes into scope immediately.
941 AutoVarEmission variable = AutoVarEmission::invalid();
942 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
943 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
944
John McCalld88687f2011-01-07 01:49:06 +0000945 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
946 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Anders Carlssonf484c312008-08-31 02:33:12 +0000948 // Fast enumeration state.
949 QualType StateTy = getContext().getObjCFastEnumerationStateType();
Daniel Dunbar195337d2010-02-09 02:48:28 +0000950 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlsson1884eb02010-05-22 17:35:42 +0000951 EmitNullInitialization(StatePtr, StateTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000952
Anders Carlssonf484c312008-08-31 02:33:12 +0000953 // Number of elements in the items array.
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000954 static const unsigned NumItems = 16;
Mike Stump1eb44332009-09-09 15:08:12 +0000955
John McCalld88687f2011-01-07 01:49:06 +0000956 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramerad468862010-03-30 11:36:44 +0000957 IdentifierInfo *II[] = {
958 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
959 &CGM.getContext().Idents.get("objects"),
960 &CGM.getContext().Idents.get("count")
961 };
962 Selector FastEnumSel =
963 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlssonf484c312008-08-31 02:33:12 +0000964
965 QualType ItemsTy =
966 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +0000967 llvm::APInt(32, NumItems),
Anders Carlssonf484c312008-08-31 02:33:12 +0000968 ArrayType::Normal, 0);
Daniel Dunbar195337d2010-02-09 02:48:28 +0000969 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +0000970
John McCalld88687f2011-01-07 01:49:06 +0000971 // Emit the collection pointer.
Anders Carlssonf484c312008-08-31 02:33:12 +0000972 llvm::Value *Collection = EmitScalarExpr(S.getCollection());
Mike Stump1eb44332009-09-09 15:08:12 +0000973
John McCalld88687f2011-01-07 01:49:06 +0000974 // Send it our message:
Anders Carlssonf484c312008-08-31 02:33:12 +0000975 CallArgList Args;
John McCalld88687f2011-01-07 01:49:06 +0000976
977 // The first argument is a temporary of the enumeration-state type.
Eli Friedman04c9a492011-05-02 17:57:46 +0000978 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000979
John McCalld88687f2011-01-07 01:49:06 +0000980 // The second argument is a temporary array with space for NumItems
981 // pointers. We'll actually be loading elements from the array
982 // pointer written into the control state; this buffer is so that
983 // collections that *aren't* backed by arrays can still queue up
984 // batches of elements.
Eli Friedman04c9a492011-05-02 17:57:46 +0000985 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000986
John McCalld88687f2011-01-07 01:49:06 +0000987 // The third argument is the capacity of that temporary array.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000988 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000989 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman04c9a492011-05-02 17:57:46 +0000990 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000991
John McCalld88687f2011-01-07 01:49:06 +0000992 // Start the enumeration.
Mike Stump1eb44332009-09-09 15:08:12 +0000993 RValue CountRV =
John McCallef072fd2010-05-22 01:48:05 +0000994 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +0000995 getContext().UnsignedLongTy,
996 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000997 Collection, Args);
Anders Carlssonf484c312008-08-31 02:33:12 +0000998
John McCalld88687f2011-01-07 01:49:06 +0000999 // The initial number of objects that were returned in the buffer.
1000 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump1eb44332009-09-09 15:08:12 +00001001
John McCalld88687f2011-01-07 01:49:06 +00001002 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1003 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump1eb44332009-09-09 15:08:12 +00001004
John McCalld88687f2011-01-07 01:49:06 +00001005 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlssonf484c312008-08-31 02:33:12 +00001006
John McCalld88687f2011-01-07 01:49:06 +00001007 // If the limit pointer was zero to begin with, the collection is
1008 // empty; skip all this.
1009 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1010 EmptyBB, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001011
John McCalld88687f2011-01-07 01:49:06 +00001012 // Otherwise, initialize the loop.
1013 EmitBlock(LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001014
John McCalld88687f2011-01-07 01:49:06 +00001015 // Save the initial mutations value. This is the value at an
1016 // address that was written into the state object by
1017 // countByEnumeratingWithState:objects:count:.
Mike Stump1eb44332009-09-09 15:08:12 +00001018 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001019 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001020 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001021 "mutationsptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001022
John McCalld88687f2011-01-07 01:49:06 +00001023 llvm::Value *initialMutations =
1024 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump1eb44332009-09-09 15:08:12 +00001025
John McCalld88687f2011-01-07 01:49:06 +00001026 // Start looping. This is the point we return to whenever we have a
1027 // fresh, non-empty batch of objects.
1028 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1029 EmitBlock(LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001030
John McCalld88687f2011-01-07 01:49:06 +00001031 // The current index into the buffer.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001032 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCalld88687f2011-01-07 01:49:06 +00001033 index->addIncoming(zero, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001034
John McCalld88687f2011-01-07 01:49:06 +00001035 // The current buffer size.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001036 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCalld88687f2011-01-07 01:49:06 +00001037 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001038
John McCalld88687f2011-01-07 01:49:06 +00001039 // Check whether the mutations value has changed from where it was
1040 // at start. StateMutationsPtr should actually be invariant between
1041 // refreshes.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001042 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCalld88687f2011-01-07 01:49:06 +00001043 llvm::Value *currentMutations
1044 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001045
John McCalld88687f2011-01-07 01:49:06 +00001046 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman361cf982011-03-02 22:39:34 +00001047 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump1eb44332009-09-09 15:08:12 +00001048
John McCalld88687f2011-01-07 01:49:06 +00001049 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1050 WasNotMutatedBB, WasMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001051
John McCalld88687f2011-01-07 01:49:06 +00001052 // If so, call the enumeration-mutation function.
1053 EmitBlock(WasMutatedBB);
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001054 llvm::Value *V =
Mike Stump1eb44332009-09-09 15:08:12 +00001055 Builder.CreateBitCast(Collection,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001056 ConvertType(getContext().getObjCIdType()),
1057 "tmp");
Daniel Dunbar2b2105e2009-02-03 23:55:40 +00001058 CallArgList Args2;
Eli Friedman04c9a492011-05-02 17:57:46 +00001059 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stumpf5408fe2009-05-16 07:57:57 +00001060 // FIXME: We shouldn't need to get the function info here, the runtime already
1061 // should have computed it to build the function.
John McCall04a67a62010-02-05 21:31:56 +00001062 EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2,
Rafael Espindola264ba482010-03-30 20:24:48 +00001063 FunctionType::ExtInfo()),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001064 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump1eb44332009-09-09 15:08:12 +00001065
John McCalld88687f2011-01-07 01:49:06 +00001066 // Otherwise, or if the mutation function returns, just continue.
1067 EmitBlock(WasNotMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001068
John McCalld88687f2011-01-07 01:49:06 +00001069 // Initialize the element variable.
1070 RunCleanupsScope elementVariableScope(*this);
John McCall57b3b6a2011-02-22 07:16:58 +00001071 bool elementIsVariable;
John McCalld88687f2011-01-07 01:49:06 +00001072 LValue elementLValue;
1073 QualType elementType;
1074 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall57b3b6a2011-02-22 07:16:58 +00001075 // Initialize the variable, in case it's a __block variable or something.
1076 EmitAutoVarInit(variable);
John McCalld88687f2011-01-07 01:49:06 +00001077
John McCall57b3b6a2011-02-22 07:16:58 +00001078 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCalld88687f2011-01-07 01:49:06 +00001079 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), D->getType(),
1080 VK_LValue, SourceLocation());
1081 elementLValue = EmitLValue(&tempDRE);
1082 elementType = D->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001083 elementIsVariable = true;
John McCall7acddac2011-06-17 06:42:21 +00001084
1085 if (D->isARCPseudoStrong())
1086 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCalld88687f2011-01-07 01:49:06 +00001087 } else {
1088 elementLValue = LValue(); // suppress warning
1089 elementType = cast<Expr>(S.getElement())->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001090 elementIsVariable = false;
John McCalld88687f2011-01-07 01:49:06 +00001091 }
Chris Lattner2acc6e32011-07-18 04:24:23 +00001092 llvm::Type *convertedElementType = ConvertType(elementType);
John McCalld88687f2011-01-07 01:49:06 +00001093
1094 // Fetch the buffer out of the enumeration state.
1095 // TODO: this pointer should actually be invariant between
1096 // refreshes, which would help us do certain loop optimizations.
Mike Stump1eb44332009-09-09 15:08:12 +00001097 llvm::Value *StateItemsPtr =
Anders Carlssonf484c312008-08-31 02:33:12 +00001098 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCalld88687f2011-01-07 01:49:06 +00001099 llvm::Value *EnumStateItems =
1100 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlssonf484c312008-08-31 02:33:12 +00001101
John McCalld88687f2011-01-07 01:49:06 +00001102 // Fetch the value at the current index from the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001103 llvm::Value *CurrentItemPtr =
John McCalld88687f2011-01-07 01:49:06 +00001104 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1105 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001106
John McCalld88687f2011-01-07 01:49:06 +00001107 // Cast that value to the right type.
1108 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1109 "currentitem");
Mike Stump1eb44332009-09-09 15:08:12 +00001110
John McCalld88687f2011-01-07 01:49:06 +00001111 // Make sure we have an l-value. Yes, this gets evaluated every
1112 // time through the loop.
John McCall7acddac2011-06-17 06:42:21 +00001113 if (!elementIsVariable) {
John McCalld88687f2011-01-07 01:49:06 +00001114 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001115 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCall7acddac2011-06-17 06:42:21 +00001116 } else {
1117 EmitScalarInit(CurrentItem, elementLValue);
1118 }
Mike Stump1eb44332009-09-09 15:08:12 +00001119
John McCall57b3b6a2011-02-22 07:16:58 +00001120 // If we do have an element variable, this assignment is the end of
1121 // its initialization.
1122 if (elementIsVariable)
1123 EmitAutoVarCleanups(variable);
1124
John McCalld88687f2011-01-07 01:49:06 +00001125 // Perform the loop body, setting up break and continue labels.
Anders Carlssone4b6d342009-02-10 05:52:02 +00001126 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCalld88687f2011-01-07 01:49:06 +00001127 {
1128 RunCleanupsScope Scope(*this);
1129 EmitStmt(S.getBody());
1130 }
Anders Carlssonf484c312008-08-31 02:33:12 +00001131 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001132
John McCalld88687f2011-01-07 01:49:06 +00001133 // Destroy the element variable now.
1134 elementVariableScope.ForceCleanup();
1135
1136 // Check whether there are more elements.
John McCallff8e1152010-07-23 21:56:41 +00001137 EmitBlock(AfterBody.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001138
John McCalld88687f2011-01-07 01:49:06 +00001139 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanianf0906c42009-01-06 18:56:31 +00001140
John McCalld88687f2011-01-07 01:49:06 +00001141 // First we check in the local buffer.
1142 llvm::Value *indexPlusOne
1143 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlssonf484c312008-08-31 02:33:12 +00001144
John McCalld88687f2011-01-07 01:49:06 +00001145 // If we haven't overrun the buffer yet, we can continue.
1146 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1147 LoopBodyBB, FetchMoreBB);
1148
1149 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1150 count->addIncoming(count, AfterBody.getBlock());
1151
1152 // Otherwise, we have to fetch more elements.
1153 EmitBlock(FetchMoreBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001154
1155 CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001156 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001157 getContext().UnsignedLongTy,
Mike Stump1eb44332009-09-09 15:08:12 +00001158 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001159 Collection, Args);
Mike Stump1eb44332009-09-09 15:08:12 +00001160
John McCalld88687f2011-01-07 01:49:06 +00001161 // If we got a zero count, we're done.
1162 llvm::Value *refetchCount = CountRV.getScalarVal();
1163
1164 // (note that the message send might split FetchMoreBB)
1165 index->addIncoming(zero, Builder.GetInsertBlock());
1166 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1167
1168 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1169 EmptyBB, LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001170
Anders Carlssonf484c312008-08-31 02:33:12 +00001171 // No more elements.
John McCalld88687f2011-01-07 01:49:06 +00001172 EmitBlock(EmptyBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001173
John McCall57b3b6a2011-02-22 07:16:58 +00001174 if (!elementIsVariable) {
Anders Carlssonf484c312008-08-31 02:33:12 +00001175 // If the element was not a declaration, set it to be null.
1176
John McCalld88687f2011-01-07 01:49:06 +00001177 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1178 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001179 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlssonf484c312008-08-31 02:33:12 +00001180 }
1181
Devang Patelbcbd03a2011-01-19 01:36:36 +00001182 if (DI) {
1183 DI->setLocation(S.getSourceRange().getEnd());
1184 DI->EmitRegionEnd(Builder);
1185 }
1186
John McCallff8e1152010-07-23 21:56:41 +00001187 EmitBlock(LoopEnd.getBlock());
Anders Carlsson3d8400d2008-08-30 19:51:14 +00001188}
1189
Mike Stump1eb44332009-09-09 15:08:12 +00001190void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001191 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001192}
1193
Mike Stump1eb44332009-09-09 15:08:12 +00001194void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001195 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1196}
1197
Chris Lattner10cac6f2008-11-15 21:26:17 +00001198void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump1eb44332009-09-09 15:08:12 +00001199 const ObjCAtSynchronizedStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001200 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +00001201}
1202
John McCallf85e1932011-06-15 23:02:42 +00001203/// Produce the code for a CK_ObjCProduceObject. Just does a
1204/// primitive retain.
1205llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1206 llvm::Value *value) {
1207 return EmitARCRetain(type, value);
1208}
1209
1210namespace {
1211 struct CallObjCRelease : EHScopeStack::Cleanup {
1212 CallObjCRelease(QualType type, llvm::Value *ptr, llvm::Value *condition)
1213 : type(type), ptr(ptr), condition(condition) {}
1214 QualType type;
1215 llvm::Value *ptr;
1216 llvm::Value *condition;
1217
John McCallad346f42011-07-12 20:27:29 +00001218 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001219 llvm::Value *object;
1220
1221 // If we're in a conditional branch, we had to stash away in an
1222 // alloca the pointer to be released.
1223 llvm::BasicBlock *cont = 0;
1224 if (condition) {
1225 llvm::BasicBlock *release = CGF.createBasicBlock("release.yes");
1226 cont = CGF.createBasicBlock("release.cont");
1227
1228 llvm::Value *cond = CGF.Builder.CreateLoad(condition);
1229 CGF.Builder.CreateCondBr(cond, release, cont);
1230 CGF.EmitBlock(release);
1231 object = CGF.Builder.CreateLoad(ptr);
1232 } else {
1233 object = ptr;
1234 }
1235
1236 CGF.EmitARCRelease(object, /*precise*/ true);
1237
1238 if (cont) CGF.EmitBlock(cont);
1239 }
1240 };
1241}
1242
1243/// Produce the code for a CK_ObjCConsumeObject. Does a primitive
1244/// release at the end of the full-expression.
1245llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1246 llvm::Value *object) {
1247 // If we're in a conditional branch, we need to make the cleanup
1248 // conditional. FIXME: this really needs to be supported by the
1249 // environment.
1250 llvm::AllocaInst *cond;
1251 llvm::Value *ptr;
1252 if (isInConditionalBranch()) {
1253 cond = CreateTempAlloca(Builder.getInt1Ty(), "release.cond");
1254 ptr = CreateTempAlloca(object->getType(), "release.value");
1255
1256 // The alloca is false until we get here.
1257 // FIXME: er. doesn't this need to be set at the start of the condition?
1258 InitTempAlloca(cond, Builder.getFalse());
1259
1260 // Then it turns true.
1261 Builder.CreateStore(Builder.getTrue(), cond);
1262 Builder.CreateStore(object, ptr);
1263 } else {
1264 cond = 0;
1265 ptr = object;
1266 }
1267
1268 EHStack.pushCleanup<CallObjCRelease>(getARCCleanupKind(), type, ptr, cond);
1269 return object;
1270}
1271
1272llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1273 llvm::Value *value) {
1274 return EmitARCRetainAutorelease(type, value);
1275}
1276
1277
1278static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001279 llvm::FunctionType *type,
John McCallf85e1932011-06-15 23:02:42 +00001280 llvm::StringRef fnName) {
1281 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1282
1283 // In -fobjc-no-arc-runtime, emit weak references to the runtime
1284 // support library.
John McCall9f084a32011-07-06 00:26:06 +00001285 if (!CGM.getCodeGenOpts().ObjCRuntimeHasARC)
John McCallf85e1932011-06-15 23:02:42 +00001286 if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
1287 f->setLinkage(llvm::Function::ExternalWeakLinkage);
1288
1289 return fn;
1290}
1291
1292/// Perform an operation having the signature
1293/// i8* (i8*)
1294/// where a null input causes a no-op and returns null.
1295static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1296 llvm::Value *value,
1297 llvm::Constant *&fn,
1298 llvm::StringRef fnName) {
1299 if (isa<llvm::ConstantPointerNull>(value)) return value;
1300
1301 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001302 std::vector<llvm::Type*> args(1, CGF.Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001303 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001304 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1305 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1306 }
1307
1308 // Cast the argument to 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001309 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001310 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1311
1312 // Call the function.
1313 llvm::CallInst *call = CGF.Builder.CreateCall(fn, value);
1314 call->setDoesNotThrow();
1315
1316 // Cast the result back to the original type.
1317 return CGF.Builder.CreateBitCast(call, origType);
1318}
1319
1320/// Perform an operation having the following signature:
1321/// i8* (i8**)
1322static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1323 llvm::Value *addr,
1324 llvm::Constant *&fn,
1325 llvm::StringRef fnName) {
1326 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001327 std::vector<llvm::Type*> args(1, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001328 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001329 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1330 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1331 }
1332
1333 // Cast the argument to 'id*'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001334 llvm::Type *origType = addr->getType();
John McCallf85e1932011-06-15 23:02:42 +00001335 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1336
1337 // Call the function.
1338 llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr);
1339 call->setDoesNotThrow();
1340
1341 // Cast the result back to a dereference of the original type.
1342 llvm::Value *result = call;
1343 if (origType != CGF.Int8PtrPtrTy)
1344 result = CGF.Builder.CreateBitCast(result,
1345 cast<llvm::PointerType>(origType)->getElementType());
1346
1347 return result;
1348}
1349
1350/// Perform an operation having the following signature:
1351/// i8* (i8**, i8*)
1352static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1353 llvm::Value *addr,
1354 llvm::Value *value,
1355 llvm::Constant *&fn,
1356 llvm::StringRef fnName,
1357 bool ignored) {
1358 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1359 == value->getType());
1360
1361 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001362 std::vector<llvm::Type*> argTypes(2);
John McCallf85e1932011-06-15 23:02:42 +00001363 argTypes[0] = CGF.Int8PtrPtrTy;
1364 argTypes[1] = CGF.Int8PtrTy;
1365
Chris Lattner2acc6e32011-07-18 04:24:23 +00001366 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001367 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1368 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1369 }
1370
Chris Lattner2acc6e32011-07-18 04:24:23 +00001371 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001372
1373 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1374 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1375
1376 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value);
1377 result->setDoesNotThrow();
1378
1379 if (ignored) return 0;
1380
1381 return CGF.Builder.CreateBitCast(result, origType);
1382}
1383
1384/// Perform an operation having the following signature:
1385/// void (i8**, i8**)
1386static void emitARCCopyOperation(CodeGenFunction &CGF,
1387 llvm::Value *dst,
1388 llvm::Value *src,
1389 llvm::Constant *&fn,
1390 llvm::StringRef fnName) {
1391 assert(dst->getType() == src->getType());
1392
1393 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001394 std::vector<llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001395 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001396 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1397 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1398 }
1399
1400 dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy);
1401 src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy);
1402
1403 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src);
1404 result->setDoesNotThrow();
1405}
1406
1407/// Produce the code to do a retain. Based on the type, calls one of:
1408/// call i8* @objc_retain(i8* %value)
1409/// call i8* @objc_retainBlock(i8* %value)
1410llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1411 if (type->isBlockPointerType())
1412 return EmitARCRetainBlock(value);
1413 else
1414 return EmitARCRetainNonBlock(value);
1415}
1416
1417/// Retain the given object, with normal retain semantics.
1418/// call i8* @objc_retain(i8* %value)
1419llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1420 return emitARCValueOperation(*this, value,
1421 CGM.getARCEntrypoints().objc_retain,
1422 "objc_retain");
1423}
1424
1425/// Retain the given block, with _Block_copy semantics.
1426/// call i8* @objc_retainBlock(i8* %value)
1427llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value) {
1428 return emitARCValueOperation(*this, value,
1429 CGM.getARCEntrypoints().objc_retainBlock,
1430 "objc_retainBlock");
1431}
1432
1433/// Retain the given object which is the result of a function call.
1434/// call i8* @objc_retainAutoreleasedReturnValue(i8* %value)
1435///
1436/// Yes, this function name is one character away from a different
1437/// call with completely different semantics.
1438llvm::Value *
1439CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1440 // Fetch the void(void) inline asm which marks that we're going to
1441 // retain the autoreleased return value.
1442 llvm::InlineAsm *&marker
1443 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1444 if (!marker) {
1445 llvm::StringRef assembly
1446 = CGM.getTargetCodeGenInfo()
1447 .getARCRetainAutoreleasedReturnValueMarker();
1448
1449 // If we have an empty assembly string, there's nothing to do.
1450 if (assembly.empty()) {
1451
1452 // Otherwise, at -O0, build an inline asm that we're going to call
1453 // in a moment.
1454 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1455 llvm::FunctionType *type =
1456 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
1457 /*variadic*/ false);
1458
1459 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1460
1461 // If we're at -O1 and above, we don't want to litter the code
1462 // with this marker yet, so leave a breadcrumb for the ARC
1463 // optimizer to pick up.
1464 } else {
1465 llvm::NamedMDNode *metadata =
1466 CGM.getModule().getOrInsertNamedMetadata(
1467 "clang.arc.retainAutoreleasedReturnValueMarker");
1468 assert(metadata->getNumOperands() <= 1);
1469 if (metadata->getNumOperands() == 0) {
1470 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
1471 llvm::Value *args[] = { string };
1472 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), args));
1473 }
1474 }
1475 }
1476
1477 // Call the marker asm if we made one, which we do only at -O0.
1478 if (marker) Builder.CreateCall(marker);
1479
1480 return emitARCValueOperation(*this, value,
1481 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1482 "objc_retainAutoreleasedReturnValue");
1483}
1484
1485/// Release the given object.
1486/// call void @objc_release(i8* %value)
1487void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) {
1488 if (isa<llvm::ConstantPointerNull>(value)) return;
1489
1490 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1491 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001492 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001493 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001494 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1495 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1496 }
1497
1498 // Cast the argument to 'id'.
1499 value = Builder.CreateBitCast(value, Int8PtrTy);
1500
1501 // Call objc_release.
1502 llvm::CallInst *call = Builder.CreateCall(fn, value);
1503 call->setDoesNotThrow();
1504
1505 if (!precise) {
1506 llvm::SmallVector<llvm::Value*,1> args;
1507 call->setMetadata("clang.imprecise_release",
1508 llvm::MDNode::get(Builder.getContext(), args));
1509 }
1510}
1511
1512/// Store into a strong object. Always calls this:
1513/// call void @objc_storeStrong(i8** %addr, i8* %value)
1514llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
1515 llvm::Value *value,
1516 bool ignored) {
1517 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1518 == value->getType());
1519
1520 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
1521 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001522 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2acc6e32011-07-18 04:24:23 +00001523 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001524 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
1525 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
1526 }
1527
1528 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1529 llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy);
1530
1531 Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow();
1532
1533 if (ignored) return 0;
1534 return value;
1535}
1536
1537/// Store into a strong object. Sometimes calls this:
1538/// call void @objc_storeStrong(i8** %addr, i8* %value)
1539/// Other times, breaks it down into components.
John McCall545d9962011-06-25 02:11:03 +00001540llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCallf85e1932011-06-15 23:02:42 +00001541 llvm::Value *newValue,
1542 bool ignored) {
John McCall545d9962011-06-25 02:11:03 +00001543 QualType type = dst.getType();
John McCallf85e1932011-06-15 23:02:42 +00001544 bool isBlock = type->isBlockPointerType();
1545
1546 // Use a store barrier at -O0 unless this is a block type or the
1547 // lvalue is inadequately aligned.
1548 if (shouldUseFusedARCCalls() &&
1549 !isBlock &&
1550 !(dst.getAlignment() && dst.getAlignment() < PointerAlignInBytes)) {
1551 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
1552 }
1553
1554 // Otherwise, split it out.
1555
1556 // Retain the new value.
1557 newValue = EmitARCRetain(type, newValue);
1558
1559 // Read the old value.
John McCall545d9962011-06-25 02:11:03 +00001560 llvm::Value *oldValue = EmitLoadOfScalar(dst);
John McCallf85e1932011-06-15 23:02:42 +00001561
1562 // Store. We do this before the release so that any deallocs won't
1563 // see the old value.
John McCall545d9962011-06-25 02:11:03 +00001564 EmitStoreOfScalar(newValue, dst);
John McCallf85e1932011-06-15 23:02:42 +00001565
1566 // Finally, release the old value.
1567 EmitARCRelease(oldValue, /*precise*/ false);
1568
1569 return newValue;
1570}
1571
1572/// Autorelease the given object.
1573/// call i8* @objc_autorelease(i8* %value)
1574llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
1575 return emitARCValueOperation(*this, value,
1576 CGM.getARCEntrypoints().objc_autorelease,
1577 "objc_autorelease");
1578}
1579
1580/// Autorelease the given object.
1581/// call i8* @objc_autoreleaseReturnValue(i8* %value)
1582llvm::Value *
1583CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
1584 return emitARCValueOperation(*this, value,
1585 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
1586 "objc_autoreleaseReturnValue");
1587}
1588
1589/// Do a fused retain/autorelease of the given object.
1590/// call i8* @objc_retainAutoreleaseReturnValue(i8* %value)
1591llvm::Value *
1592CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
1593 return emitARCValueOperation(*this, value,
1594 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
1595 "objc_retainAutoreleaseReturnValue");
1596}
1597
1598/// Do a fused retain/autorelease of the given object.
1599/// call i8* @objc_retainAutorelease(i8* %value)
1600/// or
1601/// %retain = call i8* @objc_retainBlock(i8* %value)
1602/// call i8* @objc_autorelease(i8* %retain)
1603llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
1604 llvm::Value *value) {
1605 if (!type->isBlockPointerType())
1606 return EmitARCRetainAutoreleaseNonBlock(value);
1607
1608 if (isa<llvm::ConstantPointerNull>(value)) return value;
1609
Chris Lattner2acc6e32011-07-18 04:24:23 +00001610 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001611 value = Builder.CreateBitCast(value, Int8PtrTy);
1612 value = EmitARCRetainBlock(value);
1613 value = EmitARCAutorelease(value);
1614 return Builder.CreateBitCast(value, origType);
1615}
1616
1617/// Do a fused retain/autorelease of the given object.
1618/// call i8* @objc_retainAutorelease(i8* %value)
1619llvm::Value *
1620CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
1621 return emitARCValueOperation(*this, value,
1622 CGM.getARCEntrypoints().objc_retainAutorelease,
1623 "objc_retainAutorelease");
1624}
1625
1626/// i8* @objc_loadWeak(i8** %addr)
1627/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
1628llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
1629 return emitARCLoadOperation(*this, addr,
1630 CGM.getARCEntrypoints().objc_loadWeak,
1631 "objc_loadWeak");
1632}
1633
1634/// i8* @objc_loadWeakRetained(i8** %addr)
1635llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
1636 return emitARCLoadOperation(*this, addr,
1637 CGM.getARCEntrypoints().objc_loadWeakRetained,
1638 "objc_loadWeakRetained");
1639}
1640
1641/// i8* @objc_storeWeak(i8** %addr, i8* %value)
1642/// Returns %value.
1643llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
1644 llvm::Value *value,
1645 bool ignored) {
1646 return emitARCStoreOperation(*this, addr, value,
1647 CGM.getARCEntrypoints().objc_storeWeak,
1648 "objc_storeWeak", ignored);
1649}
1650
1651/// i8* @objc_initWeak(i8** %addr, i8* %value)
1652/// Returns %value. %addr is known to not have a current weak entry.
1653/// Essentially equivalent to:
1654/// *addr = nil; objc_storeWeak(addr, value);
1655void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
1656 // If we're initializing to null, just write null to memory; no need
1657 // to get the runtime involved. But don't do this if optimization
1658 // is enabled, because accounting for this would make the optimizer
1659 // much more complicated.
1660 if (isa<llvm::ConstantPointerNull>(value) &&
1661 CGM.getCodeGenOpts().OptimizationLevel == 0) {
1662 Builder.CreateStore(value, addr);
1663 return;
1664 }
1665
1666 emitARCStoreOperation(*this, addr, value,
1667 CGM.getARCEntrypoints().objc_initWeak,
1668 "objc_initWeak", /*ignored*/ true);
1669}
1670
1671/// void @objc_destroyWeak(i8** %addr)
1672/// Essentially objc_storeWeak(addr, nil).
1673void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
1674 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
1675 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001676 std::vector<llvm::Type*> args(1, Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001677 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001678 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1679 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
1680 }
1681
1682 // Cast the argument to 'id*'.
1683 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1684
1685 llvm::CallInst *call = Builder.CreateCall(fn, addr);
1686 call->setDoesNotThrow();
1687}
1688
1689/// void @objc_moveWeak(i8** %dest, i8** %src)
1690/// Disregards the current value in %dest. Leaves %src pointing to nothing.
1691/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
1692void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
1693 emitARCCopyOperation(*this, dst, src,
1694 CGM.getARCEntrypoints().objc_moveWeak,
1695 "objc_moveWeak");
1696}
1697
1698/// void @objc_copyWeak(i8** %dest, i8** %src)
1699/// Disregards the current value in %dest. Essentially
1700/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
1701void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
1702 emitARCCopyOperation(*this, dst, src,
1703 CGM.getARCEntrypoints().objc_copyWeak,
1704 "objc_copyWeak");
1705}
1706
1707/// Produce the code to do a objc_autoreleasepool_push.
1708/// call i8* @objc_autoreleasePoolPush(void)
1709llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
1710 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
1711 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001712 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001713 llvm::FunctionType::get(Int8PtrTy, false);
1714 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
1715 }
1716
1717 llvm::CallInst *call = Builder.CreateCall(fn);
1718 call->setDoesNotThrow();
1719
1720 return call;
1721}
1722
1723/// Produce the code to do a primitive release.
1724/// call void @objc_autoreleasePoolPop(i8* %ptr)
1725void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
1726 assert(value->getType() == Int8PtrTy);
1727
1728 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
1729 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001730 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001731 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001732 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1733
1734 // We don't want to use a weak import here; instead we should not
1735 // fall into this path.
1736 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
1737 }
1738
1739 llvm::CallInst *call = Builder.CreateCall(fn, value);
1740 call->setDoesNotThrow();
1741}
1742
1743/// Produce the code to do an MRR version objc_autoreleasepool_push.
1744/// Which is: [[NSAutoreleasePool alloc] init];
1745/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
1746/// init is declared as: - (id) init; in its NSObject super class.
1747///
1748llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
1749 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
1750 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder);
1751 // [NSAutoreleasePool alloc]
1752 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
1753 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
1754 CallArgList Args;
1755 RValue AllocRV =
1756 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
1757 getContext().getObjCIdType(),
1758 AllocSel, Receiver, Args);
1759
1760 // [Receiver init]
1761 Receiver = AllocRV.getScalarVal();
1762 II = &CGM.getContext().Idents.get("init");
1763 Selector InitSel = getContext().Selectors.getSelector(0, &II);
1764 RValue InitRV =
1765 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
1766 getContext().getObjCIdType(),
1767 InitSel, Receiver, Args);
1768 return InitRV.getScalarVal();
1769}
1770
1771/// Produce the code to do a primitive release.
1772/// [tmp drain];
1773void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
1774 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
1775 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
1776 CallArgList Args;
1777 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1778 getContext().VoidTy, DrainSel, Arg, Args);
1779}
1780
John McCallbdc4d802011-07-09 01:37:26 +00001781void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
1782 llvm::Value *addr,
1783 QualType type) {
1784 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
1785 CGF.EmitARCRelease(ptr, /*precise*/ true);
1786}
1787
1788void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
1789 llvm::Value *addr,
1790 QualType type) {
1791 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
1792 CGF.EmitARCRelease(ptr, /*precise*/ false);
1793}
1794
1795void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
1796 llvm::Value *addr,
1797 QualType type) {
1798 CGF.EmitARCDestroyWeak(addr);
1799}
1800
John McCallf85e1932011-06-15 23:02:42 +00001801namespace {
John McCallf85e1932011-06-15 23:02:42 +00001802 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
1803 llvm::Value *Token;
1804
1805 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
1806
John McCallad346f42011-07-12 20:27:29 +00001807 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001808 CGF.EmitObjCAutoreleasePoolPop(Token);
1809 }
1810 };
1811 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
1812 llvm::Value *Token;
1813
1814 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
1815
John McCallad346f42011-07-12 20:27:29 +00001816 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001817 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
1818 }
1819 };
1820}
1821
1822void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
1823 if (CGM.getLangOptions().ObjCAutoRefCount)
1824 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
1825 else
1826 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
1827}
1828
John McCallf85e1932011-06-15 23:02:42 +00001829static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
1830 LValue lvalue,
1831 QualType type) {
1832 switch (type.getObjCLifetime()) {
1833 case Qualifiers::OCL_None:
1834 case Qualifiers::OCL_ExplicitNone:
1835 case Qualifiers::OCL_Strong:
1836 case Qualifiers::OCL_Autoreleasing:
John McCall545d9962011-06-25 02:11:03 +00001837 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(),
John McCallf85e1932011-06-15 23:02:42 +00001838 false);
1839
1840 case Qualifiers::OCL_Weak:
1841 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
1842 true);
1843 }
1844
1845 llvm_unreachable("impossible lifetime!");
1846 return TryEmitResult();
1847}
1848
1849static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
1850 const Expr *e) {
1851 e = e->IgnoreParens();
1852 QualType type = e->getType();
1853
1854 // As a very special optimization, in ARC++, if the l-value is the
1855 // result of a non-volatile assignment, do a simple retain of the
1856 // result of the call to objc_storeWeak instead of reloading.
1857 if (CGF.getLangOptions().CPlusPlus &&
1858 !type.isVolatileQualified() &&
1859 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
1860 isa<BinaryOperator>(e) &&
1861 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
1862 return TryEmitResult(CGF.EmitScalarExpr(e), false);
1863
1864 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
1865}
1866
1867static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
1868 llvm::Value *value);
1869
1870/// Given that the given expression is some sort of call (which does
1871/// not return retained), emit a retain following it.
1872static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
1873 llvm::Value *value = CGF.EmitScalarExpr(e);
1874 return emitARCRetainAfterCall(CGF, value);
1875}
1876
1877static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
1878 llvm::Value *value) {
1879 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
1880 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
1881
1882 // Place the retain immediately following the call.
1883 CGF.Builder.SetInsertPoint(call->getParent(),
1884 ++llvm::BasicBlock::iterator(call));
1885 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1886
1887 CGF.Builder.restoreIP(ip);
1888 return value;
1889 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
1890 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
1891
1892 // Place the retain at the beginning of the normal destination block.
1893 llvm::BasicBlock *BB = invoke->getNormalDest();
1894 CGF.Builder.SetInsertPoint(BB, BB->begin());
1895 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1896
1897 CGF.Builder.restoreIP(ip);
1898 return value;
1899
1900 // Bitcasts can arise because of related-result returns. Rewrite
1901 // the operand.
1902 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
1903 llvm::Value *operand = bitcast->getOperand(0);
1904 operand = emitARCRetainAfterCall(CGF, operand);
1905 bitcast->setOperand(0, operand);
1906 return bitcast;
1907
1908 // Generic fall-back case.
1909 } else {
1910 // Retain using the non-block variant: we never need to do a copy
1911 // of a block that's been returned to us.
1912 return CGF.EmitARCRetainNonBlock(value);
1913 }
1914}
1915
1916static TryEmitResult
1917tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCallf85e1932011-06-15 23:02:42 +00001918 // The desired result type, if it differs from the type of the
1919 // ultimate opaque expression.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001920 llvm::Type *resultType = 0;
John McCallf85e1932011-06-15 23:02:42 +00001921
Douglas Gregord1bd98a2011-06-22 16:32:26 +00001922 // If we're loading retained from a __strong xvalue, we can avoid
1923 // an extra retain/release pair by zeroing out the source of this
1924 // "move" operation.
John McCalldf7b0912011-06-25 02:26:44 +00001925 if (e->isXValue() && !e->getType().isConstQualified() &&
Douglas Gregord1bd98a2011-06-22 16:32:26 +00001926 e->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
1927 // Emit the lvalue
1928 LValue lv = CGF.EmitLValue(e);
1929
1930 // Load the object pointer and cast it to the appropriate type.
1931 QualType exprType = e->getType();
John McCall545d9962011-06-25 02:11:03 +00001932 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal();
Douglas Gregord1bd98a2011-06-22 16:32:26 +00001933
1934 if (resultType)
1935 result = CGF.Builder.CreateBitCast(result, resultType);
1936
1937 // Set the source pointer to NULL.
1938 llvm::Value *null
1939 = llvm::ConstantPointerNull::get(
1940 cast<llvm::PointerType>(CGF.ConvertType(exprType)));
John McCall545d9962011-06-25 02:11:03 +00001941 CGF.EmitStoreOfScalar(null, lv);
Douglas Gregord1bd98a2011-06-22 16:32:26 +00001942
1943 return TryEmitResult(result, true);
1944 }
1945
John McCallf85e1932011-06-15 23:02:42 +00001946 while (true) {
1947 e = e->IgnoreParens();
1948
1949 // There's a break at the end of this if-chain; anything
1950 // that wants to keep looping has to explicitly continue.
1951 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
1952 switch (ce->getCastKind()) {
1953 // No-op casts don't change the type, so we just ignore them.
1954 case CK_NoOp:
1955 e = ce->getSubExpr();
1956 continue;
1957
1958 case CK_LValueToRValue: {
1959 TryEmitResult loadResult
1960 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
1961 if (resultType) {
1962 llvm::Value *value = loadResult.getPointer();
1963 value = CGF.Builder.CreateBitCast(value, resultType);
1964 loadResult.setPointer(value);
1965 }
1966 return loadResult;
1967 }
1968
1969 // These casts can change the type, so remember that and
1970 // soldier on. We only need to remember the outermost such
1971 // cast, though.
1972 case CK_AnyPointerToObjCPointerCast:
1973 case CK_AnyPointerToBlockPointerCast:
1974 case CK_BitCast:
1975 if (!resultType)
1976 resultType = CGF.ConvertType(ce->getType());
1977 e = ce->getSubExpr();
1978 assert(e->getType()->hasPointerRepresentation());
1979 continue;
1980
1981 // For consumptions, just emit the subexpression and thus elide
1982 // the retain/release pair.
1983 case CK_ObjCConsumeObject: {
1984 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
1985 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
1986 return TryEmitResult(result, true);
1987 }
1988
John McCall7e5e5f42011-07-07 06:58:02 +00001989 // For reclaims, emit the subexpression as a retained call and
1990 // skip the consumption.
1991 case CK_ObjCReclaimReturnedObject: {
1992 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
1993 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
1994 return TryEmitResult(result, true);
1995 }
1996
John McCallf85e1932011-06-15 23:02:42 +00001997 case CK_GetObjCProperty: {
1998 llvm::Value *result = emitARCRetainCall(CGF, ce);
1999 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2000 return TryEmitResult(result, true);
2001 }
2002
2003 default:
2004 break;
2005 }
2006
2007 // Skip __extension__.
2008 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2009 if (op->getOpcode() == UO_Extension) {
2010 e = op->getSubExpr();
2011 continue;
2012 }
2013
2014 // For calls and message sends, use the retained-call logic.
2015 // Delegate inits are a special case in that they're the only
2016 // returns-retained expression that *isn't* surrounded by
2017 // a consume.
2018 } else if (isa<CallExpr>(e) ||
2019 (isa<ObjCMessageExpr>(e) &&
2020 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2021 llvm::Value *result = emitARCRetainCall(CGF, e);
2022 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2023 return TryEmitResult(result, true);
2024 }
2025
2026 // Conservatively halt the search at any other expression kind.
2027 break;
2028 }
2029
2030 // We didn't find an obvious production, so emit what we've got and
2031 // tell the caller that we didn't manage to retain.
2032 llvm::Value *result = CGF.EmitScalarExpr(e);
2033 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2034 return TryEmitResult(result, false);
2035}
2036
2037static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2038 LValue lvalue,
2039 QualType type) {
2040 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2041 llvm::Value *value = result.getPointer();
2042 if (!result.getInt())
2043 value = CGF.EmitARCRetain(type, value);
2044 return value;
2045}
2046
2047/// EmitARCRetainScalarExpr - Semantically equivalent to
2048/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2049/// best-effort attempt to peephole expressions that naturally produce
2050/// retained objects.
2051llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
2052 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2053 llvm::Value *value = result.getPointer();
2054 if (!result.getInt())
2055 value = EmitARCRetain(e->getType(), value);
2056 return value;
2057}
2058
2059llvm::Value *
2060CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
2061 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2062 llvm::Value *value = result.getPointer();
2063 if (result.getInt())
2064 value = EmitARCAutorelease(value);
2065 else
2066 value = EmitARCRetainAutorelease(e->getType(), value);
2067 return value;
2068}
2069
2070std::pair<LValue,llvm::Value*>
2071CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2072 bool ignored) {
2073 // Evaluate the RHS first.
2074 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2075 llvm::Value *value = result.getPointer();
2076
2077 LValue lvalue = EmitLValue(e->getLHS());
2078
2079 // If the RHS was emitted retained, expand this.
2080 if (result.getInt()) {
2081 llvm::Value *oldValue =
2082 EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatileQualified(),
2083 lvalue.getAlignment(), e->getType(),
2084 lvalue.getTBAAInfo());
2085 EmitStoreOfScalar(value, lvalue.getAddress(),
2086 lvalue.isVolatileQualified(), lvalue.getAlignment(),
2087 e->getType(), lvalue.getTBAAInfo());
2088 EmitARCRelease(oldValue, /*precise*/ false);
2089 } else {
John McCall545d9962011-06-25 02:11:03 +00002090 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCallf85e1932011-06-15 23:02:42 +00002091 }
2092
2093 return std::pair<LValue,llvm::Value*>(lvalue, value);
2094}
2095
2096std::pair<LValue,llvm::Value*>
2097CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2098 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2099 LValue lvalue = EmitLValue(e->getLHS());
2100
2101 EmitStoreOfScalar(value, lvalue.getAddress(),
2102 lvalue.isVolatileQualified(), lvalue.getAlignment(),
2103 e->getType(), lvalue.getTBAAInfo());
2104
2105 return std::pair<LValue,llvm::Value*>(lvalue, value);
2106}
2107
2108void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
2109 const ObjCAutoreleasePoolStmt &ARPS) {
2110 const Stmt *subStmt = ARPS.getSubStmt();
2111 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2112
2113 CGDebugInfo *DI = getDebugInfo();
2114 if (DI) {
2115 DI->setLocation(S.getLBracLoc());
2116 DI->EmitRegionStart(Builder);
2117 }
2118
2119 // Keep track of the current cleanup stack depth.
2120 RunCleanupsScope Scope(*this);
John McCall9f084a32011-07-06 00:26:06 +00002121 if (CGM.getCodeGenOpts().ObjCRuntimeHasARC) {
John McCallf85e1932011-06-15 23:02:42 +00002122 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2123 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2124 } else {
2125 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2126 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2127 }
2128
2129 for (CompoundStmt::const_body_iterator I = S.body_begin(),
2130 E = S.body_end(); I != E; ++I)
2131 EmitStmt(*I);
2132
2133 if (DI) {
2134 DI->setLocation(S.getRBracLoc());
2135 DI->EmitRegionEnd(Builder);
2136 }
2137}
John McCall0c24c802011-06-24 23:21:27 +00002138
2139/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2140/// make sure it survives garbage collection until this point.
2141void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2142 // We just use an inline assembly.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002143 llvm::Type *paramTypes[] = { VoidPtrTy };
John McCall0c24c802011-06-24 23:21:27 +00002144 llvm::FunctionType *extenderType
2145 = llvm::FunctionType::get(VoidTy, paramTypes, /*variadic*/ false);
2146 llvm::Value *extender
2147 = llvm::InlineAsm::get(extenderType,
2148 /* assembly */ "",
2149 /* constraints */ "r",
2150 /* side effects */ true);
2151
2152 object = Builder.CreateBitCast(object, VoidPtrTy);
2153 Builder.CreateCall(extender, object)->setDoesNotThrow();
2154}
2155
Ted Kremenek2979ec72008-04-09 15:51:31 +00002156CGObjCRuntime::~CGObjCRuntime() {}