1 //===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to emit Objective-C code as LLVM code.
12 //===----------------------------------------------------------------------===//
14 #include "CGDebugInfo.h"
15 #include "CGObjCRuntime.h"
16 #include "CodeGenFunction.h"
17 #include "CodeGenModule.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/StmtObjC.h"
21 #include "clang/Basic/Diagnostic.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/Target/TargetData.h"
24 using namespace clang;
25 using namespace CodeGen;
27 /// Emits an instance of NSConstantString representing the object.
28 llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
31 CGM.getObjCRuntime().GenerateConstantString(E->getString());
32 // FIXME: This bitcast should just be made an invariant on the Runtime.
33 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
37 llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
39 // Note that this implementation allows for non-constant strings to be passed
40 // as arguments to @selector(). Currently, the only thing preventing this
41 // behaviour is the type checking in the front end.
42 return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
45 llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
46 // FIXME: This should pass the Decl not the name.
47 return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol());
51 RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
52 ReturnValueSlot Return) {
53 // Only the lookup mechanism and first two arguments of the method
54 // implementation vary between runtimes. We can get the receiver and
55 // arguments in generic code.
57 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
58 bool isSuperMessage = false;
59 bool isClassMessage = false;
60 ObjCInterfaceDecl *OID = 0;
62 llvm::Value *Receiver = 0;
63 switch (E->getReceiverKind()) {
64 case ObjCMessageExpr::Instance:
65 Receiver = EmitScalarExpr(E->getInstanceReceiver());
68 case ObjCMessageExpr::Class: {
69 const ObjCObjectType *ObjTy
70 = E->getClassReceiver()->getAs<ObjCObjectType>();
71 assert(ObjTy && "Invalid Objective-C class message send");
72 OID = ObjTy->getInterface();
73 assert(OID && "Invalid Objective-C class message send");
74 Receiver = Runtime.GetClass(Builder, OID);
75 isClassMessage = true;
79 case ObjCMessageExpr::SuperInstance:
80 Receiver = LoadObjCSelf();
81 isSuperMessage = true;
84 case ObjCMessageExpr::SuperClass:
85 Receiver = LoadObjCSelf();
86 isSuperMessage = true;
87 isClassMessage = true;
92 EmitCallArgs(Args, E->getMethodDecl(), E->arg_begin(), E->arg_end());
95 E->getMethodDecl() ? E->getMethodDecl()->getResultType() : E->getType();
98 // super is only valid in an Objective-C method
99 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
100 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
101 return Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
103 OMD->getClassInterface(),
111 return Runtime.GenerateMessageSend(*this, Return, ResultType,
117 /// StartObjCMethod - Begin emission of an ObjCMethod. This generates
118 /// the LLVM function and sets the other context used by
120 void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
121 const ObjCContainerDecl *CD) {
122 FunctionArgList Args;
123 // Check if we should generate debug info for this method.
124 if (CGM.getDebugInfo() && !OMD->hasAttr<NoDebugAttr>())
125 DebugInfo = CGM.getDebugInfo();
127 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
129 const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(OMD);
130 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
132 Args.push_back(std::make_pair(OMD->getSelfDecl(),
133 OMD->getSelfDecl()->getType()));
134 Args.push_back(std::make_pair(OMD->getCmdDecl(),
135 OMD->getCmdDecl()->getType()));
137 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
138 E = OMD->param_end(); PI != E; ++PI)
139 Args.push_back(std::make_pair(*PI, (*PI)->getType()));
143 StartFunction(OMD, OMD->getResultType(), Fn, Args, OMD->getLocStart());
146 void CodeGenFunction::GenerateObjCGetterBody(ObjCIvarDecl *Ivar,
147 bool IsAtomic, bool IsStrong) {
148 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
150 llvm::Value *GetCopyStructFn =
151 CGM.getObjCRuntime().GetGetStructFunction();
152 CodeGenTypes &Types = CGM.getTypes();
153 // objc_copyStruct (ReturnValue, &structIvar,
154 // sizeof (Type of Ivar), isAtomic, false);
156 RValue RV = RValue::get(Builder.CreateBitCast(ReturnValue,
157 Types.ConvertType(getContext().VoidPtrTy)));
158 Args.push_back(std::make_pair(RV, getContext().VoidPtrTy));
159 RV = RValue::get(Builder.CreateBitCast(LV.getAddress(),
160 Types.ConvertType(getContext().VoidPtrTy)));
161 Args.push_back(std::make_pair(RV, getContext().VoidPtrTy));
162 // sizeof (Type of Ivar)
163 CharUnits Size = getContext().getTypeSizeInChars(Ivar->getType());
164 llvm::Value *SizeVal =
165 llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy),
167 Args.push_back(std::make_pair(RValue::get(SizeVal),
168 getContext().LongTy));
169 llvm::Value *isAtomic =
170 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy),
172 Args.push_back(std::make_pair(RValue::get(isAtomic),
173 getContext().BoolTy));
174 llvm::Value *hasStrong =
175 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy),
177 Args.push_back(std::make_pair(RValue::get(hasStrong),
178 getContext().BoolTy));
179 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
180 FunctionType::ExtInfo()),
181 GetCopyStructFn, ReturnValueSlot(), Args);
184 /// Generate an Objective-C method. An Objective-C method is a C function with
185 /// its pointer, name, and types registered in the class struture.
186 void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
187 StartObjCMethod(OMD, OMD->getClassInterface());
188 EmitStmt(OMD->getBody());
189 FinishFunction(OMD->getBodyRBrace());
192 // FIXME: I wasn't sure about the synthesis approach. If we end up generating an
193 // AST for the whole body we can just fall back to having a GenerateFunction
194 // which takes the body Stmt.
196 /// GenerateObjCGetter - Generate an Objective-C property getter
197 /// function. The given Decl must be an ObjCImplementationDecl. @synthesize
198 /// is illegal within a category.
199 void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
200 const ObjCPropertyImplDecl *PID) {
201 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
202 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
204 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
205 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
206 assert(OMD && "Invalid call to generate getter (empty method)");
207 StartObjCMethod(OMD, IMP->getClassInterface());
209 // Determine if we should use an objc_getProperty call for
210 // this. Non-atomic properties are directly evaluated.
211 // atomic 'copy' and 'retain' properties are also directly
212 // evaluated in gc-only mode.
213 if (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
215 (PD->getSetterKind() == ObjCPropertyDecl::Copy ||
216 PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
217 llvm::Value *GetPropertyFn =
218 CGM.getObjCRuntime().GetPropertyGetFunction();
220 if (!GetPropertyFn) {
221 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
226 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
227 // FIXME: Can't this be simpler? This might even be worse than the
228 // corresponding gcc code.
229 CodeGenTypes &Types = CGM.getTypes();
230 ValueDecl *Cmd = OMD->getCmdDecl();
231 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
232 QualType IdTy = getContext().getObjCIdType();
233 llvm::Value *SelfAsId =
234 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
235 llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
237 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
239 Args.push_back(std::make_pair(RValue::get(SelfAsId), IdTy));
240 Args.push_back(std::make_pair(RValue::get(CmdVal), Cmd->getType()));
241 Args.push_back(std::make_pair(RValue::get(Offset), getContext().LongTy));
242 Args.push_back(std::make_pair(RValue::get(True), getContext().BoolTy));
243 // FIXME: We shouldn't need to get the function info here, the
244 // runtime already should have computed it to build the function.
245 RValue RV = EmitCall(Types.getFunctionInfo(PD->getType(), Args,
246 FunctionType::ExtInfo()),
247 GetPropertyFn, ReturnValueSlot(), Args);
248 // We need to fix the type here. Ivars with copy & retain are
249 // always objects so we don't need to worry about complex or
251 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
252 Types.ConvertType(PD->getType())));
253 EmitReturnOfRValue(RV, PD->getType());
255 const llvm::Triple &Triple = getContext().Target.getTriple();
256 QualType IVART = Ivar->getType();
258 IVART->isScalarType() &&
259 (Triple.getArch() == llvm::Triple::arm ||
260 Triple.getArch() == llvm::Triple::thumb) &&
261 (getContext().getTypeSizeInChars(IVART)
262 > CharUnits::fromQuantity(4)) &&
263 CGM.getObjCRuntime().GetGetStructFunction()) {
264 GenerateObjCGetterBody(Ivar, true, false);
266 else if (IVART->isAnyComplexType()) {
267 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
269 ComplexPairTy Pair = LoadComplexFromAddr(LV.getAddress(),
270 LV.isVolatileQualified());
271 StoreComplexToAddr(Pair, ReturnValue, LV.isVolatileQualified());
273 else if (hasAggregateLLVMType(IVART)) {
274 bool IsStrong = false;
275 if ((IsAtomic || (IsStrong = IvarTypeWithAggrGCObjects(IVART)))
276 && CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect
277 && CGM.getObjCRuntime().GetGetStructFunction()) {
278 GenerateObjCGetterBody(Ivar, IsAtomic, IsStrong);
281 if (PID->getGetterCXXConstructor()) {
283 new (getContext()) ReturnStmt(SourceLocation(),
284 PID->getGetterCXXConstructor(),
286 EmitReturnStmt(*Stmt);
289 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
291 EmitAggregateCopy(ReturnValue, LV.getAddress(), IVART);
296 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
298 CodeGenTypes &Types = CGM.getTypes();
299 RValue RV = EmitLoadOfLValue(LV, IVART);
300 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
301 Types.ConvertType(PD->getType())));
302 EmitReturnOfRValue(RV, PD->getType());
309 void CodeGenFunction::GenerateObjCAtomicSetterBody(ObjCMethodDecl *OMD,
310 ObjCIvarDecl *Ivar) {
311 // objc_copyStruct (&structIvar, &Arg,
312 // sizeof (struct something), true, false);
313 llvm::Value *GetCopyStructFn =
314 CGM.getObjCRuntime().GetSetStructFunction();
315 CodeGenTypes &Types = CGM.getTypes();
317 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), Ivar, 0);
319 RValue::get(Builder.CreateBitCast(LV.getAddress(),
320 Types.ConvertType(getContext().VoidPtrTy)));
321 Args.push_back(std::make_pair(RV, getContext().VoidPtrTy));
322 llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()];
323 llvm::Value *ArgAsPtrTy =
324 Builder.CreateBitCast(Arg,
325 Types.ConvertType(getContext().VoidPtrTy));
326 RV = RValue::get(ArgAsPtrTy);
327 Args.push_back(std::make_pair(RV, getContext().VoidPtrTy));
328 // sizeof (Type of Ivar)
329 CharUnits Size = getContext().getTypeSizeInChars(Ivar->getType());
330 llvm::Value *SizeVal =
331 llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy),
333 Args.push_back(std::make_pair(RValue::get(SizeVal),
334 getContext().LongTy));
336 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
337 Args.push_back(std::make_pair(RValue::get(True), getContext().BoolTy));
339 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0);
340 Args.push_back(std::make_pair(RValue::get(False), getContext().BoolTy));
341 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
342 FunctionType::ExtInfo()),
343 GetCopyStructFn, ReturnValueSlot(), Args);
346 /// GenerateObjCSetter - Generate an Objective-C property setter
347 /// function. The given Decl must be an ObjCImplementationDecl. @synthesize
348 /// is illegal within a category.
349 void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
350 const ObjCPropertyImplDecl *PID) {
351 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
352 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
353 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
354 assert(OMD && "Invalid call to generate setter (empty method)");
355 StartObjCMethod(OMD, IMP->getClassInterface());
357 bool IsCopy = PD->getSetterKind() == ObjCPropertyDecl::Copy;
359 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
361 // Determine if we should use an objc_setProperty call for
362 // this. Properties with 'copy' semantics always use it, as do
363 // non-atomic properties with 'release' semantics as long as we are
364 // not in gc-only mode.
366 (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
367 PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
368 llvm::Value *SetPropertyFn =
369 CGM.getObjCRuntime().GetPropertySetFunction();
371 if (!SetPropertyFn) {
372 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
377 // Emit objc_setProperty((id) self, _cmd, offset, arg,
378 // <is-atomic>, <is-copy>).
379 // FIXME: Can't this be simpler? This might even be worse than the
380 // corresponding gcc code.
381 CodeGenTypes &Types = CGM.getTypes();
382 ValueDecl *Cmd = OMD->getCmdDecl();
383 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
384 QualType IdTy = getContext().getObjCIdType();
385 llvm::Value *SelfAsId =
386 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
387 llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
388 llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()];
389 llvm::Value *ArgAsId =
390 Builder.CreateBitCast(Builder.CreateLoad(Arg, "arg"),
391 Types.ConvertType(IdTy));
393 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
395 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0);
397 Args.push_back(std::make_pair(RValue::get(SelfAsId), IdTy));
398 Args.push_back(std::make_pair(RValue::get(CmdVal), Cmd->getType()));
399 Args.push_back(std::make_pair(RValue::get(Offset), getContext().LongTy));
400 Args.push_back(std::make_pair(RValue::get(ArgAsId), IdTy));
401 Args.push_back(std::make_pair(RValue::get(IsAtomic ? True : False),
402 getContext().BoolTy));
403 Args.push_back(std::make_pair(RValue::get(IsCopy ? True : False),
404 getContext().BoolTy));
405 // FIXME: We shouldn't need to get the function info here, the runtime
406 // already should have computed it to build the function.
407 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
408 FunctionType::ExtInfo()),
410 ReturnValueSlot(), Args);
411 } else if (IsAtomic && hasAggregateLLVMType(Ivar->getType()) &&
412 !Ivar->getType()->isAnyComplexType() &&
413 IndirectObjCSetterArg(*CurFnInfo)
414 && CGM.getObjCRuntime().GetSetStructFunction()) {
415 // objc_copyStruct (&structIvar, &Arg,
416 // sizeof (struct something), true, false);
417 GenerateObjCAtomicSetterBody(OMD, Ivar);
418 } else if (PID->getSetterCXXAssignment()) {
419 EmitIgnoredExpr(PID->getSetterCXXAssignment());
421 const llvm::Triple &Triple = getContext().Target.getTriple();
422 QualType IVART = Ivar->getType();
424 IVART->isScalarType() &&
425 (Triple.getArch() == llvm::Triple::arm ||
426 Triple.getArch() == llvm::Triple::thumb) &&
427 (getContext().getTypeSizeInChars(IVART)
428 > CharUnits::fromQuantity(4)) &&
429 CGM.getObjCRuntime().GetGetStructFunction()) {
430 GenerateObjCAtomicSetterBody(OMD, Ivar);
433 // FIXME: Find a clean way to avoid AST node creation.
434 SourceLocation Loc = PD->getLocation();
435 ValueDecl *Self = OMD->getSelfDecl();
436 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
437 DeclRefExpr Base(Self, Self->getType(), VK_RValue, Loc);
438 ParmVarDecl *ArgDecl = *OMD->param_begin();
439 DeclRefExpr Arg(ArgDecl, ArgDecl->getType(), VK_LValue, Loc);
440 ObjCIvarRefExpr IvarRef(Ivar, Ivar->getType(), Loc, &Base, true, true);
442 // The property type can differ from the ivar type in some situations with
443 // Objective-C pointer types, we can always bit cast the RHS in these cases.
444 if (getContext().getCanonicalType(Ivar->getType()) !=
445 getContext().getCanonicalType(ArgDecl->getType())) {
446 ImplicitCastExpr ArgCasted(ImplicitCastExpr::OnStack,
447 Ivar->getType(), CK_BitCast, &Arg,
449 BinaryOperator Assign(&IvarRef, &ArgCasted, BO_Assign,
450 Ivar->getType(), VK_RValue, OK_Ordinary, Loc);
453 BinaryOperator Assign(&IvarRef, &Arg, BO_Assign,
454 Ivar->getType(), VK_RValue, OK_Ordinary, Loc);
463 void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
466 llvm::SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
467 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
468 StartObjCMethod(MD, IMP->getClassInterface());
469 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
470 E = IMP->init_end(); B != E; ++B) {
471 CXXCtorInitializer *Member = (*B);
472 IvarInitializers.push_back(Member);
475 for (unsigned I = 0, E = IvarInitializers.size(); I != E; ++I) {
476 CXXCtorInitializer *IvarInit = IvarInitializers[I];
477 FieldDecl *Field = IvarInit->getAnyMember();
478 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
479 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
480 LoadObjCSelf(), Ivar, 0);
481 EmitAggExpr(IvarInit->getInit(), AggValueSlot::forLValue(LV, true));
483 // constructor returns 'self'.
484 CodeGenTypes &Types = CGM.getTypes();
485 QualType IdTy(CGM.getContext().getObjCIdType());
486 llvm::Value *SelfAsId =
487 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
488 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
491 for (size_t i = IvarInitializers.size(); i > 0; --i) {
492 FieldDecl *Field = IvarInitializers[i - 1]->getAnyMember();
493 QualType FieldType = Field->getType();
494 const ConstantArrayType *Array =
495 getContext().getAsConstantArrayType(FieldType);
497 FieldType = getContext().getBaseElementType(FieldType);
499 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
500 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
501 LoadObjCSelf(), Ivar, 0);
502 const RecordType *RT = FieldType->getAs<RecordType>();
503 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
504 CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor();
505 if (!Dtor->isTrivial()) {
507 const llvm::Type *BasePtr = ConvertType(FieldType);
508 BasePtr = llvm::PointerType::getUnqual(BasePtr);
509 llvm::Value *BaseAddrPtr =
510 Builder.CreateBitCast(LV.getAddress(), BasePtr);
511 EmitCXXAggrDestructorCall(Dtor,
514 EmitCXXDestructorCall(Dtor,
515 Dtor_Complete, /*ForVirtualBase=*/false,
524 bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
525 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
527 const ABIArgInfo &AI = it->info;
528 // FIXME. Is this sufficient check?
529 return (AI.getKind() == ABIArgInfo::Indirect);
532 bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
533 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
535 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
536 return FDTTy->getDecl()->hasObjectMember();
540 llvm::Value *CodeGenFunction::LoadObjCSelf() {
541 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
542 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
545 QualType CodeGenFunction::TypeOfSelfObject() {
546 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
547 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
548 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
549 getContext().getCanonicalType(selfDecl->getType()));
550 return PTy->getPointeeType();
554 CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
555 // This is a special l-value that just issues sends when we load or
558 // For certain base kinds, we need to emit the base immediately.
560 if (E->isSuperReceiver())
561 Base = LoadObjCSelf();
562 else if (E->isClassReceiver())
563 Base = CGM.getObjCRuntime().GetClass(Builder, E->getClassReceiver());
565 Base = EmitScalarExpr(E->getBase());
566 return LValue::MakePropertyRef(E, Base);
569 static RValue GenerateMessageSendSuper(CodeGenFunction &CGF,
570 ReturnValueSlot Return,
573 llvm::Value *Receiver,
574 const CallArgList &CallArgs) {
575 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CGF.CurFuncDecl);
576 bool isClassMessage = OMD->isClassMethod();
577 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
578 return CGF.CGM.getObjCRuntime()
579 .GenerateMessageSendSuper(CGF, Return, ResultType,
580 S, OMD->getClassInterface(),
581 isCategoryImpl, Receiver,
582 isClassMessage, CallArgs);
585 RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
586 ReturnValueSlot Return) {
587 const ObjCPropertyRefExpr *E = LV.getPropertyRefExpr();
590 if (E->isExplicitProperty()) {
591 const ObjCPropertyDecl *Property = E->getExplicitProperty();
592 S = Property->getGetterName();
593 ResultType = E->getType();
595 const ObjCMethodDecl *Getter = E->getImplicitPropertyGetter();
596 S = Getter->getSelector();
597 ResultType = Getter->getResultType(); // with reference!
600 llvm::Value *Receiver = LV.getPropertyRefBaseAddr();
602 // Accesses to 'super' follow a different code path.
603 if (E->isSuperReceiver())
604 return GenerateMessageSendSuper(*this, Return, ResultType,
605 S, Receiver, CallArgList());
607 const ObjCInterfaceDecl *ReceiverClass
608 = (E->isClassReceiver() ? E->getClassReceiver() : 0);
609 return CGM.getObjCRuntime().
610 GenerateMessageSend(*this, Return, ResultType, S,
611 Receiver, CallArgList(), ReceiverClass);
614 void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
616 const ObjCPropertyRefExpr *E = Dst.getPropertyRefExpr();
617 Selector S = E->getSetterSelector();
619 if (E->isImplicitProperty()) {
620 const ObjCMethodDecl *Setter = E->getImplicitPropertySetter();
621 ObjCMethodDecl::param_iterator P = Setter->param_begin();
622 ArgType = (*P)->getType();
624 ArgType = E->getType();
626 // FIXME. Other than scalars, AST is not adequate for setter and
627 // getter type mismatches which require conversion.
628 if (Src.isScalar()) {
629 llvm::Value *SrcVal = Src.getScalarVal();
630 QualType DstType = getContext().getCanonicalType(ArgType);
631 const llvm::Type *DstTy = ConvertType(DstType);
632 if (SrcVal->getType() != DstTy)
634 RValue::get(EmitScalarConversion(SrcVal, E->getType(), DstType));
638 Args.push_back(std::make_pair(Src, ArgType));
640 llvm::Value *Receiver = Dst.getPropertyRefBaseAddr();
641 QualType ResultType = getContext().VoidTy;
643 if (E->isSuperReceiver()) {
644 GenerateMessageSendSuper(*this, ReturnValueSlot(),
645 ResultType, S, Receiver, Args);
649 const ObjCInterfaceDecl *ReceiverClass
650 = (E->isClassReceiver() ? E->getClassReceiver() : 0);
652 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
653 ResultType, S, Receiver, Args,
657 void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
658 llvm::Constant *EnumerationMutationFn =
659 CGM.getObjCRuntime().EnumerationMutationFunction();
661 if (!EnumerationMutationFn) {
662 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
666 // The local variable comes into scope immediately.
667 AutoVarEmission variable = AutoVarEmission::invalid();
668 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
669 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
671 CGDebugInfo *DI = getDebugInfo();
673 DI->setLocation(S.getSourceRange().getBegin());
674 DI->EmitRegionStart(Builder);
677 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
678 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
680 // Fast enumeration state.
681 QualType StateTy = getContext().getObjCFastEnumerationStateType();
682 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
683 EmitNullInitialization(StatePtr, StateTy);
685 // Number of elements in the items array.
686 static const unsigned NumItems = 16;
688 // Fetch the countByEnumeratingWithState:objects:count: selector.
689 IdentifierInfo *II[] = {
690 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
691 &CGM.getContext().Idents.get("objects"),
692 &CGM.getContext().Idents.get("count")
694 Selector FastEnumSel =
695 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
698 getContext().getConstantArrayType(getContext().getObjCIdType(),
699 llvm::APInt(32, NumItems),
700 ArrayType::Normal, 0);
701 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
703 // Emit the collection pointer.
704 llvm::Value *Collection = EmitScalarExpr(S.getCollection());
706 // Send it our message:
709 // The first argument is a temporary of the enumeration-state type.
710 Args.push_back(std::make_pair(RValue::get(StatePtr),
711 getContext().getPointerType(StateTy)));
713 // The second argument is a temporary array with space for NumItems
714 // pointers. We'll actually be loading elements from the array
715 // pointer written into the control state; this buffer is so that
716 // collections that *aren't* backed by arrays can still queue up
717 // batches of elements.
718 Args.push_back(std::make_pair(RValue::get(ItemsPtr),
719 getContext().getPointerType(ItemsTy)));
721 // The third argument is the capacity of that temporary array.
722 const llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
723 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
724 Args.push_back(std::make_pair(RValue::get(Count),
725 getContext().UnsignedLongTy));
727 // Start the enumeration.
729 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
730 getContext().UnsignedLongTy,
734 // The initial number of objects that were returned in the buffer.
735 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
737 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
738 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
740 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
742 // If the limit pointer was zero to begin with, the collection is
743 // empty; skip all this.
744 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
745 EmptyBB, LoopInitBB);
747 // Otherwise, initialize the loop.
748 EmitBlock(LoopInitBB);
750 // Save the initial mutations value. This is the value at an
751 // address that was written into the state object by
752 // countByEnumeratingWithState:objects:count:.
753 llvm::Value *StateMutationsPtrPtr =
754 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
755 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
758 llvm::Value *initialMutations =
759 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
761 // Start looping. This is the point we return to whenever we have a
762 // fresh, non-empty batch of objects.
763 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
764 EmitBlock(LoopBodyBB);
766 // The current index into the buffer.
767 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, "forcoll.index");
768 index->addIncoming(zero, LoopInitBB);
770 // The current buffer size.
771 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, "forcoll.count");
772 count->addIncoming(initialBufferLimit, LoopInitBB);
774 // Check whether the mutations value has changed from where it was
775 // at start. StateMutationsPtr should actually be invariant between
777 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
778 llvm::Value *currentMutations
779 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
781 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
782 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcool.notmutated");
784 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
785 WasNotMutatedBB, WasMutatedBB);
787 // If so, call the enumeration-mutation function.
788 EmitBlock(WasMutatedBB);
790 Builder.CreateBitCast(Collection,
791 ConvertType(getContext().getObjCIdType()),
794 Args2.push_back(std::make_pair(RValue::get(V),
795 getContext().getObjCIdType()));
796 // FIXME: We shouldn't need to get the function info here, the runtime already
797 // should have computed it to build the function.
798 EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2,
799 FunctionType::ExtInfo()),
800 EnumerationMutationFn, ReturnValueSlot(), Args2);
802 // Otherwise, or if the mutation function returns, just continue.
803 EmitBlock(WasNotMutatedBB);
805 // Initialize the element variable.
806 RunCleanupsScope elementVariableScope(*this);
807 bool elementIsVariable;
808 LValue elementLValue;
809 QualType elementType;
810 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
811 // Initialize the variable, in case it's a __block variable or something.
812 EmitAutoVarInit(variable);
814 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
815 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), D->getType(),
816 VK_LValue, SourceLocation());
817 elementLValue = EmitLValue(&tempDRE);
818 elementType = D->getType();
819 elementIsVariable = true;
821 elementLValue = LValue(); // suppress warning
822 elementType = cast<Expr>(S.getElement())->getType();
823 elementIsVariable = false;
825 const llvm::Type *convertedElementType = ConvertType(elementType);
827 // Fetch the buffer out of the enumeration state.
828 // TODO: this pointer should actually be invariant between
829 // refreshes, which would help us do certain loop optimizations.
830 llvm::Value *StateItemsPtr =
831 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
832 llvm::Value *EnumStateItems =
833 Builder.CreateLoad(StateItemsPtr, "stateitems");
835 // Fetch the value at the current index from the buffer.
836 llvm::Value *CurrentItemPtr =
837 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
838 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
840 // Cast that value to the right type.
841 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
844 // Make sure we have an l-value. Yes, this gets evaluated every
845 // time through the loop.
846 if (!elementIsVariable)
847 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
849 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue, elementType);
851 // If we do have an element variable, this assignment is the end of
852 // its initialization.
853 if (elementIsVariable)
854 EmitAutoVarCleanups(variable);
856 // Perform the loop body, setting up break and continue labels.
857 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
859 RunCleanupsScope Scope(*this);
860 EmitStmt(S.getBody());
862 BreakContinueStack.pop_back();
864 // Destroy the element variable now.
865 elementVariableScope.ForceCleanup();
867 // Check whether there are more elements.
868 EmitBlock(AfterBody.getBlock());
870 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
872 // First we check in the local buffer.
873 llvm::Value *indexPlusOne
874 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
876 // If we haven't overrun the buffer yet, we can continue.
877 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
878 LoopBodyBB, FetchMoreBB);
880 index->addIncoming(indexPlusOne, AfterBody.getBlock());
881 count->addIncoming(count, AfterBody.getBlock());
883 // Otherwise, we have to fetch more elements.
884 EmitBlock(FetchMoreBB);
887 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
888 getContext().UnsignedLongTy,
892 // If we got a zero count, we're done.
893 llvm::Value *refetchCount = CountRV.getScalarVal();
895 // (note that the message send might split FetchMoreBB)
896 index->addIncoming(zero, Builder.GetInsertBlock());
897 count->addIncoming(refetchCount, Builder.GetInsertBlock());
899 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
900 EmptyBB, LoopBodyBB);
905 if (!elementIsVariable) {
906 // If the element was not a declaration, set it to be null.
908 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
909 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
910 EmitStoreThroughLValue(RValue::get(null), elementLValue, elementType);
914 DI->setLocation(S.getSourceRange().getEnd());
915 DI->EmitRegionEnd(Builder);
918 EmitBlock(LoopEnd.getBlock());
921 void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
922 CGM.getObjCRuntime().EmitTryStmt(*this, S);
925 void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
926 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
929 void CodeGenFunction::EmitObjCAtSynchronizedStmt(
930 const ObjCAtSynchronizedStmt &S) {
931 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
934 CGObjCRuntime::~CGObjCRuntime() {}