blob: 9849fb61b6b50b93f01ece66bf2c7935606e8064 [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
Ted Kremenek2979ec72008-04-09 15:51:31 +000014#include "CGObjCRuntime.h"
Anders Carlsson55085182007-08-21 17:43:55 +000015#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
Daniel Dunbar85c59ed2008-08-29 08:11:39 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Daniel Dunbare66f4e32008-09-03 00:27:26 +000019#include "clang/Basic/Diagnostic.h"
Anders Carlsson3d8400d2008-08-30 19:51:14 +000020#include "llvm/ADT/STLExtras.h"
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +000021#include "llvm/Target/TargetData.h"
Chris Lattner41110242008-06-17 18:05:57 +000022
Anders Carlsson55085182007-08-21 17:43:55 +000023using namespace clang;
24using namespace CodeGen;
25
Chris Lattner8fdf3282008-06-24 17:04:18 +000026/// Emits an instance of NSConstantString representing the object.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000027llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E) {
28 std::string String(E->getString()->getStrData(), E->getString()->getByteLength());
29 llvm::Constant *C = CGM.getObjCRuntime().GenerateConstantString(String);
Daniel Dunbared7c6182008-08-20 00:28:19 +000030 // FIXME: This bitcast should just be made an invariant on the Runtime.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000031 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattner8fdf3282008-06-24 17:04:18 +000032}
33
34/// Emit a selector.
35llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
36 // Untyped selector.
37 // Note that this implementation allows for non-constant strings to be passed
38 // as arguments to @selector(). Currently, the only thing preventing this
39 // behaviour is the type checking in the front end.
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000040 return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
Chris Lattner8fdf3282008-06-24 17:04:18 +000041}
42
Daniel Dunbared7c6182008-08-20 00:28:19 +000043llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
44 // FIXME: This should pass the Decl not the name.
45 return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol());
46}
Chris Lattner8fdf3282008-06-24 17:04:18 +000047
48
Daniel Dunbar8f2926b2008-08-23 03:46:30 +000049RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E) {
Chris Lattner8fdf3282008-06-24 17:04:18 +000050 // Only the lookup mechanism and first two arguments of the method
51 // implementation vary between runtimes. We can get the receiver and
52 // arguments in generic code.
53
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000054 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattner8fdf3282008-06-24 17:04:18 +000055 const Expr *ReceiverExpr = E->getReceiver();
56 bool isSuperMessage = false;
Daniel Dunbarf56f1912008-08-25 08:19:24 +000057 bool isClassMessage = false;
Chris Lattner8fdf3282008-06-24 17:04:18 +000058 // Find the receiver
59 llvm::Value *Receiver;
60 if (!ReceiverExpr) {
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +000061 const ObjCInterfaceDecl *OID = E->getClassInfo().first;
62
63 // Very special case, super send in class method. The receiver is
64 // self (the class object) and the send uses super semantics.
65 if (!OID) {
66 assert(!strcmp(E->getClassName()->getName(), "super") &&
67 "Unexpected missing class interface in message send.");
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +000068 isSuperMessage = true;
Daniel Dunbarf56f1912008-08-25 08:19:24 +000069 Receiver = LoadObjCSelf();
70 } else {
71 Receiver = Runtime.GetClass(Builder, OID);
Chris Lattner8fdf3282008-06-24 17:04:18 +000072 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +000073
74 isClassMessage = true;
Chris Lattnerd9f69102008-08-10 01:53:14 +000075 } else if (const PredefinedExpr *PDE =
76 dyn_cast<PredefinedExpr>(E->getReceiver())) {
77 assert(PDE->getIdentType() == PredefinedExpr::ObjCSuper);
Chris Lattner8fdf3282008-06-24 17:04:18 +000078 isSuperMessage = true;
79 Receiver = LoadObjCSelf();
80 } else {
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000081 Receiver = EmitScalarExpr(E->getReceiver());
Chris Lattner8fdf3282008-06-24 17:04:18 +000082 }
83
Daniel Dunbar19cd87e2008-08-30 03:02:31 +000084 CallArgList Args;
85 for (CallExpr::const_arg_iterator i = E->arg_begin(), e = E->arg_end();
86 i != e; ++i)
Daniel Dunbar46f45b92008-09-09 01:06:48 +000087 Args.push_back(std::make_pair(EmitAnyExprToTemp(*i), (*i)->getType()));
Daniel Dunbar19cd87e2008-08-30 03:02:31 +000088
Chris Lattner8fdf3282008-06-24 17:04:18 +000089 if (isSuperMessage) {
Chris Lattner9384c762008-06-26 04:42:20 +000090 // super is only valid in an Objective-C method
91 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +000092 return Runtime.GenerateMessageSendSuper(*this, E->getType(),
93 E->getSelector(),
Daniel Dunbarf56f1912008-08-25 08:19:24 +000094 OMD->getClassInterface(),
95 Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +000096 isClassMessage,
97 Args);
Chris Lattner8fdf3282008-06-24 17:04:18 +000098 }
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +000099 return Runtime.GenerateMessageSend(*this, E->getType(), E->getSelector(),
100 Receiver, isClassMessage, Args);
Anders Carlsson55085182007-08-21 17:43:55 +0000101}
102
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000103/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
104/// the LLVM function and sets the other context used by
105/// CodeGenFunction.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000106void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD) {
Daniel Dunbar7c086512008-09-09 23:14:03 +0000107 FunctionArgList Args;
108 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000109
Daniel Dunbar7c086512008-09-09 23:14:03 +0000110 CGM.SetMethodAttributes(OMD, Fn);
Chris Lattner41110242008-06-17 18:05:57 +0000111
Daniel Dunbar7c086512008-09-09 23:14:03 +0000112 Args.push_back(std::make_pair(OMD->getSelfDecl(),
113 OMD->getSelfDecl()->getType()));
114 Args.push_back(std::make_pair(OMD->getCmdDecl(),
115 OMD->getCmdDecl()->getType()));
Chris Lattner41110242008-06-17 18:05:57 +0000116
Daniel Dunbar7c086512008-09-09 23:14:03 +0000117 for (unsigned i = 0, e = OMD->getNumParams(); i != e; ++i) {
118 ParmVarDecl *IPD = OMD->getParamDecl(i);
119 Args.push_back(std::make_pair(IPD, IPD->getType()));
Chris Lattner41110242008-06-17 18:05:57 +0000120 }
Chris Lattner41110242008-06-17 18:05:57 +0000121
Daniel Dunbar7c086512008-09-09 23:14:03 +0000122 StartFunction(OMD, OMD->getResultType(), Fn, Args);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000123}
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000124
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000125/// Generate an Objective-C method. An Objective-C method is a C function with
126/// its pointer, name, and types registered in the class struture.
127void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
128 StartObjCMethod(OMD);
129 EmitStmt(OMD->getBody());
130
131 const CompoundStmt *S = dyn_cast<CompoundStmt>(OMD->getBody());
132 if (S) {
133 FinishFunction(S->getRBracLoc());
134 } else {
135 FinishFunction();
136 }
137}
138
139// FIXME: I wasn't sure about the synthesis approach. If we end up
140// generating an AST for the whole body we can just fall back to
141// having a GenerateFunction which takes the body Stmt.
142
143/// GenerateObjCGetter - Generate an Objective-C property getter
144/// function. The given Decl must be either an ObjCCategoryImplDecl
145/// or an ObjCImplementationDecl.
146void CodeGenFunction::GenerateObjCGetter(const ObjCPropertyImplDecl *PID) {
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000147 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000148 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
149 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
150 assert(OMD && "Invalid call to generate getter (empty method)");
151 // FIXME: This is rather murky, we create this here since they will
152 // not have been created by Sema for us.
153 OMD->createImplicitParams(getContext());
154 StartObjCMethod(OMD);
155
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000156 // Determine if we should use an objc_getProperty call for
157 // this. Non-atomic and properties with assign semantics are
158 // directly evaluated, and in gc-only mode we don't need it at all.
159 if (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
160 PD->getSetterKind() != ObjCPropertyDecl::Assign &&
161 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)) {
162 llvm::Value *GetPropertyFn =
163 CGM.getObjCRuntime().GetPropertyGetFunction();
164
165 if (!GetPropertyFn) {
166 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
167 FinishFunction();
168 return;
169 }
170
171 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
172 // FIXME: Can't this be simpler? This might even be worse than the
173 // corresponding gcc code.
174 CodeGenTypes &Types = CGM.getTypes();
175 ValueDecl *Cmd = OMD->getCmdDecl();
176 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
177 QualType IdTy = getContext().getObjCIdType();
178 llvm::Value *SelfAsId =
179 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
180 llvm::Value *Offset = EmitIvarOffset(OMD->getClassInterface(), Ivar);
181 llvm::Value *True =
182 llvm::ConstantInt::get(Types.ConvertTypeForMem(getContext().BoolTy), 1);
183 CallArgList Args;
184 Args.push_back(std::make_pair(RValue::get(SelfAsId), IdTy));
185 Args.push_back(std::make_pair(RValue::get(CmdVal), Cmd->getType()));
186 Args.push_back(std::make_pair(RValue::get(Offset), getContext().LongTy));
187 Args.push_back(std::make_pair(RValue::get(True), getContext().BoolTy));
188 RValue RV = EmitCall(GetPropertyFn, PD->getType(), Args);
189 // We need to fix the type here. Ivars with copy & retain are
190 // always objects so we don't need to worry about complex or
191 // aggregates.
192 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
193 Types.ConvertType(PD->getType())));
194 EmitReturnOfRValue(RV, PD->getType());
195 } else {
196 EmitReturnOfRValue(EmitLoadOfLValue(EmitLValueForIvar(LoadObjCSelf(),
197 Ivar, 0),
198 Ivar->getType()),
199 PD->getType());
200 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000201
202 FinishFunction();
203}
204
205/// GenerateObjCSetter - Generate an Objective-C property setter
206/// function. The given Decl must be either an ObjCCategoryImplDecl
207/// or an ObjCImplementationDecl.
208void CodeGenFunction::GenerateObjCSetter(const ObjCPropertyImplDecl *PID) {
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000209 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000210 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
211 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
212 assert(OMD && "Invalid call to generate setter (empty method)");
213 // FIXME: This is rather murky, we create this here since they will
214 // not have been created by Sema for us.
215 OMD->createImplicitParams(getContext());
216 StartObjCMethod(OMD);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000217
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000218 bool IsCopy = PD->getSetterKind() == ObjCPropertyDecl::Copy;
219 bool IsAtomic =
220 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
221
222 // Determine if we should use an objc_setProperty call for
223 // this. Properties with 'copy' semantics always use it, as do
224 // non-atomic properties with 'release' semantics as long as we are
225 // not in gc-only mode.
226 if (IsCopy ||
227 (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
228 PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
229 llvm::Value *SetPropertyFn =
230 CGM.getObjCRuntime().GetPropertySetFunction();
231
232 if (!SetPropertyFn) {
233 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
234 FinishFunction();
235 return;
236 }
237
238 // Emit objc_setProperty((id) self, _cmd, offset, arg,
239 // <is-atomic>, <is-copy>).
240 // FIXME: Can't this be simpler? This might even be worse than the
241 // corresponding gcc code.
242 CodeGenTypes &Types = CGM.getTypes();
243 ValueDecl *Cmd = OMD->getCmdDecl();
244 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
245 QualType IdTy = getContext().getObjCIdType();
246 llvm::Value *SelfAsId =
247 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
248 llvm::Value *Offset = EmitIvarOffset(OMD->getClassInterface(), Ivar);
249 llvm::Value *Arg = LocalDeclMap[OMD->getParamDecl(0)];
250 llvm::Value *ArgAsId =
251 Builder.CreateBitCast(Builder.CreateLoad(Arg, "arg"),
252 Types.ConvertType(IdTy));
253 llvm::Value *True =
254 llvm::ConstantInt::get(Types.ConvertTypeForMem(getContext().BoolTy), 1);
255 llvm::Value *False =
256 llvm::ConstantInt::get(Types.ConvertTypeForMem(getContext().BoolTy), 0);
257 CallArgList Args;
258 Args.push_back(std::make_pair(RValue::get(SelfAsId), IdTy));
259 Args.push_back(std::make_pair(RValue::get(CmdVal), Cmd->getType()));
260 Args.push_back(std::make_pair(RValue::get(Offset), getContext().LongTy));
261 Args.push_back(std::make_pair(RValue::get(ArgAsId), IdTy));
262 Args.push_back(std::make_pair(RValue::get(IsAtomic ? True : False),
263 getContext().BoolTy));
264 Args.push_back(std::make_pair(RValue::get(IsCopy ? True : False),
265 getContext().BoolTy));
266 EmitCall(SetPropertyFn, PD->getType(), Args);
267 } else {
268 SourceLocation Loc = PD->getLocation();
269 ValueDecl *Self = OMD->getSelfDecl();
270 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
271 DeclRefExpr Base(Self, Self->getType(), Loc);
272 ParmVarDecl *ArgDecl = OMD->getParamDecl(0);
273 DeclRefExpr Arg(ArgDecl, ArgDecl->getType(), Loc);
274 ObjCIvarRefExpr IvarRef(Ivar, Ivar->getType(), Loc, &Base,
275 true, true);
276 BinaryOperator Assign(&IvarRef, &Arg, BinaryOperator::Assign,
277 Ivar->getType(), Loc);
278 EmitStmt(&Assign);
279 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000280
281 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +0000282}
283
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000284llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000285 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
286 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner41110242008-06-17 18:05:57 +0000287}
288
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000289RValue CodeGenFunction::EmitObjCPropertyGet(const ObjCPropertyRefExpr *E) {
290 // Determine getter selector.
291 Selector S;
Daniel Dunbare66f4e32008-09-03 00:27:26 +0000292 if (E->getKind() == ObjCPropertyRefExpr::MethodRef) {
293 S = E->getGetterMethod()->getSelector();
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000294 } else {
Daniel Dunbare66f4e32008-09-03 00:27:26 +0000295 S = E->getProperty()->getGetterName();
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000296 }
297
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000298 return CGM.getObjCRuntime().
299 GenerateMessageSend(*this, E->getType(), S,
300 EmitScalarExpr(E->getBase()),
301 false, CallArgList());
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000302}
303
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000304void CodeGenFunction::EmitObjCPropertySet(const ObjCPropertyRefExpr *E,
305 RValue Src) {
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000306 Selector S;
Daniel Dunbare66f4e32008-09-03 00:27:26 +0000307 if (E->getKind() == ObjCPropertyRefExpr::MethodRef) {
308 ObjCMethodDecl *Setter = E->getSetterMethod();
309
310 if (Setter) {
311 S = Setter->getSelector();
312 } else {
313 // FIXME: This should be diagnosed by sema.
314 SourceRange Range = E->getSourceRange();
315 CGM.getDiags().Report(getContext().getFullLoc(E->getLocStart()),
316 diag::err_typecheck_assign_const, 0, 0,
317 &Range, 1);
318 return;
319 }
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000320 } else {
Daniel Dunbare66f4e32008-09-03 00:27:26 +0000321 S = E->getProperty()->getSetterName();
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000322 }
323
324 CallArgList Args;
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000325 Args.push_back(std::make_pair(Src, E->getType()));
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000326 CGM.getObjCRuntime().GenerateMessageSend(*this, getContext().VoidTy, S,
327 EmitScalarExpr(E->getBase()),
328 false, Args);
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000329}
330
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000331void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S)
332{
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000333 llvm::Function *EnumerationMutationFn =
334 CGM.getObjCRuntime().EnumerationMutationFunction();
Anders Carlssonf484c312008-08-31 02:33:12 +0000335 llvm::Value *DeclAddress;
336 QualType ElementTy;
337
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000338 if (!EnumerationMutationFn) {
339 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
340 return;
341 }
342
Anders Carlssonf484c312008-08-31 02:33:12 +0000343 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
344 EmitStmt(SD);
Ted Kremenek39741ce2008-10-06 20:59:48 +0000345 const ScopedDecl* D = SD->getSolitaryDecl();
346 ElementTy = cast<ValueDecl>(D)->getType();
347 DeclAddress = LocalDeclMap[D];
Anders Carlssonf484c312008-08-31 02:33:12 +0000348 } else {
349 ElementTy = cast<Expr>(S.getElement())->getType();
350 DeclAddress = 0;
351 }
352
353 // Fast enumeration state.
354 QualType StateTy = getContext().getObjCFastEnumerationStateType();
355 llvm::AllocaInst *StatePtr = CreateTempAlloca(ConvertType(StateTy),
356 "state.ptr");
357 StatePtr->setAlignment(getContext().getTypeAlign(StateTy) >> 3);
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000358 EmitMemSetToZero(StatePtr, StateTy);
Anders Carlssonf484c312008-08-31 02:33:12 +0000359
360 // Number of elements in the items array.
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000361 static const unsigned NumItems = 16;
Anders Carlssonf484c312008-08-31 02:33:12 +0000362
363 // Get selector
364 llvm::SmallVector<IdentifierInfo*, 3> II;
365 II.push_back(&CGM.getContext().Idents.get("countByEnumeratingWithState"));
366 II.push_back(&CGM.getContext().Idents.get("objects"));
367 II.push_back(&CGM.getContext().Idents.get("count"));
368 Selector FastEnumSel = CGM.getContext().Selectors.getSelector(II.size(),
369 &II[0]);
370
371 QualType ItemsTy =
372 getContext().getConstantArrayType(getContext().getObjCIdType(),
373 llvm::APInt(32, NumItems),
374 ArrayType::Normal, 0);
375 llvm::Value *ItemsPtr = CreateTempAlloca(ConvertType(ItemsTy), "items.ptr");
376
377 llvm::Value *Collection = EmitScalarExpr(S.getCollection());
378
379 CallArgList Args;
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000380 Args.push_back(std::make_pair(RValue::get(StatePtr),
Anders Carlssonf484c312008-08-31 02:33:12 +0000381 getContext().getPointerType(StateTy)));
382
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000383 Args.push_back(std::make_pair(RValue::get(ItemsPtr),
Anders Carlssonf484c312008-08-31 02:33:12 +0000384 getContext().getPointerType(ItemsTy)));
385
386 const llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
387 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000388 Args.push_back(std::make_pair(RValue::get(Count),
389 getContext().UnsignedLongTy));
Anders Carlssonf484c312008-08-31 02:33:12 +0000390
391 RValue CountRV =
392 CGM.getObjCRuntime().GenerateMessageSend(*this,
393 getContext().UnsignedLongTy,
394 FastEnumSel,
395 Collection, false, Args);
396
397 llvm::Value *LimitPtr = CreateTempAlloca(UnsignedLongLTy, "limit.ptr");
398 Builder.CreateStore(CountRV.getScalarVal(), LimitPtr);
399
400 llvm::BasicBlock *NoElements = llvm::BasicBlock::Create("noelements");
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000401 llvm::BasicBlock *SetStartMutations =
402 llvm::BasicBlock::Create("setstartmutations");
Anders Carlssonf484c312008-08-31 02:33:12 +0000403
404 llvm::Value *Limit = Builder.CreateLoad(LimitPtr);
405 llvm::Value *Zero = llvm::Constant::getNullValue(UnsignedLongLTy);
406
407 llvm::Value *IsZero = Builder.CreateICmpEQ(Limit, Zero, "iszero");
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000408 Builder.CreateCondBr(IsZero, NoElements, SetStartMutations);
Anders Carlssonf484c312008-08-31 02:33:12 +0000409
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000410 EmitBlock(SetStartMutations);
411
412 llvm::Value *StartMutationsPtr =
413 CreateTempAlloca(UnsignedLongLTy);
414
415 llvm::Value *StateMutationsPtrPtr =
416 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
417 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
418 "mutationsptr");
419
420 llvm::Value *StateMutations = Builder.CreateLoad(StateMutationsPtr,
421 "mutations");
422
423 Builder.CreateStore(StateMutations, StartMutationsPtr);
424
425 llvm::BasicBlock *LoopStart = llvm::BasicBlock::Create("loopstart");
Anders Carlssonf484c312008-08-31 02:33:12 +0000426 EmitBlock(LoopStart);
427
Anders Carlssonf484c312008-08-31 02:33:12 +0000428 llvm::Value *CounterPtr = CreateTempAlloca(UnsignedLongLTy, "counter.ptr");
429 Builder.CreateStore(Zero, CounterPtr);
430
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000431 llvm::BasicBlock *LoopBody = llvm::BasicBlock::Create("loopbody");
Anders Carlssonf484c312008-08-31 02:33:12 +0000432 EmitBlock(LoopBody);
433
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000434 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
435 StateMutations = Builder.CreateLoad(StateMutationsPtr, "statemutations");
436
437 llvm::Value *StartMutations = Builder.CreateLoad(StartMutationsPtr,
438 "mutations");
439 llvm::Value *MutationsEqual = Builder.CreateICmpEQ(StateMutations,
440 StartMutations,
441 "tobool");
442
443
444 llvm::BasicBlock *WasMutated = llvm::BasicBlock::Create("wasmutated");
445 llvm::BasicBlock *WasNotMutated = llvm::BasicBlock::Create("wasnotmutated");
446
447 Builder.CreateCondBr(MutationsEqual, WasNotMutated, WasMutated);
448
449 EmitBlock(WasMutated);
450 llvm::Value *V =
451 Builder.CreateBitCast(Collection,
452 ConvertType(getContext().getObjCIdType()),
453 "tmp");
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000454 Builder.CreateCall(EnumerationMutationFn, V);
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000455
456 EmitBlock(WasNotMutated);
457
Anders Carlssonf484c312008-08-31 02:33:12 +0000458 llvm::Value *StateItemsPtr =
459 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
460
461 llvm::Value *Counter = Builder.CreateLoad(CounterPtr, "counter");
462
463 llvm::Value *EnumStateItems = Builder.CreateLoad(StateItemsPtr,
464 "stateitems");
465
466 llvm::Value *CurrentItemPtr =
467 Builder.CreateGEP(EnumStateItems, Counter, "currentitem.ptr");
468
469 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr, "currentitem");
470
471 // Cast the item to the right type.
472 CurrentItem = Builder.CreateBitCast(CurrentItem,
473 ConvertType(ElementTy), "tmp");
474
475 if (!DeclAddress) {
476 LValue LV = EmitLValue(cast<Expr>(S.getElement()));
477
478 // Set the value to null.
479 Builder.CreateStore(CurrentItem, LV.getAddress());
480 } else
481 Builder.CreateStore(CurrentItem, DeclAddress);
482
483 // Increment the counter.
484 Counter = Builder.CreateAdd(Counter,
485 llvm::ConstantInt::get(UnsignedLongLTy, 1));
486 Builder.CreateStore(Counter, CounterPtr);
487
488 llvm::BasicBlock *LoopEnd = llvm::BasicBlock::Create("loopend");
489 llvm::BasicBlock *AfterBody = llvm::BasicBlock::Create("afterbody");
490
491 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
492
493 EmitStmt(S.getBody());
494
495 BreakContinueStack.pop_back();
496
497 EmitBlock(AfterBody);
498
499 llvm::BasicBlock *FetchMore = llvm::BasicBlock::Create("fetchmore");
500
501 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, Limit, "isless");
Daniel Dunbarfe2b2c02008-09-04 21:54:37 +0000502 Builder.CreateCondBr(IsLess, LoopBody, FetchMore);
Anders Carlssonf484c312008-08-31 02:33:12 +0000503
504 // Fetch more elements.
505 EmitBlock(FetchMore);
506
507 CountRV =
508 CGM.getObjCRuntime().GenerateMessageSend(*this,
509 getContext().UnsignedLongTy,
510 FastEnumSel,
511 Collection, false, Args);
512 Builder.CreateStore(CountRV.getScalarVal(), LimitPtr);
513 Limit = Builder.CreateLoad(LimitPtr);
514
515 IsZero = Builder.CreateICmpEQ(Limit, Zero, "iszero");
516 Builder.CreateCondBr(IsZero, NoElements, LoopStart);
517
518 // No more elements.
519 EmitBlock(NoElements);
520
521 if (!DeclAddress) {
522 // If the element was not a declaration, set it to be null.
523
524 LValue LV = EmitLValue(cast<Expr>(S.getElement()));
525
526 // Set the value to null.
527 Builder.CreateStore(llvm::Constant::getNullValue(ConvertType(ElementTy)),
528 LV.getAddress());
529 }
530
531 EmitBlock(LoopEnd);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000532}
533
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000534void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S)
535{
536 CGM.getObjCRuntime().EmitTryStmt(*this, S);
537}
538
539void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S)
540{
541 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
542}
543
Ted Kremenek2979ec72008-04-09 15:51:31 +0000544CGObjCRuntime::~CGObjCRuntime() {}