blob: 1b3eba4018d23f77471700db99f4ce1d3cd5680b [file] [log] [blame]
Anders Carlsson55085182007-08-21 17:43:55 +00001//===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Anders Carlsson55085182007-08-21 17:43:55 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Objective-C code as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Devang Patelbcbd03a2011-01-19 01:36:36 +000014#include "CGDebugInfo.h"
Ted Kremenek2979ec72008-04-09 15:51:31 +000015#include "CGObjCRuntime.h"
Anders Carlsson55085182007-08-21 17:43:55 +000016#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
John McCallf85e1932011-06-15 23:02:42 +000018#include "TargetInfo.h"
Daniel Dunbar85c59ed2008-08-29 08:11:39 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Chris Lattner16f00492009-04-26 01:32:48 +000021#include "clang/AST/StmtObjC.h"
Daniel Dunbare66f4e32008-09-03 00:27:26 +000022#include "clang/Basic/Diagnostic.h"
Anders Carlsson3d8400d2008-08-30 19:51:14 +000023#include "llvm/ADT/STLExtras.h"
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +000024#include "llvm/Target/TargetData.h"
John McCallf85e1932011-06-15 23:02:42 +000025#include "llvm/InlineAsm.h"
Anders Carlsson55085182007-08-21 17:43:55 +000026using namespace clang;
27using namespace CodeGen;
28
John McCallf85e1932011-06-15 23:02:42 +000029typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
30static TryEmitResult
31tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
32
33/// Given the address of a variable of pointer type, find the correct
34/// null to store into it.
35static llvm::Constant *getNullForVariable(llvm::Value *addr) {
Chris Lattner2acc6e32011-07-18 04:24:23 +000036 llvm::Type *type =
John McCallf85e1932011-06-15 23:02:42 +000037 cast<llvm::PointerType>(addr->getType())->getElementType();
38 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
39}
40
Chris Lattner8fdf3282008-06-24 17:04:18 +000041/// Emits an instance of NSConstantString representing the object.
Mike Stump1eb44332009-09-09 15:08:12 +000042llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar71fcec92008-11-25 21:53:21 +000043{
David Chisnall0d13f6f2010-01-23 02:40:42 +000044 llvm::Constant *C =
45 CGM.getObjCRuntime().GenerateConstantString(E->getString());
Daniel Dunbared7c6182008-08-20 00:28:19 +000046 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Anderson3c4972d2009-07-29 18:54:39 +000047 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattner8fdf3282008-06-24 17:04:18 +000048}
49
50/// Emit a selector.
51llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
52 // Untyped selector.
53 // Note that this implementation allows for non-constant strings to be passed
54 // as arguments to @selector(). Currently, the only thing preventing this
55 // behaviour is the type checking in the front end.
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +000056 return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
Chris Lattner8fdf3282008-06-24 17:04:18 +000057}
58
Daniel Dunbared7c6182008-08-20 00:28:19 +000059llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
60 // FIXME: This should pass the Decl not the name.
61 return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol());
62}
Chris Lattner8fdf3282008-06-24 17:04:18 +000063
Douglas Gregor926df6c2011-06-11 01:09:30 +000064/// \brief Adjust the type of the result of an Objective-C message send
65/// expression when the method has a related result type.
66static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
67 const Expr *E,
68 const ObjCMethodDecl *Method,
69 RValue Result) {
70 if (!Method)
71 return Result;
John McCallf85e1932011-06-15 23:02:42 +000072
Douglas Gregor926df6c2011-06-11 01:09:30 +000073 if (!Method->hasRelatedResultType() ||
74 CGF.getContext().hasSameType(E->getType(), Method->getResultType()) ||
75 !Result.isScalar())
76 return Result;
77
78 // We have applied a related result type. Cast the rvalue appropriately.
79 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
80 CGF.ConvertType(E->getType())));
81}
Chris Lattner8fdf3282008-06-24 17:04:18 +000082
John McCalldc7c5ad2011-07-22 08:53:00 +000083/// Decide whether to extend the lifetime of the receiver of a
84/// returns-inner-pointer message.
85static bool
86shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
87 switch (message->getReceiverKind()) {
88
89 // For a normal instance message, we should extend unless the
90 // receiver is loaded from a variable with precise lifetime.
91 case ObjCMessageExpr::Instance: {
92 const Expr *receiver = message->getInstanceReceiver();
93 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
94 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
95 receiver = ice->getSubExpr()->IgnoreParens();
96
97 // Only __strong variables.
98 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
99 return true;
100
101 // All ivars and fields have precise lifetime.
102 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
103 return false;
104
105 // Otherwise, check for variables.
106 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
107 if (!declRef) return true;
108 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
109 if (!var) return true;
110
111 // All variables have precise lifetime except local variables with
112 // automatic storage duration that aren't specially marked.
113 return (var->hasLocalStorage() &&
114 !var->hasAttr<ObjCPreciseLifetimeAttr>());
115 }
116
117 case ObjCMessageExpr::Class:
118 case ObjCMessageExpr::SuperClass:
119 // It's never necessary for class objects.
120 return false;
121
122 case ObjCMessageExpr::SuperInstance:
123 // We generally assume that 'self' lives throughout a method call.
124 return false;
125 }
126
127 llvm_unreachable("invalid receiver kind");
128}
129
John McCallef072fd2010-05-22 01:48:05 +0000130RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
131 ReturnValueSlot Return) {
Chris Lattner8fdf3282008-06-24 17:04:18 +0000132 // Only the lookup mechanism and first two arguments of the method
133 // implementation vary between runtimes. We can get the receiver and
134 // arguments in generic code.
Mike Stump1eb44332009-09-09 15:08:12 +0000135
John McCallf85e1932011-06-15 23:02:42 +0000136 bool isDelegateInit = E->isDelegateInitCall();
137
John McCalldc7c5ad2011-07-22 08:53:00 +0000138 const ObjCMethodDecl *method = E->getMethodDecl();
139
John McCallf85e1932011-06-15 23:02:42 +0000140 // We don't retain the receiver in delegate init calls, and this is
141 // safe because the receiver value is always loaded from 'self',
142 // which we zero out. We don't want to Block_copy block receivers,
143 // though.
144 bool retainSelf =
145 (!isDelegateInit &&
146 CGM.getLangOptions().ObjCAutoRefCount &&
John McCalldc7c5ad2011-07-22 08:53:00 +0000147 method &&
148 method->hasAttr<NSConsumesSelfAttr>());
John McCallf85e1932011-06-15 23:02:42 +0000149
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000150 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000151 bool isSuperMessage = false;
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000152 bool isClassMessage = false;
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000153 ObjCInterfaceDecl *OID = 0;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000154 // Find the receiver
Douglas Gregor926df6c2011-06-11 01:09:30 +0000155 QualType ReceiverType;
Daniel Dunbar0b647a62010-04-22 03:17:06 +0000156 llvm::Value *Receiver = 0;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000157 switch (E->getReceiverKind()) {
158 case ObjCMessageExpr::Instance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000159 ReceiverType = E->getInstanceReceiver()->getType();
John McCallf85e1932011-06-15 23:02:42 +0000160 if (retainSelf) {
161 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
162 E->getInstanceReceiver());
163 Receiver = ter.getPointer();
John McCalldc7c5ad2011-07-22 08:53:00 +0000164 if (ter.getInt()) retainSelf = false;
John McCallf85e1932011-06-15 23:02:42 +0000165 } else
166 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor04badcf2010-04-21 00:45:42 +0000167 break;
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000168
Douglas Gregor04badcf2010-04-21 00:45:42 +0000169 case ObjCMessageExpr::Class: {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000170 ReceiverType = E->getClassReceiver();
171 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3031c632010-05-17 20:12:43 +0000172 assert(ObjTy && "Invalid Objective-C class message send");
173 OID = ObjTy->getInterface();
174 assert(OID && "Invalid Objective-C class message send");
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000175 Receiver = Runtime.GetClass(Builder, OID);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000176 isClassMessage = true;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000177 break;
178 }
179
180 case ObjCMessageExpr::SuperInstance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000181 ReceiverType = E->getSuperType();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000182 Receiver = LoadObjCSelf();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000183 isSuperMessage = true;
184 break;
185
186 case ObjCMessageExpr::SuperClass:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000187 ReceiverType = E->getSuperType();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000188 Receiver = LoadObjCSelf();
189 isSuperMessage = true;
190 isClassMessage = true;
191 break;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000192 }
193
John McCalldc7c5ad2011-07-22 08:53:00 +0000194 if (retainSelf)
195 Receiver = EmitARCRetainNonBlock(Receiver);
196
197 // In ARC, we sometimes want to "extend the lifetime"
198 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
199 // messages.
200 if (getLangOptions().ObjCAutoRefCount && method &&
201 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
202 shouldExtendReceiverForInnerPointerMessage(E))
203 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
204
John McCallf85e1932011-06-15 23:02:42 +0000205 QualType ResultType =
John McCalldc7c5ad2011-07-22 08:53:00 +0000206 method ? method->getResultType() : E->getType();
John McCallf85e1932011-06-15 23:02:42 +0000207
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000208 CallArgList Args;
John McCalldc7c5ad2011-07-22 08:53:00 +0000209 EmitCallArgs(Args, method, E->arg_begin(), E->arg_end());
Mike Stump1eb44332009-09-09 15:08:12 +0000210
John McCallf85e1932011-06-15 23:02:42 +0000211 // For delegate init calls in ARC, do an unsafe store of null into
212 // self. This represents the call taking direct ownership of that
213 // value. We have to do this after emitting the other call
214 // arguments because they might also reference self, but we don't
215 // have to worry about any of them modifying self because that would
216 // be an undefined read and write of an object in unordered
217 // expressions.
218 if (isDelegateInit) {
219 assert(getLangOptions().ObjCAutoRefCount &&
220 "delegate init calls should only be marked in ARC");
221
222 // Do an unsafe store of null into self.
223 llvm::Value *selfAddr =
224 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
225 assert(selfAddr && "no self entry for a delegate init call?");
226
227 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
228 }
Anders Carlsson7e70fb22010-06-21 20:59:55 +0000229
Douglas Gregor926df6c2011-06-11 01:09:30 +0000230 RValue result;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000231 if (isSuperMessage) {
Chris Lattner9384c762008-06-26 04:42:20 +0000232 // super is only valid in an Objective-C method
233 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000234 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor926df6c2011-06-11 01:09:30 +0000235 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
236 E->getSelector(),
237 OMD->getClassInterface(),
238 isCategoryImpl,
239 Receiver,
240 isClassMessage,
241 Args,
John McCalldc7c5ad2011-07-22 08:53:00 +0000242 method);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000243 } else {
244 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
245 E->getSelector(),
246 Receiver, Args, OID,
John McCalldc7c5ad2011-07-22 08:53:00 +0000247 method);
Chris Lattner8fdf3282008-06-24 17:04:18 +0000248 }
John McCallf85e1932011-06-15 23:02:42 +0000249
250 // For delegate init calls in ARC, implicitly store the result of
251 // the call back into self. This takes ownership of the value.
252 if (isDelegateInit) {
253 llvm::Value *selfAddr =
254 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
255 llvm::Value *newSelf = result.getScalarVal();
256
257 // The delegate return type isn't necessarily a matching type; in
258 // fact, it's quite likely to be 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000259 llvm::Type *selfTy =
John McCallf85e1932011-06-15 23:02:42 +0000260 cast<llvm::PointerType>(selfAddr->getType())->getElementType();
261 newSelf = Builder.CreateBitCast(newSelf, selfTy);
262
263 Builder.CreateStore(newSelf, selfAddr);
264 }
265
John McCalldc7c5ad2011-07-22 08:53:00 +0000266 return AdjustRelatedResultType(*this, E, method, result);
Anders Carlsson55085182007-08-21 17:43:55 +0000267}
268
John McCallf85e1932011-06-15 23:02:42 +0000269namespace {
270struct FinishARCDealloc : EHScopeStack::Cleanup {
John McCallad346f42011-07-12 20:27:29 +0000271 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +0000272 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCall799d34e2011-07-13 18:26:47 +0000273
274 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCallf85e1932011-06-15 23:02:42 +0000275 const ObjCInterfaceDecl *iface = impl->getClassInterface();
276 if (!iface->getSuperClass()) return;
277
John McCall799d34e2011-07-13 18:26:47 +0000278 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
279
John McCallf85e1932011-06-15 23:02:42 +0000280 // Call [super dealloc] if we have a superclass.
281 llvm::Value *self = CGF.LoadObjCSelf();
282
283 CallArgList args;
284 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
285 CGF.getContext().VoidTy,
286 method->getSelector(),
287 iface,
John McCall799d34e2011-07-13 18:26:47 +0000288 isCategory,
John McCallf85e1932011-06-15 23:02:42 +0000289 self,
290 /*is class msg*/ false,
291 args,
292 method);
293 }
294};
295}
296
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000297/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
298/// the LLVM function and sets the other context used by
299/// CodeGenFunction.
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000300void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
Devang Patel8d3f8972011-05-19 23:37:41 +0000301 const ObjCContainerDecl *CD,
302 SourceLocation StartLoc) {
John McCalld26bc762011-03-09 04:27:21 +0000303 FunctionArgList args;
Devang Patel4800ea62010-04-05 21:09:15 +0000304 // Check if we should generate debug info for this method.
Devang Patelaa112892011-03-07 18:45:56 +0000305 if (CGM.getModuleDebugInfo() && !OMD->hasAttr<NoDebugAttr>())
306 DebugInfo = CGM.getModuleDebugInfo();
Devang Patel4800ea62010-04-05 21:09:15 +0000307
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000308 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000309
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000310 const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(OMD);
311 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner41110242008-06-17 18:05:57 +0000312
John McCalld26bc762011-03-09 04:27:21 +0000313 args.push_back(OMD->getSelfDecl());
314 args.push_back(OMD->getCmdDecl());
Chris Lattner41110242008-06-17 18:05:57 +0000315
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +0000316 for (ObjCMethodDecl::param_const_iterator PI = OMD->param_begin(),
Chris Lattner89951a82009-02-20 18:43:26 +0000317 E = OMD->param_end(); PI != E; ++PI)
John McCalld26bc762011-03-09 04:27:21 +0000318 args.push_back(*PI);
Chris Lattner41110242008-06-17 18:05:57 +0000319
Peter Collingbourne14110472011-01-13 18:57:25 +0000320 CurGD = OMD;
321
Devang Patel8d3f8972011-05-19 23:37:41 +0000322 StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc);
John McCallf85e1932011-06-15 23:02:42 +0000323
324 // In ARC, certain methods get an extra cleanup.
325 if (CGM.getLangOptions().ObjCAutoRefCount &&
326 OMD->isInstanceMethod() &&
327 OMD->getSelector().isUnarySelector()) {
328 const IdentifierInfo *ident =
329 OMD->getSelector().getIdentifierInfoForSlot(0);
330 if (ident->isStr("dealloc"))
331 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
332 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000333}
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000334
John McCallf85e1932011-06-15 23:02:42 +0000335static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
336 LValue lvalue, QualType type);
337
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000338/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump1eb44332009-09-09 15:08:12 +0000339/// its pointer, name, and types registered in the class struture.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000340void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
Devang Patel8d3f8972011-05-19 23:37:41 +0000341 StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000342 EmitStmt(OMD->getBody());
343 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000344}
345
John McCall41bdde92011-09-12 23:06:44 +0000346/// emitStructGetterCall - Call the runtime function to load a property
347/// into the return value slot.
348static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
349 bool isAtomic, bool hasStrong) {
350 ASTContext &Context = CGF.getContext();
351
352 llvm::Value *src =
353 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(),
354 ivar, 0).getAddress();
355
356 // objc_copyStruct (ReturnValue, &structIvar,
357 // sizeof (Type of Ivar), isAtomic, false);
358 CallArgList args;
359
360 llvm::Value *dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
361 args.add(RValue::get(dest), Context.VoidPtrTy);
362
363 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
364 args.add(RValue::get(src), Context.VoidPtrTy);
365
366 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
367 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
368 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
369 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
370
371 llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
372 CGF.EmitCall(CGF.getTypes().getFunctionInfo(Context.VoidTy, args,
373 FunctionType::ExtInfo()),
374 fn, ReturnValueSlot(), args);
375}
376
John McCall1e1f4872011-09-13 03:34:09 +0000377/// Determine whether the given architecture supports unaligned atomic
378/// accesses. They don't have to be fast, just faster than a function
379/// call and a mutex.
380static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedmande24d442011-09-13 20:48:30 +0000381 // FIXME: Allow unaligned atomic load/store on x86. (It is not
382 // currently supported by the backend.)
383 return 0;
John McCall1e1f4872011-09-13 03:34:09 +0000384}
385
386/// Return the maximum size that permits atomic accesses for the given
387/// architecture.
388static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
389 llvm::Triple::ArchType arch) {
390 // ARM has 8-byte atomic accesses, but it's not clear whether we
391 // want to rely on them here.
392
393 // In the default case, just assume that any size up to a pointer is
394 // fine given adequate alignment.
395 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
396}
397
398namespace {
399 class PropertyImplStrategy {
400 public:
401 enum StrategyKind {
402 /// The 'native' strategy is to use the architecture's provided
403 /// reads and writes.
404 Native,
405
406 /// Use objc_setProperty and objc_getProperty.
407 GetSetProperty,
408
409 /// Use objc_setProperty for the setter, but use expression
410 /// evaluation for the getter.
411 SetPropertyAndExpressionGet,
412
413 /// Use objc_copyStruct.
414 CopyStruct,
415
416 /// The 'expression' strategy is to emit normal assignment or
417 /// lvalue-to-rvalue expressions.
418 Expression
419 };
420
421 StrategyKind getKind() const { return StrategyKind(Kind); }
422
423 bool hasStrongMember() const { return HasStrong; }
424 bool isAtomic() const { return IsAtomic; }
425 bool isCopy() const { return IsCopy; }
426
427 CharUnits getIvarSize() const { return IvarSize; }
428 CharUnits getIvarAlignment() const { return IvarAlignment; }
429
430 PropertyImplStrategy(CodeGenModule &CGM,
431 const ObjCPropertyImplDecl *propImpl);
432
433 private:
434 unsigned Kind : 8;
435 unsigned IsAtomic : 1;
436 unsigned IsCopy : 1;
437 unsigned HasStrong : 1;
438
439 CharUnits IvarSize;
440 CharUnits IvarAlignment;
441 };
442}
443
444/// Pick an implementation strategy for the the given property synthesis.
445PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
446 const ObjCPropertyImplDecl *propImpl) {
447 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall265941b2011-09-13 18:31:23 +0000448 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCall1e1f4872011-09-13 03:34:09 +0000449
John McCall265941b2011-09-13 18:31:23 +0000450 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
451 IsAtomic = prop->isAtomic();
John McCall1e1f4872011-09-13 03:34:09 +0000452 HasStrong = false; // doesn't matter here.
453
454 // Evaluate the ivar's size and alignment.
455 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
456 QualType ivarType = ivar->getType();
457 llvm::tie(IvarSize, IvarAlignment)
458 = CGM.getContext().getTypeInfoInChars(ivarType);
459
460 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall265941b2011-09-13 18:31:23 +0000461 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCall1e1f4872011-09-13 03:34:09 +0000462 if (IsCopy) {
463 Kind = GetSetProperty;
464 return;
465 }
466
John McCall265941b2011-09-13 18:31:23 +0000467 // Handle retain.
468 if (setterKind == ObjCPropertyDecl::Retain) {
John McCall1e1f4872011-09-13 03:34:09 +0000469 // In GC-only, there's nothing special that needs to be done.
Douglas Gregore289d812011-09-13 17:21:33 +0000470 if (CGM.getLangOptions().getGC() == LangOptions::GCOnly) {
John McCall1e1f4872011-09-13 03:34:09 +0000471 // fallthrough
472
473 // In ARC, if the property is non-atomic, use expression emission,
474 // which translates to objc_storeStrong. This isn't required, but
475 // it's slightly nicer.
476 } else if (CGM.getLangOptions().ObjCAutoRefCount && !IsAtomic) {
477 Kind = Expression;
478 return;
479
480 // Otherwise, we need to at least use setProperty. However, if
481 // the property isn't atomic, we can use normal expression
482 // emission for the getter.
483 } else if (!IsAtomic) {
484 Kind = SetPropertyAndExpressionGet;
485 return;
486
487 // Otherwise, we have to use both setProperty and getProperty.
488 } else {
489 Kind = GetSetProperty;
490 return;
491 }
492 }
493
494 // If we're not atomic, just use expression accesses.
495 if (!IsAtomic) {
496 Kind = Expression;
497 return;
498 }
499
John McCall5889c602011-09-13 05:36:29 +0000500 // Properties on bitfield ivars need to be emitted using expression
501 // accesses even if they're nominally atomic.
502 if (ivar->isBitField()) {
503 Kind = Expression;
504 return;
505 }
506
John McCall1e1f4872011-09-13 03:34:09 +0000507 // GC-qualified or ARC-qualified ivars need to be emitted as
508 // expressions. This actually works out to being atomic anyway,
509 // except for ARC __strong, but that should trigger the above code.
510 if (ivarType.hasNonTrivialObjCLifetime() ||
Douglas Gregore289d812011-09-13 17:21:33 +0000511 (CGM.getLangOptions().getGC() &&
John McCall1e1f4872011-09-13 03:34:09 +0000512 CGM.getContext().getObjCGCAttrKind(ivarType))) {
513 Kind = Expression;
514 return;
515 }
516
517 // Compute whether the ivar has strong members.
Douglas Gregore289d812011-09-13 17:21:33 +0000518 if (CGM.getLangOptions().getGC())
John McCall1e1f4872011-09-13 03:34:09 +0000519 if (const RecordType *recordType = ivarType->getAs<RecordType>())
520 HasStrong = recordType->getDecl()->hasObjectMember();
521
522 // We can never access structs with object members with a native
523 // access, because we need to use write barriers. This is what
524 // objc_copyStruct is for.
525 if (HasStrong) {
526 Kind = CopyStruct;
527 return;
528 }
529
530 // Otherwise, this is target-dependent and based on the size and
531 // alignment of the ivar.
John McCallc5d9a902011-09-13 07:33:34 +0000532
533 // If the size of the ivar is not a power of two, give up. We don't
534 // want to get into the business of doing compare-and-swaps.
535 if (!IvarSize.isPowerOfTwo()) {
536 Kind = CopyStruct;
537 return;
538 }
539
John McCall1e1f4872011-09-13 03:34:09 +0000540 llvm::Triple::ArchType arch =
541 CGM.getContext().getTargetInfo().getTriple().getArch();
542
543 // Most architectures require memory to fit within a single cache
544 // line, so the alignment has to be at least the size of the access.
545 // Otherwise we have to grab a lock.
546 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
547 Kind = CopyStruct;
548 return;
549 }
550
551 // If the ivar's size exceeds the architecture's maximum atomic
552 // access size, we have to use CopyStruct.
553 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
554 Kind = CopyStruct;
555 return;
556 }
557
558 // Otherwise, we can use native loads and stores.
559 Kind = Native;
560}
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000561
562/// GenerateObjCGetter - Generate an Objective-C property getter
Steve Naroff489034c2009-01-10 22:55:25 +0000563/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
564/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000565void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
566 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000567 llvm::Constant *AtomicHelperFn =
568 GenerateObjCAtomicCopyHelperFunction(PID, false);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000569 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
570 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
571 assert(OMD && "Invalid call to generate getter (empty method)");
Devang Patel8d3f8972011-05-19 23:37:41 +0000572 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +0000573
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000574 generateObjCGetterBody(IMP, PID, AtomicHelperFn);
John McCall1e1f4872011-09-13 03:34:09 +0000575
576 FinishFunction();
577}
578
John McCall6c11f0b2011-09-13 06:00:03 +0000579static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
580 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCall1e1f4872011-09-13 03:34:09 +0000581 if (!getter) return true;
582
583 // Sema only makes only of these when the ivar has a C++ class type,
584 // so the form is pretty constrained.
585
John McCall6c11f0b2011-09-13 06:00:03 +0000586 // If the property has a reference type, we might just be binding a
587 // reference, in which case the result will be a gl-value. We should
588 // treat this as a non-trivial operation.
589 if (getter->isGLValue())
590 return false;
591
John McCall1e1f4872011-09-13 03:34:09 +0000592 // If we selected a trivial copy-constructor, we're okay.
593 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
594 return (construct->getConstructor()->isTrivial());
595
596 // The constructor might require cleanups (in which case it's never
597 // trivial).
598 assert(isa<ExprWithCleanups>(getter));
599 return false;
600}
601
602void
603CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000604 const ObjCPropertyImplDecl *propImpl,
605 llvm::Constant *AtomicHelperFn) {
John McCall1e1f4872011-09-13 03:34:09 +0000606 // If there's a non-trivial 'get' expression, we just have to emit that.
607 if (!hasTrivialGetExpr(propImpl)) {
608 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
609 /*nrvo*/ 0);
610 EmitReturnStmt(ret);
611 return;
612 }
613
614 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
615 QualType propType = prop->getType();
616 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
617
618 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
619
620 // Pick an implementation strategy.
621 PropertyImplStrategy strategy(CGM, propImpl);
622 switch (strategy.getKind()) {
623 case PropertyImplStrategy::Native: {
624 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
625
626 // Currently, all atomic accesses have to be through integer
627 // types, so there's no point in trying to pick a prettier type.
628 llvm::Type *bitcastType =
629 llvm::Type::getIntNTy(getLLVMContext(),
630 getContext().toBits(strategy.getIvarSize()));
631 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
632
633 // Perform an atomic load. This does not impose ordering constraints.
634 llvm::Value *ivarAddr = LV.getAddress();
635 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
636 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
637 load->setAlignment(strategy.getIvarAlignment().getQuantity());
638 load->setAtomic(llvm::Unordered);
639
640 // Store that value into the return address. Doing this with a
641 // bitcast is likely to produce some pretty ugly IR, but it's not
642 // the *most* terrible thing in the world.
643 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
644
645 // Make sure we don't do an autorelease.
646 AutoreleaseResult = false;
647 return;
648 }
649
650 case PropertyImplStrategy::GetSetProperty: {
651 llvm::Value *getPropertyFn =
652 CGM.getObjCRuntime().GetPropertyGetFunction();
653 if (!getPropertyFn) {
654 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000655 return;
656 }
657
658 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
659 // FIXME: Can't this be simpler? This might even be worse than the
660 // corresponding gcc code.
John McCall1e1f4872011-09-13 03:34:09 +0000661 llvm::Value *cmd =
662 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
663 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
664 llvm::Value *ivarOffset =
665 EmitIvarOffset(classImpl->getClassInterface(), ivar);
666
667 CallArgList args;
668 args.add(RValue::get(self), getContext().getObjCIdType());
669 args.add(RValue::get(cmd), getContext().getObjCSelType());
670 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall265941b2011-09-13 18:31:23 +0000671 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
672 getContext().BoolTy);
John McCall1e1f4872011-09-13 03:34:09 +0000673
Daniel Dunbare4be5a62009-02-03 23:43:59 +0000674 // FIXME: We shouldn't need to get the function info here, the
675 // runtime already should have computed it to build the function.
John McCall1e1f4872011-09-13 03:34:09 +0000676 RValue RV = EmitCall(getTypes().getFunctionInfo(propType, args,
John McCall41bdde92011-09-12 23:06:44 +0000677 FunctionType::ExtInfo()),
John McCall1e1f4872011-09-13 03:34:09 +0000678 getPropertyFn, ReturnValueSlot(), args);
679
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000680 // We need to fix the type here. Ivars with copy & retain are
681 // always objects so we don't need to worry about complex or
682 // aggregates.
Mike Stump1eb44332009-09-09 15:08:12 +0000683 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
John McCall1e1f4872011-09-13 03:34:09 +0000684 getTypes().ConvertType(propType)));
685
686 EmitReturnOfRValue(RV, propType);
John McCallf85e1932011-06-15 23:02:42 +0000687
688 // objc_getProperty does an autorelease, so we should suppress ours.
689 AutoreleaseResult = false;
John McCallf85e1932011-06-15 23:02:42 +0000690
John McCall1e1f4872011-09-13 03:34:09 +0000691 return;
692 }
693
694 case PropertyImplStrategy::CopyStruct:
695 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
696 strategy.hasStrongMember());
697 return;
698
699 case PropertyImplStrategy::Expression:
700 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
701 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
702
703 QualType ivarType = ivar->getType();
704 if (ivarType->isAnyComplexType()) {
705 ComplexPairTy pair = LoadComplexFromAddr(LV.getAddress(),
706 LV.isVolatileQualified());
707 StoreComplexToAddr(pair, ReturnValue, LV.isVolatileQualified());
708 } else if (hasAggregateLLVMType(ivarType)) {
709 // The return value slot is guaranteed to not be aliased, but
710 // that's not necessarily the same as "on the stack", so
711 // we still potentially need objc_memmove_collectable.
712 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
713 } else {
John McCallba3dd902011-07-22 05:23:13 +0000714 llvm::Value *value;
715 if (propType->isReferenceType()) {
716 value = LV.getAddress();
717 } else {
718 // We want to load and autoreleaseReturnValue ARC __weak ivars.
719 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall1e1f4872011-09-13 03:34:09 +0000720 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
John McCallba3dd902011-07-22 05:23:13 +0000721
722 // Otherwise we want to do a simple load, suppressing the
723 // final autorelease.
John McCallf85e1932011-06-15 23:02:42 +0000724 } else {
John McCallba3dd902011-07-22 05:23:13 +0000725 value = EmitLoadOfLValue(LV).getScalarVal();
726 AutoreleaseResult = false;
Fariborz Jahanian14086762011-03-28 23:47:18 +0000727 }
John McCallf85e1932011-06-15 23:02:42 +0000728
John McCallba3dd902011-07-22 05:23:13 +0000729 value = Builder.CreateBitCast(value, ConvertType(propType));
730 }
731
732 EmitReturnOfRValue(RValue::get(value), propType);
Fariborz Jahanianed1d29d2009-03-03 18:49:40 +0000733 }
John McCall1e1f4872011-09-13 03:34:09 +0000734 return;
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000735 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000736
John McCall1e1f4872011-09-13 03:34:09 +0000737 }
738 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000739}
740
John McCall41bdde92011-09-12 23:06:44 +0000741/// emitStructSetterCall - Call the runtime function to store the value
742/// from the first formal parameter into the given ivar.
743static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
744 ObjCIvarDecl *ivar) {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000745 // objc_copyStruct (&structIvar, &Arg,
746 // sizeof (struct something), true, false);
John McCallbbb253c2011-09-10 09:30:49 +0000747 CallArgList args;
748
749 // The first argument is the address of the ivar.
John McCall41bdde92011-09-12 23:06:44 +0000750 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
751 CGF.LoadObjCSelf(), ivar, 0)
752 .getAddress();
753 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
754 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000755
756 // The second argument is the address of the parameter variable.
John McCall41bdde92011-09-12 23:06:44 +0000757 ParmVarDecl *argVar = *OMD->param_begin();
Fariborz Jahanianc3953aa2012-01-05 00:10:16 +0000758 DeclRefExpr argRef(argVar, argVar->getType().getNonReferenceType(),
759 VK_LValue, SourceLocation());
John McCall41bdde92011-09-12 23:06:44 +0000760 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
761 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
762 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000763
764 // The third argument is the sizeof the type.
765 llvm::Value *size =
John McCall41bdde92011-09-12 23:06:44 +0000766 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
767 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCallbbb253c2011-09-10 09:30:49 +0000768
John McCall41bdde92011-09-12 23:06:44 +0000769 // The fourth argument is the 'isAtomic' flag.
770 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCallbbb253c2011-09-10 09:30:49 +0000771
John McCall41bdde92011-09-12 23:06:44 +0000772 // The fifth argument is the 'hasStrong' flag.
773 // FIXME: should this really always be false?
774 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
775
776 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
777 CGF.EmitCall(CGF.getTypes().getFunctionInfo(CGF.getContext().VoidTy, args,
778 FunctionType::ExtInfo()),
779 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000780}
781
Fariborz Jahaniancd93b962012-01-06 22:33:54 +0000782/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
783/// the value from the first formal parameter into the given ivar, using
784/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
785static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
786 ObjCMethodDecl *OMD,
787 ObjCIvarDecl *ivar,
788 llvm::Constant *AtomicHelperFn) {
789 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
790 // AtomicHelperFn);
791 CallArgList args;
792
793 // The first argument is the address of the ivar.
794 llvm::Value *ivarAddr =
795 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
796 CGF.LoadObjCSelf(), ivar, 0).getAddress();
797 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
798 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
799
800 // The second argument is the address of the parameter variable.
801 ParmVarDecl *argVar = *OMD->param_begin();
802 DeclRefExpr argRef(argVar, argVar->getType().getNonReferenceType(),
803 VK_LValue, SourceLocation());
804 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
805 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
806 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
807
808 // Third argument is the helper function.
809 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
810
811 llvm::Value *copyCppAtomicObjectFn =
812 CGF.CGM.getObjCRuntime().GetCppAtomicObjectFunction();
813 CGF.EmitCall(CGF.getTypes().getFunctionInfo(CGF.getContext().VoidTy, args,
814 FunctionType::ExtInfo()),
815 copyCppAtomicObjectFn, ReturnValueSlot(), args);
816
817
818}
819
John McCall1e1f4872011-09-13 03:34:09 +0000820static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
821 Expr *setter = PID->getSetterCXXAssignment();
822 if (!setter) return true;
823
824 // Sema only makes only of these when the ivar has a C++ class type,
825 // so the form is pretty constrained.
John McCall71c758d2011-09-10 09:17:20 +0000826
827 // An operator call is trivial if the function it calls is trivial.
John McCall1e1f4872011-09-13 03:34:09 +0000828 // This also implies that there's nothing non-trivial going on with
829 // the arguments, because operator= can only be trivial if it's a
830 // synthesized assignment operator and therefore both parameters are
831 // references.
832 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall71c758d2011-09-10 09:17:20 +0000833 if (const FunctionDecl *callee
834 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
835 if (callee->isTrivial())
836 return true;
837 return false;
Fariborz Jahanian01cb3072011-04-06 16:05:26 +0000838 }
John McCall71c758d2011-09-10 09:17:20 +0000839
John McCall1e1f4872011-09-13 03:34:09 +0000840 assert(isa<ExprWithCleanups>(setter));
John McCall71c758d2011-09-10 09:17:20 +0000841 return false;
842}
843
John McCall71c758d2011-09-10 09:17:20 +0000844void
845CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahaniancd93b962012-01-06 22:33:54 +0000846 const ObjCPropertyImplDecl *propImpl,
847 llvm::Constant *AtomicHelperFn) {
John McCall71c758d2011-09-10 09:17:20 +0000848 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian84e49862012-01-06 00:29:35 +0000849 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall71c758d2011-09-10 09:17:20 +0000850 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +0000851
852 // Just use the setter expression if Sema gave us one and it's
853 // non-trivial.
854 if (!hasTrivialSetExpr(propImpl)) {
855 if (!AtomicHelperFn)
856 // If non-atomic, assignment is called directly.
857 EmitStmt(propImpl->getSetterCXXAssignment());
858 else
859 // If atomic, assignment is called via a locking api.
860 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
861 AtomicHelperFn);
862 return;
863 }
John McCall71c758d2011-09-10 09:17:20 +0000864
John McCall1e1f4872011-09-13 03:34:09 +0000865 PropertyImplStrategy strategy(CGM, propImpl);
866 switch (strategy.getKind()) {
867 case PropertyImplStrategy::Native: {
868 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
John McCall71c758d2011-09-10 09:17:20 +0000869
John McCall1e1f4872011-09-13 03:34:09 +0000870 LValue ivarLValue =
871 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
872 llvm::Value *ivarAddr = ivarLValue.getAddress();
John McCall71c758d2011-09-10 09:17:20 +0000873
John McCall1e1f4872011-09-13 03:34:09 +0000874 // Currently, all atomic accesses have to be through integer
875 // types, so there's no point in trying to pick a prettier type.
876 llvm::Type *bitcastType =
877 llvm::Type::getIntNTy(getLLVMContext(),
878 getContext().toBits(strategy.getIvarSize()));
879 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
880
881 // Cast both arguments to the chosen operation type.
882 argAddr = Builder.CreateBitCast(argAddr, bitcastType);
883 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
884
885 // This bitcast load is likely to cause some nasty IR.
886 llvm::Value *load = Builder.CreateLoad(argAddr);
887
888 // Perform an atomic store. There are no memory ordering requirements.
889 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
890 store->setAlignment(strategy.getIvarAlignment().getQuantity());
891 store->setAtomic(llvm::Unordered);
892 return;
893 }
894
895 case PropertyImplStrategy::GetSetProperty:
896 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
John McCall71c758d2011-09-10 09:17:20 +0000897 llvm::Value *setPropertyFn =
898 CGM.getObjCRuntime().GetPropertySetFunction();
899 if (!setPropertyFn) {
900 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
901 return;
902 }
903
904 // Emit objc_setProperty((id) self, _cmd, offset, arg,
905 // <is-atomic>, <is-copy>).
906 llvm::Value *cmd =
907 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
908 llvm::Value *self =
909 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
910 llvm::Value *ivarOffset =
911 EmitIvarOffset(classImpl->getClassInterface(), ivar);
912 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
913 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
914
915 CallArgList args;
916 args.add(RValue::get(self), getContext().getObjCIdType());
917 args.add(RValue::get(cmd), getContext().getObjCSelType());
918 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
919 args.add(RValue::get(arg), getContext().getObjCIdType());
John McCall1e1f4872011-09-13 03:34:09 +0000920 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
921 getContext().BoolTy);
922 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
923 getContext().BoolTy);
John McCall71c758d2011-09-10 09:17:20 +0000924 // FIXME: We shouldn't need to get the function info here, the runtime
925 // already should have computed it to build the function.
926 EmitCall(getTypes().getFunctionInfo(getContext().VoidTy, args,
927 FunctionType::ExtInfo()),
928 setPropertyFn, ReturnValueSlot(), args);
929 return;
930 }
931
John McCall1e1f4872011-09-13 03:34:09 +0000932 case PropertyImplStrategy::CopyStruct:
John McCall41bdde92011-09-12 23:06:44 +0000933 emitStructSetterCall(*this, setterMethod, ivar);
John McCall71c758d2011-09-10 09:17:20 +0000934 return;
John McCall1e1f4872011-09-13 03:34:09 +0000935
936 case PropertyImplStrategy::Expression:
937 break;
John McCall71c758d2011-09-10 09:17:20 +0000938 }
939
940 // Otherwise, fake up some ASTs and emit a normal assignment.
941 ValueDecl *selfDecl = setterMethod->getSelfDecl();
942 DeclRefExpr self(selfDecl, selfDecl->getType(), VK_LValue, SourceLocation());
943 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
944 selfDecl->getType(), CK_LValueToRValue, &self,
945 VK_RValue);
946 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
947 SourceLocation(), &selfLoad, true, true);
948
949 ParmVarDecl *argDecl = *setterMethod->param_begin();
950 QualType argType = argDecl->getType().getNonReferenceType();
951 DeclRefExpr arg(argDecl, argType, VK_LValue, SourceLocation());
952 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
953 argType.getUnqualifiedType(), CK_LValueToRValue,
954 &arg, VK_RValue);
955
956 // The property type can differ from the ivar type in some situations with
957 // Objective-C pointer types, we can always bit cast the RHS in these cases.
958 // The following absurdity is just to ensure well-formed IR.
959 CastKind argCK = CK_NoOp;
960 if (ivarRef.getType()->isObjCObjectPointerType()) {
961 if (argLoad.getType()->isObjCObjectPointerType())
962 argCK = CK_BitCast;
963 else if (argLoad.getType()->isBlockPointerType())
964 argCK = CK_BlockPointerToObjCPointerCast;
965 else
966 argCK = CK_CPointerToObjCPointerCast;
967 } else if (ivarRef.getType()->isBlockPointerType()) {
968 if (argLoad.getType()->isBlockPointerType())
969 argCK = CK_BitCast;
970 else
971 argCK = CK_AnyPointerToBlockPointerCast;
972 } else if (ivarRef.getType()->isPointerType()) {
973 argCK = CK_BitCast;
974 }
975 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
976 ivarRef.getType(), argCK, &argLoad,
977 VK_RValue);
978 Expr *finalArg = &argLoad;
979 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
980 argLoad.getType()))
981 finalArg = &argCast;
982
983
984 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
985 ivarRef.getType(), VK_RValue, OK_Ordinary,
986 SourceLocation());
987 EmitStmt(&assign);
Fariborz Jahanian01cb3072011-04-06 16:05:26 +0000988}
989
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000990/// GenerateObjCSetter - Generate an Objective-C property setter
Steve Naroff489034c2009-01-10 22:55:25 +0000991/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
992/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000993void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
994 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000995 llvm::Constant *AtomicHelperFn =
996 GenerateObjCAtomicCopyHelperFunction(PID, true);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000997 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
998 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
999 assert(OMD && "Invalid call to generate setter (empty method)");
Devang Patel8d3f8972011-05-19 23:37:41 +00001000 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Daniel Dunbar86957eb2008-09-24 06:32:09 +00001001
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001002 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001003
1004 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +00001005}
1006
John McCalle81ac692011-03-22 07:05:39 +00001007namespace {
John McCall9928c482011-07-12 16:41:08 +00001008 struct DestroyIvar : EHScopeStack::Cleanup {
1009 private:
1010 llvm::Value *addr;
John McCalle81ac692011-03-22 07:05:39 +00001011 const ObjCIvarDecl *ivar;
John McCall9928c482011-07-12 16:41:08 +00001012 CodeGenFunction::Destroyer &destroyer;
1013 bool useEHCleanupForArray;
1014 public:
1015 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1016 CodeGenFunction::Destroyer *destroyer,
1017 bool useEHCleanupForArray)
1018 : addr(addr), ivar(ivar), destroyer(*destroyer),
1019 useEHCleanupForArray(useEHCleanupForArray) {}
John McCalle81ac692011-03-22 07:05:39 +00001020
John McCallad346f42011-07-12 20:27:29 +00001021 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +00001022 LValue lvalue
1023 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1024 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +00001025 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCalle81ac692011-03-22 07:05:39 +00001026 }
1027 };
1028}
1029
John McCall9928c482011-07-12 16:41:08 +00001030/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1031static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1032 llvm::Value *addr,
1033 QualType type) {
1034 llvm::Value *null = getNullForVariable(addr);
1035 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1036}
John McCallf85e1932011-06-15 23:02:42 +00001037
John McCalle81ac692011-03-22 07:05:39 +00001038static void emitCXXDestructMethod(CodeGenFunction &CGF,
1039 ObjCImplementationDecl *impl) {
1040 CodeGenFunction::RunCleanupsScope scope(CGF);
1041
1042 llvm::Value *self = CGF.LoadObjCSelf();
1043
Jordy Rosedb8264e2011-07-22 02:08:32 +00001044 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1045 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +00001046 ivar; ivar = ivar->getNextIvar()) {
1047 QualType type = ivar->getType();
1048
John McCalle81ac692011-03-22 07:05:39 +00001049 // Check whether the ivar is a destructible type.
John McCall9928c482011-07-12 16:41:08 +00001050 QualType::DestructionKind dtorKind = type.isDestructedType();
1051 if (!dtorKind) continue;
John McCalle81ac692011-03-22 07:05:39 +00001052
John McCall9928c482011-07-12 16:41:08 +00001053 CodeGenFunction::Destroyer *destroyer = 0;
John McCalle81ac692011-03-22 07:05:39 +00001054
John McCall9928c482011-07-12 16:41:08 +00001055 // Use a call to objc_storeStrong to destroy strong ivars, for the
1056 // general benefit of the tools.
1057 if (dtorKind == QualType::DK_objc_strong_lifetime) {
1058 destroyer = &destroyARCStrongWithStore;
John McCallf85e1932011-06-15 23:02:42 +00001059
John McCall9928c482011-07-12 16:41:08 +00001060 // Otherwise use the default for the destruction kind.
1061 } else {
1062 destroyer = &CGF.getDestroyer(dtorKind);
John McCalle81ac692011-03-22 07:05:39 +00001063 }
John McCall9928c482011-07-12 16:41:08 +00001064
1065 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1066
1067 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1068 cleanupKind & EHCleanup);
John McCalle81ac692011-03-22 07:05:39 +00001069 }
1070
1071 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1072}
1073
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001074void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1075 ObjCMethodDecl *MD,
1076 bool ctor) {
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001077 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Devang Patel8d3f8972011-05-19 23:37:41 +00001078 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
John McCalle81ac692011-03-22 07:05:39 +00001079
1080 // Emit .cxx_construct.
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001081 if (ctor) {
John McCallf85e1932011-06-15 23:02:42 +00001082 // Suppress the final autorelease in ARC.
1083 AutoreleaseResult = false;
1084
Chris Lattner5f9e2722011-07-23 10:55:15 +00001085 SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
John McCalle81ac692011-03-22 07:05:39 +00001086 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
1087 E = IMP->init_end(); B != E; ++B) {
1088 CXXCtorInitializer *IvarInit = (*B);
Francois Pichet00eb3f92010-12-04 09:14:42 +00001089 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001090 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian9b4d4fc2010-04-28 22:30:33 +00001091 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1092 LoadObjCSelf(), Ivar, 0);
John McCall7c2349b2011-08-25 20:40:09 +00001093 EmitAggExpr(IvarInit->getInit(),
1094 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001095 AggValueSlot::DoesNotNeedGCBarriers,
1096 AggValueSlot::IsNotAliased));
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001097 }
1098 // constructor returns 'self'.
1099 CodeGenTypes &Types = CGM.getTypes();
1100 QualType IdTy(CGM.getContext().getObjCIdType());
1101 llvm::Value *SelfAsId =
1102 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1103 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCalle81ac692011-03-22 07:05:39 +00001104
1105 // Emit .cxx_destruct.
Chandler Carruthbc397cf2010-05-06 00:20:39 +00001106 } else {
John McCalle81ac692011-03-22 07:05:39 +00001107 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001108 }
1109 FinishFunction();
1110}
1111
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +00001112bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1113 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1114 it++; it++;
1115 const ABIArgInfo &AI = it->info;
1116 // FIXME. Is this sufficient check?
1117 return (AI.getKind() == ABIArgInfo::Indirect);
1118}
1119
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001120bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
Douglas Gregore289d812011-09-13 17:21:33 +00001121 if (CGM.getLangOptions().getGC() == LangOptions::NonGC)
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001122 return false;
1123 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1124 return FDTTy->getDecl()->hasObjectMember();
1125 return false;
1126}
1127
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001128llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001129 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1130 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner41110242008-06-17 18:05:57 +00001131}
1132
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001133QualType CodeGenFunction::TypeOfSelfObject() {
1134 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1135 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff14108da2009-07-10 23:34:53 +00001136 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1137 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001138 return PTy->getPointeeType();
1139}
1140
Chris Lattner74391b42009-03-22 21:03:39 +00001141void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump1eb44332009-09-09 15:08:12 +00001142 llvm::Constant *EnumerationMutationFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001143 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +00001144
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001145 if (!EnumerationMutationFn) {
1146 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1147 return;
1148 }
1149
Devang Patelbcbd03a2011-01-19 01:36:36 +00001150 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00001151 if (DI)
1152 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001153
Devang Patel9d99f2d2011-06-13 23:15:32 +00001154 // The local variable comes into scope immediately.
1155 AutoVarEmission variable = AutoVarEmission::invalid();
1156 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1157 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1158
John McCalld88687f2011-01-07 01:49:06 +00001159 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump1eb44332009-09-09 15:08:12 +00001160
Anders Carlssonf484c312008-08-31 02:33:12 +00001161 // Fast enumeration state.
Douglas Gregor0815b572011-08-09 17:23:49 +00001162 QualType StateTy = CGM.getObjCFastEnumerationStateType();
Daniel Dunbar195337d2010-02-09 02:48:28 +00001163 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlsson1884eb02010-05-22 17:35:42 +00001164 EmitNullInitialization(StatePtr, StateTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001165
Anders Carlssonf484c312008-08-31 02:33:12 +00001166 // Number of elements in the items array.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001167 static const unsigned NumItems = 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001168
John McCalld88687f2011-01-07 01:49:06 +00001169 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramerad468862010-03-30 11:36:44 +00001170 IdentifierInfo *II[] = {
1171 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1172 &CGM.getContext().Idents.get("objects"),
1173 &CGM.getContext().Idents.get("count")
1174 };
1175 Selector FastEnumSel =
1176 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlssonf484c312008-08-31 02:33:12 +00001177
1178 QualType ItemsTy =
1179 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +00001180 llvm::APInt(32, NumItems),
Anders Carlssonf484c312008-08-31 02:33:12 +00001181 ArrayType::Normal, 0);
Daniel Dunbar195337d2010-02-09 02:48:28 +00001182 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001183
John McCall990567c2011-07-27 01:07:15 +00001184 // Emit the collection pointer. In ARC, we do a retain.
1185 llvm::Value *Collection;
1186 if (getLangOptions().ObjCAutoRefCount) {
1187 Collection = EmitARCRetainScalarExpr(S.getCollection());
1188
1189 // Enter a cleanup to do the release.
1190 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1191 } else {
1192 Collection = EmitScalarExpr(S.getCollection());
1193 }
Mike Stump1eb44332009-09-09 15:08:12 +00001194
John McCall4b302d32011-08-05 00:14:38 +00001195 // The 'continue' label needs to appear within the cleanup for the
1196 // collection object.
1197 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1198
John McCalld88687f2011-01-07 01:49:06 +00001199 // Send it our message:
Anders Carlssonf484c312008-08-31 02:33:12 +00001200 CallArgList Args;
John McCalld88687f2011-01-07 01:49:06 +00001201
1202 // The first argument is a temporary of the enumeration-state type.
Eli Friedman04c9a492011-05-02 17:57:46 +00001203 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001204
John McCalld88687f2011-01-07 01:49:06 +00001205 // The second argument is a temporary array with space for NumItems
1206 // pointers. We'll actually be loading elements from the array
1207 // pointer written into the control state; this buffer is so that
1208 // collections that *aren't* backed by arrays can still queue up
1209 // batches of elements.
Eli Friedman04c9a492011-05-02 17:57:46 +00001210 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001211
John McCalld88687f2011-01-07 01:49:06 +00001212 // The third argument is the capacity of that temporary array.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001213 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001214 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman04c9a492011-05-02 17:57:46 +00001215 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001216
John McCalld88687f2011-01-07 01:49:06 +00001217 // Start the enumeration.
Mike Stump1eb44332009-09-09 15:08:12 +00001218 RValue CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001219 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001220 getContext().UnsignedLongTy,
1221 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001222 Collection, Args);
Anders Carlssonf484c312008-08-31 02:33:12 +00001223
John McCalld88687f2011-01-07 01:49:06 +00001224 // The initial number of objects that were returned in the buffer.
1225 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump1eb44332009-09-09 15:08:12 +00001226
John McCalld88687f2011-01-07 01:49:06 +00001227 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1228 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump1eb44332009-09-09 15:08:12 +00001229
John McCalld88687f2011-01-07 01:49:06 +00001230 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlssonf484c312008-08-31 02:33:12 +00001231
John McCalld88687f2011-01-07 01:49:06 +00001232 // If the limit pointer was zero to begin with, the collection is
1233 // empty; skip all this.
1234 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1235 EmptyBB, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001236
John McCalld88687f2011-01-07 01:49:06 +00001237 // Otherwise, initialize the loop.
1238 EmitBlock(LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001239
John McCalld88687f2011-01-07 01:49:06 +00001240 // Save the initial mutations value. This is the value at an
1241 // address that was written into the state object by
1242 // countByEnumeratingWithState:objects:count:.
Mike Stump1eb44332009-09-09 15:08:12 +00001243 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001244 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001245 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001246 "mutationsptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001247
John McCalld88687f2011-01-07 01:49:06 +00001248 llvm::Value *initialMutations =
1249 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump1eb44332009-09-09 15:08:12 +00001250
John McCalld88687f2011-01-07 01:49:06 +00001251 // Start looping. This is the point we return to whenever we have a
1252 // fresh, non-empty batch of objects.
1253 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1254 EmitBlock(LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001255
John McCalld88687f2011-01-07 01:49:06 +00001256 // The current index into the buffer.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001257 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCalld88687f2011-01-07 01:49:06 +00001258 index->addIncoming(zero, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001259
John McCalld88687f2011-01-07 01:49:06 +00001260 // The current buffer size.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001261 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCalld88687f2011-01-07 01:49:06 +00001262 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001263
John McCalld88687f2011-01-07 01:49:06 +00001264 // Check whether the mutations value has changed from where it was
1265 // at start. StateMutationsPtr should actually be invariant between
1266 // refreshes.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001267 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCalld88687f2011-01-07 01:49:06 +00001268 llvm::Value *currentMutations
1269 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001270
John McCalld88687f2011-01-07 01:49:06 +00001271 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman361cf982011-03-02 22:39:34 +00001272 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump1eb44332009-09-09 15:08:12 +00001273
John McCalld88687f2011-01-07 01:49:06 +00001274 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1275 WasNotMutatedBB, WasMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001276
John McCalld88687f2011-01-07 01:49:06 +00001277 // If so, call the enumeration-mutation function.
1278 EmitBlock(WasMutatedBB);
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001279 llvm::Value *V =
Mike Stump1eb44332009-09-09 15:08:12 +00001280 Builder.CreateBitCast(Collection,
Benjamin Kramer578faa82011-09-27 21:06:10 +00001281 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar2b2105e2009-02-03 23:55:40 +00001282 CallArgList Args2;
Eli Friedman04c9a492011-05-02 17:57:46 +00001283 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stumpf5408fe2009-05-16 07:57:57 +00001284 // FIXME: We shouldn't need to get the function info here, the runtime already
1285 // should have computed it to build the function.
John McCall04a67a62010-02-05 21:31:56 +00001286 EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2,
Rafael Espindola264ba482010-03-30 20:24:48 +00001287 FunctionType::ExtInfo()),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001288 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump1eb44332009-09-09 15:08:12 +00001289
John McCalld88687f2011-01-07 01:49:06 +00001290 // Otherwise, or if the mutation function returns, just continue.
1291 EmitBlock(WasNotMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001292
John McCalld88687f2011-01-07 01:49:06 +00001293 // Initialize the element variable.
1294 RunCleanupsScope elementVariableScope(*this);
John McCall57b3b6a2011-02-22 07:16:58 +00001295 bool elementIsVariable;
John McCalld88687f2011-01-07 01:49:06 +00001296 LValue elementLValue;
1297 QualType elementType;
1298 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall57b3b6a2011-02-22 07:16:58 +00001299 // Initialize the variable, in case it's a __block variable or something.
1300 EmitAutoVarInit(variable);
John McCalld88687f2011-01-07 01:49:06 +00001301
John McCall57b3b6a2011-02-22 07:16:58 +00001302 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCalld88687f2011-01-07 01:49:06 +00001303 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), D->getType(),
1304 VK_LValue, SourceLocation());
1305 elementLValue = EmitLValue(&tempDRE);
1306 elementType = D->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001307 elementIsVariable = true;
John McCall7acddac2011-06-17 06:42:21 +00001308
1309 if (D->isARCPseudoStrong())
1310 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCalld88687f2011-01-07 01:49:06 +00001311 } else {
1312 elementLValue = LValue(); // suppress warning
1313 elementType = cast<Expr>(S.getElement())->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001314 elementIsVariable = false;
John McCalld88687f2011-01-07 01:49:06 +00001315 }
Chris Lattner2acc6e32011-07-18 04:24:23 +00001316 llvm::Type *convertedElementType = ConvertType(elementType);
John McCalld88687f2011-01-07 01:49:06 +00001317
1318 // Fetch the buffer out of the enumeration state.
1319 // TODO: this pointer should actually be invariant between
1320 // refreshes, which would help us do certain loop optimizations.
Mike Stump1eb44332009-09-09 15:08:12 +00001321 llvm::Value *StateItemsPtr =
Anders Carlssonf484c312008-08-31 02:33:12 +00001322 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCalld88687f2011-01-07 01:49:06 +00001323 llvm::Value *EnumStateItems =
1324 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlssonf484c312008-08-31 02:33:12 +00001325
John McCalld88687f2011-01-07 01:49:06 +00001326 // Fetch the value at the current index from the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001327 llvm::Value *CurrentItemPtr =
John McCalld88687f2011-01-07 01:49:06 +00001328 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1329 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001330
John McCalld88687f2011-01-07 01:49:06 +00001331 // Cast that value to the right type.
1332 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1333 "currentitem");
Mike Stump1eb44332009-09-09 15:08:12 +00001334
John McCalld88687f2011-01-07 01:49:06 +00001335 // Make sure we have an l-value. Yes, this gets evaluated every
1336 // time through the loop.
John McCall7acddac2011-06-17 06:42:21 +00001337 if (!elementIsVariable) {
John McCalld88687f2011-01-07 01:49:06 +00001338 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001339 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCall7acddac2011-06-17 06:42:21 +00001340 } else {
1341 EmitScalarInit(CurrentItem, elementLValue);
1342 }
Mike Stump1eb44332009-09-09 15:08:12 +00001343
John McCall57b3b6a2011-02-22 07:16:58 +00001344 // If we do have an element variable, this assignment is the end of
1345 // its initialization.
1346 if (elementIsVariable)
1347 EmitAutoVarCleanups(variable);
1348
John McCalld88687f2011-01-07 01:49:06 +00001349 // Perform the loop body, setting up break and continue labels.
Anders Carlssone4b6d342009-02-10 05:52:02 +00001350 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCalld88687f2011-01-07 01:49:06 +00001351 {
1352 RunCleanupsScope Scope(*this);
1353 EmitStmt(S.getBody());
1354 }
Anders Carlssonf484c312008-08-31 02:33:12 +00001355 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001356
John McCalld88687f2011-01-07 01:49:06 +00001357 // Destroy the element variable now.
1358 elementVariableScope.ForceCleanup();
1359
1360 // Check whether there are more elements.
John McCallff8e1152010-07-23 21:56:41 +00001361 EmitBlock(AfterBody.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001362
John McCalld88687f2011-01-07 01:49:06 +00001363 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanianf0906c42009-01-06 18:56:31 +00001364
John McCalld88687f2011-01-07 01:49:06 +00001365 // First we check in the local buffer.
1366 llvm::Value *indexPlusOne
1367 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlssonf484c312008-08-31 02:33:12 +00001368
John McCalld88687f2011-01-07 01:49:06 +00001369 // If we haven't overrun the buffer yet, we can continue.
1370 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1371 LoopBodyBB, FetchMoreBB);
1372
1373 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1374 count->addIncoming(count, AfterBody.getBlock());
1375
1376 // Otherwise, we have to fetch more elements.
1377 EmitBlock(FetchMoreBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001378
1379 CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001380 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001381 getContext().UnsignedLongTy,
Mike Stump1eb44332009-09-09 15:08:12 +00001382 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001383 Collection, Args);
Mike Stump1eb44332009-09-09 15:08:12 +00001384
John McCalld88687f2011-01-07 01:49:06 +00001385 // If we got a zero count, we're done.
1386 llvm::Value *refetchCount = CountRV.getScalarVal();
1387
1388 // (note that the message send might split FetchMoreBB)
1389 index->addIncoming(zero, Builder.GetInsertBlock());
1390 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1391
1392 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1393 EmptyBB, LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001394
Anders Carlssonf484c312008-08-31 02:33:12 +00001395 // No more elements.
John McCalld88687f2011-01-07 01:49:06 +00001396 EmitBlock(EmptyBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001397
John McCall57b3b6a2011-02-22 07:16:58 +00001398 if (!elementIsVariable) {
Anders Carlssonf484c312008-08-31 02:33:12 +00001399 // If the element was not a declaration, set it to be null.
1400
John McCalld88687f2011-01-07 01:49:06 +00001401 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1402 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001403 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlssonf484c312008-08-31 02:33:12 +00001404 }
1405
Eric Christopher73fb3502011-10-13 21:45:18 +00001406 if (DI)
1407 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001408
John McCall990567c2011-07-27 01:07:15 +00001409 // Leave the cleanup we entered in ARC.
1410 if (getLangOptions().ObjCAutoRefCount)
1411 PopCleanupBlock();
1412
John McCallff8e1152010-07-23 21:56:41 +00001413 EmitBlock(LoopEnd.getBlock());
Anders Carlsson3d8400d2008-08-30 19:51:14 +00001414}
1415
Mike Stump1eb44332009-09-09 15:08:12 +00001416void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001417 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001418}
1419
Mike Stump1eb44332009-09-09 15:08:12 +00001420void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001421 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1422}
1423
Chris Lattner10cac6f2008-11-15 21:26:17 +00001424void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump1eb44332009-09-09 15:08:12 +00001425 const ObjCAtSynchronizedStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001426 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +00001427}
1428
John McCall33e56f32011-09-10 06:18:15 +00001429/// Produce the code for a CK_ARCProduceObject. Just does a
John McCallf85e1932011-06-15 23:02:42 +00001430/// primitive retain.
1431llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1432 llvm::Value *value) {
1433 return EmitARCRetain(type, value);
1434}
1435
1436namespace {
1437 struct CallObjCRelease : EHScopeStack::Cleanup {
John McCallbddfd872011-08-03 22:24:24 +00001438 CallObjCRelease(llvm::Value *object) : object(object) {}
1439 llvm::Value *object;
John McCallf85e1932011-06-15 23:02:42 +00001440
John McCallad346f42011-07-12 20:27:29 +00001441 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001442 CGF.EmitARCRelease(object, /*precise*/ true);
John McCallf85e1932011-06-15 23:02:42 +00001443 }
1444 };
1445}
1446
John McCall33e56f32011-09-10 06:18:15 +00001447/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCallf85e1932011-06-15 23:02:42 +00001448/// release at the end of the full-expression.
1449llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1450 llvm::Value *object) {
1451 // If we're in a conditional branch, we need to make the cleanup
John McCallbddfd872011-08-03 22:24:24 +00001452 // conditional.
1453 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCallf85e1932011-06-15 23:02:42 +00001454 return object;
1455}
1456
1457llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1458 llvm::Value *value) {
1459 return EmitARCRetainAutorelease(type, value);
1460}
1461
1462
1463static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001464 llvm::FunctionType *type,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001465 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001466 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1467
1468 // In -fobjc-no-arc-runtime, emit weak references to the runtime
1469 // support library.
John McCall9f084a32011-07-06 00:26:06 +00001470 if (!CGM.getCodeGenOpts().ObjCRuntimeHasARC)
John McCallf85e1932011-06-15 23:02:42 +00001471 if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
1472 f->setLinkage(llvm::Function::ExternalWeakLinkage);
1473
1474 return fn;
1475}
1476
1477/// Perform an operation having the signature
1478/// i8* (i8*)
1479/// where a null input causes a no-op and returns null.
1480static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1481 llvm::Value *value,
1482 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001483 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001484 if (isa<llvm::ConstantPointerNull>(value)) return value;
1485
1486 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001487 std::vector<llvm::Type*> args(1, CGF.Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001488 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001489 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1490 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1491 }
1492
1493 // Cast the argument to 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001494 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001495 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1496
1497 // Call the function.
1498 llvm::CallInst *call = CGF.Builder.CreateCall(fn, value);
1499 call->setDoesNotThrow();
1500
1501 // Cast the result back to the original type.
1502 return CGF.Builder.CreateBitCast(call, origType);
1503}
1504
1505/// Perform an operation having the following signature:
1506/// i8* (i8**)
1507static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1508 llvm::Value *addr,
1509 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001510 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001511 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001512 std::vector<llvm::Type*> args(1, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001513 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001514 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1515 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1516 }
1517
1518 // Cast the argument to 'id*'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001519 llvm::Type *origType = addr->getType();
John McCallf85e1932011-06-15 23:02:42 +00001520 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1521
1522 // Call the function.
1523 llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr);
1524 call->setDoesNotThrow();
1525
1526 // Cast the result back to a dereference of the original type.
1527 llvm::Value *result = call;
1528 if (origType != CGF.Int8PtrPtrTy)
1529 result = CGF.Builder.CreateBitCast(result,
1530 cast<llvm::PointerType>(origType)->getElementType());
1531
1532 return result;
1533}
1534
1535/// Perform an operation having the following signature:
1536/// i8* (i8**, i8*)
1537static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1538 llvm::Value *addr,
1539 llvm::Value *value,
1540 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001541 StringRef fnName,
John McCallf85e1932011-06-15 23:02:42 +00001542 bool ignored) {
1543 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1544 == value->getType());
1545
1546 if (!fn) {
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00001547 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
John McCallf85e1932011-06-15 23:02:42 +00001548
Chris Lattner2acc6e32011-07-18 04:24:23 +00001549 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001550 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1551 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1552 }
1553
Chris Lattner2acc6e32011-07-18 04:24:23 +00001554 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001555
1556 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1557 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1558
1559 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value);
1560 result->setDoesNotThrow();
1561
1562 if (ignored) return 0;
1563
1564 return CGF.Builder.CreateBitCast(result, origType);
1565}
1566
1567/// Perform an operation having the following signature:
1568/// void (i8**, i8**)
1569static void emitARCCopyOperation(CodeGenFunction &CGF,
1570 llvm::Value *dst,
1571 llvm::Value *src,
1572 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001573 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001574 assert(dst->getType() == src->getType());
1575
1576 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001577 std::vector<llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001578 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001579 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1580 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1581 }
1582
1583 dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy);
1584 src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy);
1585
1586 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src);
1587 result->setDoesNotThrow();
1588}
1589
1590/// Produce the code to do a retain. Based on the type, calls one of:
1591/// call i8* @objc_retain(i8* %value)
1592/// call i8* @objc_retainBlock(i8* %value)
1593llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1594 if (type->isBlockPointerType())
John McCall348f16f2011-10-04 06:23:45 +00001595 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallf85e1932011-06-15 23:02:42 +00001596 else
1597 return EmitARCRetainNonBlock(value);
1598}
1599
1600/// Retain the given object, with normal retain semantics.
1601/// call i8* @objc_retain(i8* %value)
1602llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1603 return emitARCValueOperation(*this, value,
1604 CGM.getARCEntrypoints().objc_retain,
1605 "objc_retain");
1606}
1607
1608/// Retain the given block, with _Block_copy semantics.
1609/// call i8* @objc_retainBlock(i8* %value)
John McCall348f16f2011-10-04 06:23:45 +00001610///
1611/// \param mandatory - If false, emit the call with metadata
1612/// indicating that it's okay for the optimizer to eliminate this call
1613/// if it can prove that the block never escapes except down the stack.
1614llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1615 bool mandatory) {
1616 llvm::Value *result
1617 = emitARCValueOperation(*this, value,
1618 CGM.getARCEntrypoints().objc_retainBlock,
1619 "objc_retainBlock");
1620
1621 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1622 // tell the optimizer that it doesn't need to do this copy if the
1623 // block doesn't escape, where being passed as an argument doesn't
1624 // count as escaping.
1625 if (!mandatory && isa<llvm::Instruction>(result)) {
1626 llvm::CallInst *call
1627 = cast<llvm::CallInst>(result->stripPointerCasts());
1628 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
1629
1630 SmallVector<llvm::Value*,1> args;
1631 call->setMetadata("clang.arc.copy_on_escape",
1632 llvm::MDNode::get(Builder.getContext(), args));
1633 }
1634
1635 return result;
John McCallf85e1932011-06-15 23:02:42 +00001636}
1637
1638/// Retain the given object which is the result of a function call.
1639/// call i8* @objc_retainAutoreleasedReturnValue(i8* %value)
1640///
1641/// Yes, this function name is one character away from a different
1642/// call with completely different semantics.
1643llvm::Value *
1644CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1645 // Fetch the void(void) inline asm which marks that we're going to
1646 // retain the autoreleased return value.
1647 llvm::InlineAsm *&marker
1648 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1649 if (!marker) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001650 StringRef assembly
John McCallf85e1932011-06-15 23:02:42 +00001651 = CGM.getTargetCodeGenInfo()
1652 .getARCRetainAutoreleasedReturnValueMarker();
1653
1654 // If we have an empty assembly string, there's nothing to do.
1655 if (assembly.empty()) {
1656
1657 // Otherwise, at -O0, build an inline asm that we're going to call
1658 // in a moment.
1659 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1660 llvm::FunctionType *type =
1661 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
1662 /*variadic*/ false);
1663
1664 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1665
1666 // If we're at -O1 and above, we don't want to litter the code
1667 // with this marker yet, so leave a breadcrumb for the ARC
1668 // optimizer to pick up.
1669 } else {
1670 llvm::NamedMDNode *metadata =
1671 CGM.getModule().getOrInsertNamedMetadata(
1672 "clang.arc.retainAutoreleasedReturnValueMarker");
1673 assert(metadata->getNumOperands() <= 1);
1674 if (metadata->getNumOperands() == 0) {
1675 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
Jay Foadda549e82011-07-29 13:56:53 +00001676 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
John McCallf85e1932011-06-15 23:02:42 +00001677 }
1678 }
1679 }
1680
1681 // Call the marker asm if we made one, which we do only at -O0.
1682 if (marker) Builder.CreateCall(marker);
1683
1684 return emitARCValueOperation(*this, value,
1685 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1686 "objc_retainAutoreleasedReturnValue");
1687}
1688
1689/// Release the given object.
1690/// call void @objc_release(i8* %value)
1691void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) {
1692 if (isa<llvm::ConstantPointerNull>(value)) return;
1693
1694 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1695 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001696 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001697 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001698 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1699 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1700 }
1701
1702 // Cast the argument to 'id'.
1703 value = Builder.CreateBitCast(value, Int8PtrTy);
1704
1705 // Call objc_release.
1706 llvm::CallInst *call = Builder.CreateCall(fn, value);
1707 call->setDoesNotThrow();
1708
1709 if (!precise) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001710 SmallVector<llvm::Value*,1> args;
John McCallf85e1932011-06-15 23:02:42 +00001711 call->setMetadata("clang.imprecise_release",
1712 llvm::MDNode::get(Builder.getContext(), args));
1713 }
1714}
1715
1716/// Store into a strong object. Always calls this:
1717/// call void @objc_storeStrong(i8** %addr, i8* %value)
1718llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
1719 llvm::Value *value,
1720 bool ignored) {
1721 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1722 == value->getType());
1723
1724 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
1725 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001726 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2acc6e32011-07-18 04:24:23 +00001727 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001728 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
1729 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
1730 }
1731
1732 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1733 llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy);
1734
1735 Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow();
1736
1737 if (ignored) return 0;
1738 return value;
1739}
1740
1741/// Store into a strong object. Sometimes calls this:
1742/// call void @objc_storeStrong(i8** %addr, i8* %value)
1743/// Other times, breaks it down into components.
John McCall545d9962011-06-25 02:11:03 +00001744llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCallf85e1932011-06-15 23:02:42 +00001745 llvm::Value *newValue,
1746 bool ignored) {
John McCall545d9962011-06-25 02:11:03 +00001747 QualType type = dst.getType();
John McCallf85e1932011-06-15 23:02:42 +00001748 bool isBlock = type->isBlockPointerType();
1749
1750 // Use a store barrier at -O0 unless this is a block type or the
1751 // lvalue is inadequately aligned.
1752 if (shouldUseFusedARCCalls() &&
1753 !isBlock &&
Eli Friedman6da2c712011-12-03 04:14:32 +00001754 (dst.getAlignment().isZero() ||
1755 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCallf85e1932011-06-15 23:02:42 +00001756 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
1757 }
1758
1759 // Otherwise, split it out.
1760
1761 // Retain the new value.
1762 newValue = EmitARCRetain(type, newValue);
1763
1764 // Read the old value.
John McCall545d9962011-06-25 02:11:03 +00001765 llvm::Value *oldValue = EmitLoadOfScalar(dst);
John McCallf85e1932011-06-15 23:02:42 +00001766
1767 // Store. We do this before the release so that any deallocs won't
1768 // see the old value.
John McCall545d9962011-06-25 02:11:03 +00001769 EmitStoreOfScalar(newValue, dst);
John McCallf85e1932011-06-15 23:02:42 +00001770
1771 // Finally, release the old value.
1772 EmitARCRelease(oldValue, /*precise*/ false);
1773
1774 return newValue;
1775}
1776
1777/// Autorelease the given object.
1778/// call i8* @objc_autorelease(i8* %value)
1779llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
1780 return emitARCValueOperation(*this, value,
1781 CGM.getARCEntrypoints().objc_autorelease,
1782 "objc_autorelease");
1783}
1784
1785/// Autorelease the given object.
1786/// call i8* @objc_autoreleaseReturnValue(i8* %value)
1787llvm::Value *
1788CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
1789 return emitARCValueOperation(*this, value,
1790 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
1791 "objc_autoreleaseReturnValue");
1792}
1793
1794/// Do a fused retain/autorelease of the given object.
1795/// call i8* @objc_retainAutoreleaseReturnValue(i8* %value)
1796llvm::Value *
1797CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
1798 return emitARCValueOperation(*this, value,
1799 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
1800 "objc_retainAutoreleaseReturnValue");
1801}
1802
1803/// Do a fused retain/autorelease of the given object.
1804/// call i8* @objc_retainAutorelease(i8* %value)
1805/// or
1806/// %retain = call i8* @objc_retainBlock(i8* %value)
1807/// call i8* @objc_autorelease(i8* %retain)
1808llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
1809 llvm::Value *value) {
1810 if (!type->isBlockPointerType())
1811 return EmitARCRetainAutoreleaseNonBlock(value);
1812
1813 if (isa<llvm::ConstantPointerNull>(value)) return value;
1814
Chris Lattner2acc6e32011-07-18 04:24:23 +00001815 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001816 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCall348f16f2011-10-04 06:23:45 +00001817 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCallf85e1932011-06-15 23:02:42 +00001818 value = EmitARCAutorelease(value);
1819 return Builder.CreateBitCast(value, origType);
1820}
1821
1822/// Do a fused retain/autorelease of the given object.
1823/// call i8* @objc_retainAutorelease(i8* %value)
1824llvm::Value *
1825CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
1826 return emitARCValueOperation(*this, value,
1827 CGM.getARCEntrypoints().objc_retainAutorelease,
1828 "objc_retainAutorelease");
1829}
1830
1831/// i8* @objc_loadWeak(i8** %addr)
1832/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
1833llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
1834 return emitARCLoadOperation(*this, addr,
1835 CGM.getARCEntrypoints().objc_loadWeak,
1836 "objc_loadWeak");
1837}
1838
1839/// i8* @objc_loadWeakRetained(i8** %addr)
1840llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
1841 return emitARCLoadOperation(*this, addr,
1842 CGM.getARCEntrypoints().objc_loadWeakRetained,
1843 "objc_loadWeakRetained");
1844}
1845
1846/// i8* @objc_storeWeak(i8** %addr, i8* %value)
1847/// Returns %value.
1848llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
1849 llvm::Value *value,
1850 bool ignored) {
1851 return emitARCStoreOperation(*this, addr, value,
1852 CGM.getARCEntrypoints().objc_storeWeak,
1853 "objc_storeWeak", ignored);
1854}
1855
1856/// i8* @objc_initWeak(i8** %addr, i8* %value)
1857/// Returns %value. %addr is known to not have a current weak entry.
1858/// Essentially equivalent to:
1859/// *addr = nil; objc_storeWeak(addr, value);
1860void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
1861 // If we're initializing to null, just write null to memory; no need
1862 // to get the runtime involved. But don't do this if optimization
1863 // is enabled, because accounting for this would make the optimizer
1864 // much more complicated.
1865 if (isa<llvm::ConstantPointerNull>(value) &&
1866 CGM.getCodeGenOpts().OptimizationLevel == 0) {
1867 Builder.CreateStore(value, addr);
1868 return;
1869 }
1870
1871 emitARCStoreOperation(*this, addr, value,
1872 CGM.getARCEntrypoints().objc_initWeak,
1873 "objc_initWeak", /*ignored*/ true);
1874}
1875
1876/// void @objc_destroyWeak(i8** %addr)
1877/// Essentially objc_storeWeak(addr, nil).
1878void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
1879 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
1880 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001881 std::vector<llvm::Type*> args(1, Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001882 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001883 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1884 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
1885 }
1886
1887 // Cast the argument to 'id*'.
1888 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1889
1890 llvm::CallInst *call = Builder.CreateCall(fn, addr);
1891 call->setDoesNotThrow();
1892}
1893
1894/// void @objc_moveWeak(i8** %dest, i8** %src)
1895/// Disregards the current value in %dest. Leaves %src pointing to nothing.
1896/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
1897void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
1898 emitARCCopyOperation(*this, dst, src,
1899 CGM.getARCEntrypoints().objc_moveWeak,
1900 "objc_moveWeak");
1901}
1902
1903/// void @objc_copyWeak(i8** %dest, i8** %src)
1904/// Disregards the current value in %dest. Essentially
1905/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
1906void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
1907 emitARCCopyOperation(*this, dst, src,
1908 CGM.getARCEntrypoints().objc_copyWeak,
1909 "objc_copyWeak");
1910}
1911
1912/// Produce the code to do a objc_autoreleasepool_push.
1913/// call i8* @objc_autoreleasePoolPush(void)
1914llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
1915 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
1916 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001917 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001918 llvm::FunctionType::get(Int8PtrTy, false);
1919 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
1920 }
1921
1922 llvm::CallInst *call = Builder.CreateCall(fn);
1923 call->setDoesNotThrow();
1924
1925 return call;
1926}
1927
1928/// Produce the code to do a primitive release.
1929/// call void @objc_autoreleasePoolPop(i8* %ptr)
1930void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
1931 assert(value->getType() == Int8PtrTy);
1932
1933 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
1934 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001935 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001936 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001937 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1938
1939 // We don't want to use a weak import here; instead we should not
1940 // fall into this path.
1941 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
1942 }
1943
1944 llvm::CallInst *call = Builder.CreateCall(fn, value);
1945 call->setDoesNotThrow();
1946}
1947
1948/// Produce the code to do an MRR version objc_autoreleasepool_push.
1949/// Which is: [[NSAutoreleasePool alloc] init];
1950/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
1951/// init is declared as: - (id) init; in its NSObject super class.
1952///
1953llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
1954 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
1955 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder);
1956 // [NSAutoreleasePool alloc]
1957 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
1958 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
1959 CallArgList Args;
1960 RValue AllocRV =
1961 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
1962 getContext().getObjCIdType(),
1963 AllocSel, Receiver, Args);
1964
1965 // [Receiver init]
1966 Receiver = AllocRV.getScalarVal();
1967 II = &CGM.getContext().Idents.get("init");
1968 Selector InitSel = getContext().Selectors.getSelector(0, &II);
1969 RValue InitRV =
1970 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
1971 getContext().getObjCIdType(),
1972 InitSel, Receiver, Args);
1973 return InitRV.getScalarVal();
1974}
1975
1976/// Produce the code to do a primitive release.
1977/// [tmp drain];
1978void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
1979 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
1980 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
1981 CallArgList Args;
1982 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1983 getContext().VoidTy, DrainSel, Arg, Args);
1984}
1985
John McCallbdc4d802011-07-09 01:37:26 +00001986void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
1987 llvm::Value *addr,
1988 QualType type) {
1989 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
1990 CGF.EmitARCRelease(ptr, /*precise*/ true);
1991}
1992
1993void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
1994 llvm::Value *addr,
1995 QualType type) {
1996 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
1997 CGF.EmitARCRelease(ptr, /*precise*/ false);
1998}
1999
2000void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2001 llvm::Value *addr,
2002 QualType type) {
2003 CGF.EmitARCDestroyWeak(addr);
2004}
2005
John McCallf85e1932011-06-15 23:02:42 +00002006namespace {
John McCallf85e1932011-06-15 23:02:42 +00002007 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2008 llvm::Value *Token;
2009
2010 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2011
John McCallad346f42011-07-12 20:27:29 +00002012 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002013 CGF.EmitObjCAutoreleasePoolPop(Token);
2014 }
2015 };
2016 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2017 llvm::Value *Token;
2018
2019 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2020
John McCallad346f42011-07-12 20:27:29 +00002021 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002022 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2023 }
2024 };
2025}
2026
2027void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
2028 if (CGM.getLangOptions().ObjCAutoRefCount)
2029 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2030 else
2031 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2032}
2033
John McCallf85e1932011-06-15 23:02:42 +00002034static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2035 LValue lvalue,
2036 QualType type) {
2037 switch (type.getObjCLifetime()) {
2038 case Qualifiers::OCL_None:
2039 case Qualifiers::OCL_ExplicitNone:
2040 case Qualifiers::OCL_Strong:
2041 case Qualifiers::OCL_Autoreleasing:
John McCall545d9962011-06-25 02:11:03 +00002042 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(),
John McCallf85e1932011-06-15 23:02:42 +00002043 false);
2044
2045 case Qualifiers::OCL_Weak:
2046 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2047 true);
2048 }
2049
2050 llvm_unreachable("impossible lifetime!");
2051 return TryEmitResult();
2052}
2053
2054static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2055 const Expr *e) {
2056 e = e->IgnoreParens();
2057 QualType type = e->getType();
2058
John McCall21480112011-08-30 00:57:29 +00002059 // If we're loading retained from a __strong xvalue, we can avoid
2060 // an extra retain/release pair by zeroing out the source of this
2061 // "move" operation.
2062 if (e->isXValue() &&
2063 !type.isConstQualified() &&
2064 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2065 // Emit the lvalue.
2066 LValue lv = CGF.EmitLValue(e);
2067
2068 // Load the object pointer.
2069 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal();
2070
2071 // Set the source pointer to NULL.
2072 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2073
2074 return TryEmitResult(result, true);
2075 }
2076
John McCallf85e1932011-06-15 23:02:42 +00002077 // As a very special optimization, in ARC++, if the l-value is the
2078 // result of a non-volatile assignment, do a simple retain of the
2079 // result of the call to objc_storeWeak instead of reloading.
2080 if (CGF.getLangOptions().CPlusPlus &&
2081 !type.isVolatileQualified() &&
2082 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2083 isa<BinaryOperator>(e) &&
2084 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2085 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2086
2087 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2088}
2089
2090static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2091 llvm::Value *value);
2092
2093/// Given that the given expression is some sort of call (which does
2094/// not return retained), emit a retain following it.
2095static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2096 llvm::Value *value = CGF.EmitScalarExpr(e);
2097 return emitARCRetainAfterCall(CGF, value);
2098}
2099
2100static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2101 llvm::Value *value) {
2102 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2103 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2104
2105 // Place the retain immediately following the call.
2106 CGF.Builder.SetInsertPoint(call->getParent(),
2107 ++llvm::BasicBlock::iterator(call));
2108 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2109
2110 CGF.Builder.restoreIP(ip);
2111 return value;
2112 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2113 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2114
2115 // Place the retain at the beginning of the normal destination block.
2116 llvm::BasicBlock *BB = invoke->getNormalDest();
2117 CGF.Builder.SetInsertPoint(BB, BB->begin());
2118 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2119
2120 CGF.Builder.restoreIP(ip);
2121 return value;
2122
2123 // Bitcasts can arise because of related-result returns. Rewrite
2124 // the operand.
2125 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2126 llvm::Value *operand = bitcast->getOperand(0);
2127 operand = emitARCRetainAfterCall(CGF, operand);
2128 bitcast->setOperand(0, operand);
2129 return bitcast;
2130
2131 // Generic fall-back case.
2132 } else {
2133 // Retain using the non-block variant: we never need to do a copy
2134 // of a block that's been returned to us.
2135 return CGF.EmitARCRetainNonBlock(value);
2136 }
2137}
2138
John McCalldc05b112011-09-10 01:16:55 +00002139/// Determine whether it might be important to emit a separate
2140/// objc_retain_block on the result of the given expression, or
2141/// whether it's okay to just emit it in a +1 context.
2142static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2143 assert(e->getType()->isBlockPointerType());
2144 e = e->IgnoreParens();
2145
2146 // For future goodness, emit block expressions directly in +1
2147 // contexts if we can.
2148 if (isa<BlockExpr>(e))
2149 return false;
2150
2151 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2152 switch (cast->getCastKind()) {
2153 // Emitting these operations in +1 contexts is goodness.
2154 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00002155 case CK_ARCReclaimReturnedObject:
2156 case CK_ARCConsumeObject:
2157 case CK_ARCProduceObject:
John McCalldc05b112011-09-10 01:16:55 +00002158 return false;
2159
2160 // These operations preserve a block type.
2161 case CK_NoOp:
2162 case CK_BitCast:
2163 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2164
2165 // These operations are known to be bad (or haven't been considered).
2166 case CK_AnyPointerToBlockPointerCast:
2167 default:
2168 return true;
2169 }
2170 }
2171
2172 return true;
2173}
2174
John McCall4b9c2d22011-11-06 09:01:30 +00002175/// Try to emit a PseudoObjectExpr at +1.
2176///
2177/// This massively duplicates emitPseudoObjectRValue.
2178static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
2179 const PseudoObjectExpr *E) {
2180 llvm::SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
2181
2182 // Find the result expression.
2183 const Expr *resultExpr = E->getResultExpr();
2184 assert(resultExpr);
2185 TryEmitResult result;
2186
2187 for (PseudoObjectExpr::const_semantics_iterator
2188 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2189 const Expr *semantic = *i;
2190
2191 // If this semantic expression is an opaque value, bind it
2192 // to the result of its source expression.
2193 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2194 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2195 OVMA opaqueData;
2196
2197 // If this semantic is the result of the pseudo-object
2198 // expression, try to evaluate the source as +1.
2199 if (ov == resultExpr) {
2200 assert(!OVMA::shouldBindAsLValue(ov));
2201 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
2202 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
2203
2204 // Otherwise, just bind it.
2205 } else {
2206 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2207 }
2208 opaques.push_back(opaqueData);
2209
2210 // Otherwise, if the expression is the result, evaluate it
2211 // and remember the result.
2212 } else if (semantic == resultExpr) {
2213 result = tryEmitARCRetainScalarExpr(CGF, semantic);
2214
2215 // Otherwise, evaluate the expression in an ignored context.
2216 } else {
2217 CGF.EmitIgnoredExpr(semantic);
2218 }
2219 }
2220
2221 // Unbind all the opaques now.
2222 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2223 opaques[i].unbind(CGF);
2224
2225 return result;
2226}
2227
John McCallf85e1932011-06-15 23:02:42 +00002228static TryEmitResult
2229tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCall990567c2011-07-27 01:07:15 +00002230 // Look through cleanups.
2231 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
John McCall1a343eb2011-11-10 08:15:53 +00002232 CGF.enterFullExpression(cleanups);
John McCall990567c2011-07-27 01:07:15 +00002233 CodeGenFunction::RunCleanupsScope scope(CGF);
2234 return tryEmitARCRetainScalarExpr(CGF, cleanups->getSubExpr());
2235 }
2236
John McCallf85e1932011-06-15 23:02:42 +00002237 // The desired result type, if it differs from the type of the
2238 // ultimate opaque expression.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002239 llvm::Type *resultType = 0;
John McCallf85e1932011-06-15 23:02:42 +00002240
2241 while (true) {
2242 e = e->IgnoreParens();
2243
2244 // There's a break at the end of this if-chain; anything
2245 // that wants to keep looping has to explicitly continue.
2246 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2247 switch (ce->getCastKind()) {
2248 // No-op casts don't change the type, so we just ignore them.
2249 case CK_NoOp:
2250 e = ce->getSubExpr();
2251 continue;
2252
2253 case CK_LValueToRValue: {
2254 TryEmitResult loadResult
2255 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2256 if (resultType) {
2257 llvm::Value *value = loadResult.getPointer();
2258 value = CGF.Builder.CreateBitCast(value, resultType);
2259 loadResult.setPointer(value);
2260 }
2261 return loadResult;
2262 }
2263
2264 // These casts can change the type, so remember that and
2265 // soldier on. We only need to remember the outermost such
2266 // cast, though.
John McCall1d9b3b22011-09-09 05:25:32 +00002267 case CK_CPointerToObjCPointerCast:
2268 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00002269 case CK_AnyPointerToBlockPointerCast:
2270 case CK_BitCast:
2271 if (!resultType)
2272 resultType = CGF.ConvertType(ce->getType());
2273 e = ce->getSubExpr();
2274 assert(e->getType()->hasPointerRepresentation());
2275 continue;
2276
2277 // For consumptions, just emit the subexpression and thus elide
2278 // the retain/release pair.
John McCall33e56f32011-09-10 06:18:15 +00002279 case CK_ARCConsumeObject: {
John McCallf85e1932011-06-15 23:02:42 +00002280 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2281 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2282 return TryEmitResult(result, true);
2283 }
2284
John McCalldc05b112011-09-10 01:16:55 +00002285 // Block extends are net +0. Naively, we could just recurse on
2286 // the subexpression, but actually we need to ensure that the
2287 // value is copied as a block, so there's a little filter here.
John McCall33e56f32011-09-10 06:18:15 +00002288 case CK_ARCExtendBlockObject: {
John McCalldc05b112011-09-10 01:16:55 +00002289 llvm::Value *result; // will be a +0 value
2290
2291 // If we can't safely assume the sub-expression will produce a
2292 // block-copied value, emit the sub-expression at +0.
2293 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2294 result = CGF.EmitScalarExpr(ce->getSubExpr());
2295
2296 // Otherwise, try to emit the sub-expression at +1 recursively.
2297 } else {
2298 TryEmitResult subresult
2299 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2300 result = subresult.getPointer();
2301
2302 // If that produced a retained value, just use that,
2303 // possibly casting down.
2304 if (subresult.getInt()) {
2305 if (resultType)
2306 result = CGF.Builder.CreateBitCast(result, resultType);
2307 return TryEmitResult(result, true);
2308 }
2309
2310 // Otherwise it's +0.
2311 }
2312
2313 // Retain the object as a block, then cast down.
John McCall348f16f2011-10-04 06:23:45 +00002314 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
John McCalldc05b112011-09-10 01:16:55 +00002315 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2316 return TryEmitResult(result, true);
2317 }
2318
John McCall7e5e5f42011-07-07 06:58:02 +00002319 // For reclaims, emit the subexpression as a retained call and
2320 // skip the consumption.
John McCall33e56f32011-09-10 06:18:15 +00002321 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00002322 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2323 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2324 return TryEmitResult(result, true);
2325 }
2326
John McCallf85e1932011-06-15 23:02:42 +00002327 default:
2328 break;
2329 }
2330
2331 // Skip __extension__.
2332 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2333 if (op->getOpcode() == UO_Extension) {
2334 e = op->getSubExpr();
2335 continue;
2336 }
2337
2338 // For calls and message sends, use the retained-call logic.
2339 // Delegate inits are a special case in that they're the only
2340 // returns-retained expression that *isn't* surrounded by
2341 // a consume.
2342 } else if (isa<CallExpr>(e) ||
2343 (isa<ObjCMessageExpr>(e) &&
2344 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2345 llvm::Value *result = emitARCRetainCall(CGF, e);
2346 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2347 return TryEmitResult(result, true);
John McCall4b9c2d22011-11-06 09:01:30 +00002348
2349 // Look through pseudo-object expressions.
2350 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2351 TryEmitResult result
2352 = tryEmitARCRetainPseudoObject(CGF, pseudo);
2353 if (resultType) {
2354 llvm::Value *value = result.getPointer();
2355 value = CGF.Builder.CreateBitCast(value, resultType);
2356 result.setPointer(value);
2357 }
2358 return result;
John McCallf85e1932011-06-15 23:02:42 +00002359 }
2360
2361 // Conservatively halt the search at any other expression kind.
2362 break;
2363 }
2364
2365 // We didn't find an obvious production, so emit what we've got and
2366 // tell the caller that we didn't manage to retain.
2367 llvm::Value *result = CGF.EmitScalarExpr(e);
2368 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2369 return TryEmitResult(result, false);
2370}
2371
2372static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2373 LValue lvalue,
2374 QualType type) {
2375 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2376 llvm::Value *value = result.getPointer();
2377 if (!result.getInt())
2378 value = CGF.EmitARCRetain(type, value);
2379 return value;
2380}
2381
2382/// EmitARCRetainScalarExpr - Semantically equivalent to
2383/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2384/// best-effort attempt to peephole expressions that naturally produce
2385/// retained objects.
2386llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
2387 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2388 llvm::Value *value = result.getPointer();
2389 if (!result.getInt())
2390 value = EmitARCRetain(e->getType(), value);
2391 return value;
2392}
2393
2394llvm::Value *
2395CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
2396 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2397 llvm::Value *value = result.getPointer();
2398 if (result.getInt())
2399 value = EmitARCAutorelease(value);
2400 else
2401 value = EmitARCRetainAutorelease(e->getType(), value);
2402 return value;
2403}
2404
John McCall348f16f2011-10-04 06:23:45 +00002405llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2406 llvm::Value *result;
2407 bool doRetain;
2408
2409 if (shouldEmitSeparateBlockRetain(e)) {
2410 result = EmitScalarExpr(e);
2411 doRetain = true;
2412 } else {
2413 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2414 result = subresult.getPointer();
2415 doRetain = !subresult.getInt();
2416 }
2417
2418 if (doRetain)
2419 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2420 return EmitObjCConsumeObject(e->getType(), result);
2421}
2422
John McCall2b014d62011-10-01 10:32:24 +00002423llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2424 // In ARC, retain and autorelease the expression.
2425 if (getLangOptions().ObjCAutoRefCount) {
2426 // Do so before running any cleanups for the full-expression.
2427 // tryEmitARCRetainScalarExpr does make an effort to do things
2428 // inside cleanups, but there are crazy cases like
2429 // @throw A().foo;
2430 // where a full retain+autorelease is required and would
2431 // otherwise happen after the destructor for the temporary.
John McCall1a343eb2011-11-10 08:15:53 +00002432 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(expr)) {
2433 enterFullExpression(ewc);
John McCall2b014d62011-10-01 10:32:24 +00002434 expr = ewc->getSubExpr();
John McCall1a343eb2011-11-10 08:15:53 +00002435 }
John McCall2b014d62011-10-01 10:32:24 +00002436
John McCall1a343eb2011-11-10 08:15:53 +00002437 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall2b014d62011-10-01 10:32:24 +00002438 return EmitARCRetainAutoreleaseScalarExpr(expr);
2439 }
2440
2441 // Otherwise, use the normal scalar-expression emission. The
2442 // exception machinery doesn't do anything special with the
2443 // exception like retaining it, so there's no safety associated with
2444 // only running cleanups after the throw has started, and when it
2445 // matters it tends to be substantially inferior code.
2446 return EmitScalarExpr(expr);
2447}
2448
John McCallf85e1932011-06-15 23:02:42 +00002449std::pair<LValue,llvm::Value*>
2450CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2451 bool ignored) {
2452 // Evaluate the RHS first.
2453 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2454 llvm::Value *value = result.getPointer();
2455
John McCallfb720812011-07-28 07:23:35 +00002456 bool hasImmediateRetain = result.getInt();
2457
2458 // If we didn't emit a retained object, and the l-value is of block
2459 // type, then we need to emit the block-retain immediately in case
2460 // it invalidates the l-value.
2461 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCall348f16f2011-10-04 06:23:45 +00002462 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallfb720812011-07-28 07:23:35 +00002463 hasImmediateRetain = true;
2464 }
2465
John McCallf85e1932011-06-15 23:02:42 +00002466 LValue lvalue = EmitLValue(e->getLHS());
2467
2468 // If the RHS was emitted retained, expand this.
John McCallfb720812011-07-28 07:23:35 +00002469 if (hasImmediateRetain) {
John McCallf85e1932011-06-15 23:02:42 +00002470 llvm::Value *oldValue =
Eli Friedman6da2c712011-12-03 04:14:32 +00002471 EmitLoadOfScalar(lvalue);
2472 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +00002473 EmitARCRelease(oldValue, /*precise*/ false);
2474 } else {
John McCall545d9962011-06-25 02:11:03 +00002475 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCallf85e1932011-06-15 23:02:42 +00002476 }
2477
2478 return std::pair<LValue,llvm::Value*>(lvalue, value);
2479}
2480
2481std::pair<LValue,llvm::Value*>
2482CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2483 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2484 LValue lvalue = EmitLValue(e->getLHS());
2485
Eli Friedman6da2c712011-12-03 04:14:32 +00002486 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +00002487
2488 return std::pair<LValue,llvm::Value*>(lvalue, value);
2489}
2490
2491void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
2492 const ObjCAutoreleasePoolStmt &ARPS) {
2493 const Stmt *subStmt = ARPS.getSubStmt();
2494 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2495
2496 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00002497 if (DI)
2498 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002499
2500 // Keep track of the current cleanup stack depth.
2501 RunCleanupsScope Scope(*this);
John McCall9f084a32011-07-06 00:26:06 +00002502 if (CGM.getCodeGenOpts().ObjCRuntimeHasARC) {
John McCallf85e1932011-06-15 23:02:42 +00002503 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2504 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2505 } else {
2506 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2507 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2508 }
2509
2510 for (CompoundStmt::const_body_iterator I = S.body_begin(),
2511 E = S.body_end(); I != E; ++I)
2512 EmitStmt(*I);
2513
Eric Christopher73fb3502011-10-13 21:45:18 +00002514 if (DI)
2515 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002516}
John McCall0c24c802011-06-24 23:21:27 +00002517
2518/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2519/// make sure it survives garbage collection until this point.
2520void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2521 // We just use an inline assembly.
John McCall0c24c802011-06-24 23:21:27 +00002522 llvm::FunctionType *extenderType
Jay Foadda549e82011-07-29 13:56:53 +00002523 = llvm::FunctionType::get(VoidTy, VoidPtrTy, /*variadic*/ false);
John McCall0c24c802011-06-24 23:21:27 +00002524 llvm::Value *extender
2525 = llvm::InlineAsm::get(extenderType,
2526 /* assembly */ "",
2527 /* constraints */ "r",
2528 /* side effects */ true);
2529
2530 object = Builder.CreateBitCast(object, VoidPtrTy);
2531 Builder.CreateCall(extender, object)->setDoesNotThrow();
2532}
2533
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002534/// GenerateObjCAtomicCopyHelperFunction - Given a c++ object type with
2535/// non-trivial copy assignment function, produce following helper function.
2536/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
2537///
2538llvm::Constant *
2539CodeGenFunction::GenerateObjCAtomicCopyHelperFunction(
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +00002540 const ObjCPropertyImplDecl *PID,
2541 bool forSetter) {
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002542 // FIXME. This api is for NeXt runtime only for now.
2543 if (!getLangOptions().CPlusPlus || !getLangOptions().NeXTRuntime)
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002544 return 0;
2545 QualType Ty = PID->getPropertyIvarDecl()->getType();
2546 if (!Ty->isRecordType())
2547 return 0;
2548 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +00002549 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic))
2550 || /* temporary */ true)
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002551 return 0;
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +00002552 if (forSetter) {
2553 if (hasTrivialSetExpr(PID))
2554 return 0;
2555 }
2556 else
2557 if (hasTrivialGetExpr(PID))
2558 return 0;
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002559 llvm::Constant * HelperFn = CGM.getAtomicHelperFnMap(Ty);
2560 if (HelperFn)
2561 return HelperFn;
2562
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002563 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
2564
2565 ASTContext &C = getContext();
2566 IdentifierInfo *II
2567 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
2568 FunctionDecl *FD = FunctionDecl::Create(C,
2569 C.getTranslationUnitDecl(),
2570 SourceLocation(),
2571 SourceLocation(), II, C.VoidTy, 0,
2572 SC_Static,
2573 SC_None,
2574 false,
2575 true);
2576
2577 QualType DestTy = C.getPointerType(Ty);
2578 QualType SrcTy = Ty;
2579 SrcTy.addConst();
2580 SrcTy = C.getPointerType(SrcTy);
2581
2582 FunctionArgList args;
2583 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2584 args.push_back(&dstDecl);
2585 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2586 args.push_back(&srcDecl);
2587
2588 const CGFunctionInfo &FI =
2589 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
2590
2591 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
2592
2593 llvm::Function *Fn =
2594 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2595 "__copy_helper_atomic_property_", &CGM.getModule());
2596
2597 if (CGM.getModuleDebugInfo())
2598 DebugInfo = CGM.getModuleDebugInfo();
2599
2600
2601 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2602
2603 DeclRefExpr *DstExpr =
2604 new (C) DeclRefExpr(&dstDecl, DestTy,
2605 VK_RValue, SourceLocation());
2606
2607 Expr* DST = new (C) UnaryOperator(DstExpr, UO_Deref, DestTy->getPointeeType(),
2608 VK_LValue, OK_Ordinary, SourceLocation());
2609
2610 DeclRefExpr *SrcExpr =
2611 new (C) DeclRefExpr(&srcDecl, SrcTy,
2612 VK_RValue, SourceLocation());
2613
2614 Expr* SRC = new (C) UnaryOperator(SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2615 VK_LValue, OK_Ordinary, SourceLocation());
2616
2617 Expr *Args[2] = { DST, SRC };
2618 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
2619 CXXOperatorCallExpr *TheCall =
2620 new (C) CXXOperatorCallExpr(C, OO_Equal, CalleeExp->getCallee(),
2621 Args, 2, DestTy->getPointeeType(),
2622 VK_LValue, SourceLocation());
2623
2624 EmitStmt(TheCall);
2625
2626 FinishFunction();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002627 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2628 CGM.setAtomicHelperFnMap(Ty, HelperFn);
2629 return HelperFn;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002630
2631}
2632
2633
Ted Kremenek2979ec72008-04-09 15:51:31 +00002634CGObjCRuntime::~CGObjCRuntime() {}