blob: a23ba4921c8640f2b9d6d1d6c5f2d678ec19403f [file] [log] [blame]
Chris Lattner85a932e2008-01-04 22:32:30 +00001//===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for Objective-C expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
John McCall5f1e0942010-08-24 08:50:51 +000016#include "clang/Sema/Scope.h"
John McCall26743b22011-02-03 09:00:02 +000017#include "clang/Sema/ScopeInfo.h"
Douglas Gregore737f502010-08-12 20:07:10 +000018#include "clang/Sema/Initialization.h"
John McCall2cf031d2011-10-01 01:01:08 +000019#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
Chris Lattner85a932e2008-01-04 22:32:30 +000020#include "clang/AST/ASTContext.h"
21#include "clang/AST/DeclObjC.h"
Steve Narofff494b572008-05-29 21:12:08 +000022#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000023#include "clang/AST/StmtVisitor.h"
Douglas Gregor2725ca82010-04-21 19:57:20 +000024#include "clang/AST/TypeLoc.h"
Chris Lattner39c28bb2009-02-18 06:48:40 +000025#include "llvm/ADT/SmallString.h"
Steve Naroff61f72cb2009-03-09 21:12:44 +000026#include "clang/Lex/Preprocessor.h"
27
Chris Lattner85a932e2008-01-04 22:32:30 +000028using namespace clang;
John McCall26743b22011-02-03 09:00:02 +000029using namespace sema;
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +000030using llvm::makeArrayRef;
Chris Lattner85a932e2008-01-04 22:32:30 +000031
John McCallf312b1e2010-08-26 23:41:50 +000032ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
33 Expr **strings,
34 unsigned NumStrings) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000035 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
36
Chris Lattnerf4b136f2009-02-18 06:13:04 +000037 // Most ObjC strings are formed out of a single piece. However, we *can*
38 // have strings formed out of multiple @ strings with multiple pptokens in
39 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
40 // StringLiteral for ObjCStringLiteral to hold onto.
Chris Lattner39c28bb2009-02-18 06:48:40 +000041 StringLiteral *S = Strings[0];
Mike Stump1eb44332009-09-09 15:08:12 +000042
Chris Lattnerf4b136f2009-02-18 06:13:04 +000043 // If we have a multi-part string, merge it all together.
44 if (NumStrings != 1) {
Chris Lattner85a932e2008-01-04 22:32:30 +000045 // Concatenate objc strings.
Chris Lattner39c28bb2009-02-18 06:48:40 +000046 llvm::SmallString<128> StrBuf;
Chris Lattner5f9e2722011-07-23 10:55:15 +000047 SmallVector<SourceLocation, 8> StrLocs;
Mike Stump1eb44332009-09-09 15:08:12 +000048
Chris Lattner726e1682009-02-18 05:49:11 +000049 for (unsigned i = 0; i != NumStrings; ++i) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000050 S = Strings[i];
Mike Stump1eb44332009-09-09 15:08:12 +000051
Douglas Gregor5cee1192011-07-27 05:40:30 +000052 // ObjC strings can't be wide or UTF.
53 if (!S->isAscii()) {
Chris Lattnerf4b136f2009-02-18 06:13:04 +000054 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
55 << S->getSourceRange();
56 return true;
57 }
Mike Stump1eb44332009-09-09 15:08:12 +000058
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +000059 // Append the string.
60 StrBuf += S->getString();
Mike Stump1eb44332009-09-09 15:08:12 +000061
Chris Lattner39c28bb2009-02-18 06:48:40 +000062 // Get the locations of the string tokens.
63 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Chris Lattner85a932e2008-01-04 22:32:30 +000064 }
Mike Stump1eb44332009-09-09 15:08:12 +000065
Chris Lattner39c28bb2009-02-18 06:48:40 +000066 // Create the aggregate string with the appropriate content and location
67 // information.
Jay Foad65aa6882011-06-21 15:13:30 +000068 S = StringLiteral::Create(Context, StrBuf,
Douglas Gregor5cee1192011-07-27 05:40:30 +000069 StringLiteral::Ascii, /*Pascal=*/false,
Chris Lattner2085fd62009-02-18 06:40:38 +000070 Context.getPointerType(Context.CharTy),
Chris Lattner39c28bb2009-02-18 06:48:40 +000071 &StrLocs[0], StrLocs.size());
Chris Lattner85a932e2008-01-04 22:32:30 +000072 }
Mike Stump1eb44332009-09-09 15:08:12 +000073
Chris Lattner69039812009-02-18 06:01:06 +000074 // Verify that this composite string is acceptable for ObjC strings.
75 if (CheckObjCString(S))
Chris Lattner85a932e2008-01-04 22:32:30 +000076 return true;
Chris Lattnera0af1fe2009-02-18 06:06:56 +000077
78 // Initialize the constant string interface lazily. This assumes
Steve Naroffd9fd7642009-04-07 14:18:33 +000079 // the NSString interface is seen in this translation unit. Note: We
80 // don't use NSConstantString, since the runtime team considers this
81 // interface private (even though it appears in the header files).
Chris Lattnera0af1fe2009-02-18 06:06:56 +000082 QualType Ty = Context.getObjCConstantStringInterface();
83 if (!Ty.isNull()) {
Steve Naroff14108da2009-07-10 23:34:53 +000084 Ty = Context.getObjCObjectPointerType(Ty);
Fariborz Jahanian8a437762010-04-23 23:19:04 +000085 } else if (getLangOptions().NoConstantCFStrings) {
Fariborz Jahanian4c733072010-10-19 17:19:29 +000086 IdentifierInfo *NSIdent=0;
87 std::string StringClass(getLangOptions().ObjCConstantStringClass);
88
89 if (StringClass.empty())
90 NSIdent = &Context.Idents.get("NSConstantString");
91 else
92 NSIdent = &Context.Idents.get(StringClass);
93
Fariborz Jahanian8a437762010-04-23 23:19:04 +000094 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
95 LookupOrdinaryName);
96 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
97 Context.setObjCConstantStringInterface(StrIF);
98 Ty = Context.getObjCConstantStringInterface();
99 Ty = Context.getObjCObjectPointerType(Ty);
100 } else {
101 // If there is no NSConstantString interface defined then treat this
102 // as error and recover from it.
103 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
104 << S->getSourceRange();
105 Ty = Context.getObjCIdType();
106 }
Chris Lattner13fd7e52008-06-21 21:44:18 +0000107 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +0000108 IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
Douglas Gregorc83c6872010-04-15 22:33:43 +0000109 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
110 LookupOrdinaryName);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000111 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
112 Context.setObjCConstantStringInterface(StrIF);
113 Ty = Context.getObjCConstantStringInterface();
Steve Naroff14108da2009-07-10 23:34:53 +0000114 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000115 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +0000116 // If there is no NSString interface defined then treat constant
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000117 // strings as untyped objects and let the runtime figure it out later.
118 Ty = Context.getObjCIdType();
119 }
Chris Lattner13fd7e52008-06-21 21:44:18 +0000120 }
Mike Stump1eb44332009-09-09 15:08:12 +0000121
Chris Lattnerf4b136f2009-02-18 06:13:04 +0000122 return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]);
Chris Lattner85a932e2008-01-04 22:32:30 +0000123}
124
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000125ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregor81d34662010-04-20 15:39:42 +0000126 TypeSourceInfo *EncodedTypeInfo,
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000127 SourceLocation RParenLoc) {
Douglas Gregor81d34662010-04-20 15:39:42 +0000128 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000129 QualType StrTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000130 if (EncodedType->isDependentType())
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000131 StrTy = Context.DependentTy;
132 else {
Fariborz Jahanian6c916152011-06-16 22:34:44 +0000133 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
134 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000135 if (RequireCompleteType(AtLoc, EncodedType,
136 PDiag(diag::err_incomplete_type_objc_at_encode)
137 << EncodedTypeInfo->getTypeLoc().getSourceRange()))
138 return ExprError();
139
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000140 std::string Str;
141 Context.getObjCEncodingForType(EncodedType, Str);
142
143 // The type of @encode is the same as the type of the corresponding string,
144 // which is an array type.
145 StrTy = Context.CharTy;
146 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
John McCall4b7a8342010-03-15 10:54:44 +0000147 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000148 StrTy.addConst();
149 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
150 ArrayType::Normal, 0);
151 }
Mike Stump1eb44332009-09-09 15:08:12 +0000152
Douglas Gregor81d34662010-04-20 15:39:42 +0000153 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000154}
155
John McCallf312b1e2010-08-26 23:41:50 +0000156ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
157 SourceLocation EncodeLoc,
158 SourceLocation LParenLoc,
159 ParsedType ty,
160 SourceLocation RParenLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000161 // FIXME: Preserve type source info ?
Douglas Gregor81d34662010-04-20 15:39:42 +0000162 TypeSourceInfo *TInfo;
163 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
164 if (!TInfo)
165 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
166 PP.getLocForEndOfToken(LParenLoc));
Chris Lattner85a932e2008-01-04 22:32:30 +0000167
Douglas Gregor81d34662010-04-20 15:39:42 +0000168 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000169}
170
John McCallf312b1e2010-08-26 23:41:50 +0000171ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
172 SourceLocation AtLoc,
173 SourceLocation SelLoc,
174 SourceLocation LParenLoc,
175 SourceLocation RParenLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000176 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000177 SourceRange(LParenLoc, RParenLoc), false, false);
Fariborz Jahanian7ff22de2009-06-16 16:25:00 +0000178 if (!Method)
179 Method = LookupFactoryMethodInGlobalPool(Sel,
180 SourceRange(LParenLoc, RParenLoc));
181 if (!Method)
182 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Fariborz Jahanian4c91d892011-07-13 19:05:43 +0000183
184 if (!Method ||
185 Method->getImplementationControl() != ObjCMethodDecl::Optional) {
186 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
187 = ReferencedSelectors.find(Sel);
188 if (Pos == ReferencedSelectors.end())
189 ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
190 }
Fariborz Jahanian3fe10412010-07-22 18:24:20 +0000191
John McCallf85e1932011-06-15 23:02:42 +0000192 // In ARC, forbid the user from using @selector for
193 // retain/release/autorelease/dealloc/retainCount.
194 if (getLangOptions().ObjCAutoRefCount) {
195 switch (Sel.getMethodFamily()) {
196 case OMF_retain:
197 case OMF_release:
198 case OMF_autorelease:
199 case OMF_retainCount:
200 case OMF_dealloc:
201 Diag(AtLoc, diag::err_arc_illegal_selector) <<
202 Sel << SourceRange(LParenLoc, RParenLoc);
203 break;
204
205 case OMF_None:
206 case OMF_alloc:
207 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +0000208 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +0000209 case OMF_init:
210 case OMF_mutableCopy:
211 case OMF_new:
212 case OMF_self:
Fariborz Jahanian9670e172011-07-05 22:38:59 +0000213 case OMF_performSelector:
John McCallf85e1932011-06-15 23:02:42 +0000214 break;
215 }
216 }
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000217 QualType Ty = Context.getObjCSelType();
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000218 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000219}
220
John McCallf312b1e2010-08-26 23:41:50 +0000221ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
222 SourceLocation AtLoc,
223 SourceLocation ProtoLoc,
224 SourceLocation LParenLoc,
225 SourceLocation RParenLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000226 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000227 if (!PDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000228 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattner85a932e2008-01-04 22:32:30 +0000229 return true;
230 }
Mike Stump1eb44332009-09-09 15:08:12 +0000231
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000232 QualType Ty = Context.getObjCProtoType();
233 if (Ty.isNull())
Chris Lattner85a932e2008-01-04 22:32:30 +0000234 return true;
Steve Naroff14108da2009-07-10 23:34:53 +0000235 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000236 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000237}
238
John McCall26743b22011-02-03 09:00:02 +0000239/// Try to capture an implicit reference to 'self'.
240ObjCMethodDecl *Sema::tryCaptureObjCSelf() {
241 // Ignore block scopes: we can capture through them.
242 DeclContext *DC = CurContext;
243 while (true) {
244 if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
245 else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
246 else break;
247 }
248
249 // If we're not in an ObjC method, error out. Note that, unlike the
250 // C++ case, we don't require an instance method --- class methods
251 // still have a 'self', and we really do still need to capture it!
252 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
253 if (!method)
254 return 0;
255
256 ImplicitParamDecl *self = method->getSelfDecl();
257 assert(self && "capturing 'self' in non-definition?");
258
259 // Mark that we're closing on 'this' in all the block scopes, if applicable.
260 for (unsigned idx = FunctionScopes.size() - 1;
261 isa<BlockScopeInfo>(FunctionScopes[idx]);
John McCall6b5a61b2011-02-07 10:33:21 +0000262 --idx) {
263 BlockScopeInfo *blockScope = cast<BlockScopeInfo>(FunctionScopes[idx]);
264 unsigned &captureIndex = blockScope->CaptureMap[self];
265 if (captureIndex) break;
266
267 bool nested = isa<BlockScopeInfo>(FunctionScopes[idx-1]);
268 blockScope->Captures.push_back(
269 BlockDecl::Capture(self, /*byref*/ false, nested, /*copy*/ 0));
270 captureIndex = blockScope->Captures.size(); // +1
271 }
John McCall26743b22011-02-03 09:00:02 +0000272
273 return method;
274}
275
Douglas Gregor5c16d632011-09-09 20:05:21 +0000276static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
277 if (T == Context.getObjCInstanceType())
278 return Context.getObjCIdType();
279
280 return T;
281}
282
Douglas Gregor926df6c2011-06-11 01:09:30 +0000283QualType Sema::getMessageSendResultType(QualType ReceiverType,
284 ObjCMethodDecl *Method,
285 bool isClassMessage, bool isSuperMessage) {
286 assert(Method && "Must have a method");
287 if (!Method->hasRelatedResultType())
288 return Method->getSendResultType();
289
290 // If a method has a related return type:
291 // - if the method found is an instance method, but the message send
292 // was a class message send, T is the declared return type of the method
293 // found
294 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregor5c16d632011-09-09 20:05:21 +0000295 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor926df6c2011-06-11 01:09:30 +0000296
297 // - if the receiver is super, T is a pointer to the class of the
298 // enclosing method definition
299 if (isSuperMessage) {
300 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
301 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
302 return Context.getObjCObjectPointerType(
303 Context.getObjCInterfaceType(Class));
304 }
305
306 // - if the receiver is the name of a class U, T is a pointer to U
307 if (ReceiverType->getAs<ObjCInterfaceType>() ||
308 ReceiverType->isObjCQualifiedInterfaceType())
309 return Context.getObjCObjectPointerType(ReceiverType);
310 // - if the receiver is of type Class or qualified Class type,
311 // T is the declared return type of the method.
312 if (ReceiverType->isObjCClassType() ||
313 ReceiverType->isObjCQualifiedClassType())
Douglas Gregor5c16d632011-09-09 20:05:21 +0000314 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor926df6c2011-06-11 01:09:30 +0000315
316 // - if the receiver is id, qualified id, Class, or qualified Class, T
317 // is the receiver type, otherwise
318 // - T is the type of the receiver expression.
319 return ReceiverType;
320}
John McCall26743b22011-02-03 09:00:02 +0000321
Douglas Gregor926df6c2011-06-11 01:09:30 +0000322void Sema::EmitRelatedResultTypeNote(const Expr *E) {
323 E = E->IgnoreParenImpCasts();
324 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
325 if (!MsgSend)
326 return;
327
328 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
329 if (!Method)
330 return;
331
332 if (!Method->hasRelatedResultType())
333 return;
334
335 if (Context.hasSameUnqualifiedType(Method->getResultType()
336 .getNonReferenceType(),
337 MsgSend->getType()))
338 return;
339
Douglas Gregore97179c2011-09-08 01:46:34 +0000340 if (!Context.hasSameUnqualifiedType(Method->getResultType(),
341 Context.getObjCInstanceType()))
342 return;
343
Douglas Gregor926df6c2011-06-11 01:09:30 +0000344 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
345 << Method->isInstanceMethod() << Method->getSelector()
346 << MsgSend->getType();
347}
348
349bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
350 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000351 Selector Sel, ObjCMethodDecl *Method,
Douglas Gregor926df6c2011-06-11 01:09:30 +0000352 bool isClassMessage, bool isSuperMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000353 SourceLocation lbrac, SourceLocation rbrac,
John McCallf89e55a2010-11-18 06:31:45 +0000354 QualType &ReturnType, ExprValueKind &VK) {
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000355 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000356 // Apply default argument promotion as for (C99 6.5.2.2p6).
Douglas Gregor92e986e2010-04-22 16:44:27 +0000357 for (unsigned i = 0; i != NumArgs; i++) {
358 if (Args[i]->isTypeDependent())
359 continue;
360
John Wiegley429bb272011-04-08 18:41:53 +0000361 ExprResult Result = DefaultArgumentPromotion(Args[i]);
362 if (Result.isInvalid())
363 return true;
364 Args[i] = Result.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000365 }
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000366
John McCallf85e1932011-06-15 23:02:42 +0000367 unsigned DiagID;
368 if (getLangOptions().ObjCAutoRefCount)
369 DiagID = diag::err_arc_method_not_found;
370 else
371 DiagID = isClassMessage ? diag::warn_class_method_not_found
372 : diag::warn_inst_method_not_found;
John McCall819e7452011-08-31 20:57:36 +0000373 if (!getLangOptions().DebuggerSupport)
374 Diag(lbrac, DiagID)
375 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
John McCall48218c62011-07-13 17:56:40 +0000376
377 // In debuggers, we want to use __unknown_anytype for these
378 // results so that clients can cast them.
379 if (getLangOptions().DebuggerSupport) {
380 ReturnType = Context.UnknownAnyTy;
381 } else {
382 ReturnType = Context.getObjCIdType();
383 }
John McCallf89e55a2010-11-18 06:31:45 +0000384 VK = VK_RValue;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000385 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000386 }
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Douglas Gregor926df6c2011-06-11 01:09:30 +0000388 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
389 isSuperMessage);
John McCallf89e55a2010-11-18 06:31:45 +0000390 VK = Expr::getValueKindForType(Method->getResultType());
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000392 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000393 // Method might have more arguments than selector indicates. This is due
394 // to addition of c-style arguments in method.
395 if (Method->param_size() > Sel.getNumArgs())
396 NumNamedArgs = Method->param_size();
397 // FIXME. This need be cleaned up.
398 if (NumArgs < NumNamedArgs) {
John McCallf89e55a2010-11-18 06:31:45 +0000399 Diag(lbrac, diag::err_typecheck_call_too_few_args)
400 << 2 << NumNamedArgs << NumArgs;
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000401 return false;
402 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000403
Chris Lattner312531a2009-04-12 08:11:20 +0000404 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000405 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000406 // We can't do any type-checking on a type-dependent argument.
407 if (Args[i]->isTypeDependent())
408 continue;
409
Chris Lattner85a932e2008-01-04 22:32:30 +0000410 Expr *argExpr = Args[i];
Douglas Gregor92e986e2010-04-22 16:44:27 +0000411
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000412 ParmVarDecl *Param = Method->param_begin()[i];
Chris Lattner85a932e2008-01-04 22:32:30 +0000413 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000415 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
416 Param->getType(),
417 PDiag(diag::err_call_incomplete_argument)
418 << argExpr->getSourceRange()))
419 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +0000420
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000421 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
422 Param);
John McCall3fa5cae2010-10-26 07:05:15 +0000423 ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000424 if (ArgE.isInvalid())
425 IsError = true;
426 else
427 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +0000428 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000429
430 // Promote additional arguments to variadic methods.
431 if (Method->isVariadic()) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000432 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
433 if (Args[i]->isTypeDependent())
434 continue;
435
John Wiegley429bb272011-04-08 18:41:53 +0000436 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
437 IsError |= Arg.isInvalid();
438 Args[i] = Arg.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000439 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000440 } else {
441 // Check for extra arguments to non-variadic methods.
442 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +0000443 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000444 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000445 << 2 /*method*/ << NumNamedArgs << NumArgs
446 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000447 << SourceRange(Args[NumNamedArgs]->getLocStart(),
448 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000449 }
450 }
Fariborz Jahanian5272adf2011-04-15 22:06:22 +0000451 // diagnose nonnull arguments.
452 for (specific_attr_iterator<NonNullAttr>
453 i = Method->specific_attr_begin<NonNullAttr>(),
454 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
455 CheckNonNullArguments(*i, Args, lbrac);
456 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000457
Douglas Gregor2725ca82010-04-21 19:57:20 +0000458 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Chris Lattner312531a2009-04-12 08:11:20 +0000459 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +0000460}
461
Douglas Gregorc737acb2011-09-27 16:10:05 +0000462bool Sema::isSelfExpr(Expr *receiver) {
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +0000463 // 'self' is objc 'self' in an objc method only.
Fariborz Jahanianb4602102011-03-28 16:23:34 +0000464 DeclContext *DC = CurContext;
465 while (isa<BlockDecl>(DC))
466 DC = DC->getParent();
467 if (DC && !isa<ObjCMethodDecl>(DC))
Douglas Gregorc737acb2011-09-27 16:10:05 +0000468 return false;
John McCallf85e1932011-06-15 23:02:42 +0000469 receiver = receiver->IgnoreParenLValueCasts();
470 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000471 if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
Douglas Gregorc737acb2011-09-27 16:10:05 +0000472 return true;
473 return false;
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000474}
475
Steve Narofff1afaf62009-02-26 15:55:06 +0000476// Helper method for ActOnClassMethod/ActOnInstanceMethod.
477// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000478// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +0000479// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +0000480ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +0000481 ObjCInterfaceDecl *ClassDecl) {
482 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +0000483 // lookup in class and all superclasses
484 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000485 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000486 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000487
Steve Naroff5609ec02009-03-08 18:56:13 +0000488 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000489 if (!Method)
490 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000491
Steve Naroff5609ec02009-03-08 18:56:13 +0000492 // Before we give up, check if the selector is an instance method.
493 // But only in the root. This matches gcc's behaviour and what the
494 // runtime expects.
495 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000496 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000497 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +0000498 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +0000499 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +0000500 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
501 }
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Steve Naroff5609ec02009-03-08 18:56:13 +0000503 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +0000504 }
Steve Naroff5609ec02009-03-08 18:56:13 +0000505 return Method;
506}
507
508ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
509 ObjCInterfaceDecl *ClassDecl) {
510 ObjCMethodDecl *Method = 0;
511 while (ClassDecl && !Method) {
512 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000513 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000514 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Steve Naroff5609ec02009-03-08 18:56:13 +0000516 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000517 if (!Method)
518 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +0000519 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000520 }
Steve Narofff1afaf62009-02-26 15:55:06 +0000521 return Method;
522}
523
Fariborz Jahanian61478062011-03-09 20:18:06 +0000524/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
525/// list of a qualified objective pointer type.
526ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
527 const ObjCObjectPointerType *OPT,
528 bool Instance)
529{
530 ObjCMethodDecl *MD = 0;
531 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
532 E = OPT->qual_end(); I != E; ++I) {
533 ObjCProtocolDecl *PROTO = (*I);
534 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
535 return MD;
536 }
537 }
538 return 0;
539}
540
Chris Lattner7f816522010-04-11 07:45:24 +0000541/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
542/// objective C interface. This is a property reference expression.
John McCall60d7b3a2010-08-24 06:29:42 +0000543ExprResult Sema::
Chris Lattner7f816522010-04-11 07:45:24 +0000544HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000545 Expr *BaseExpr, SourceLocation OpLoc,
546 DeclarationName MemberName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000547 SourceLocation MemberLoc,
548 SourceLocation SuperLoc, QualType SuperType,
549 bool Super) {
Chris Lattner7f816522010-04-11 07:45:24 +0000550 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
551 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Douglas Gregor109ec1b2011-04-20 18:19:55 +0000552
553 if (MemberName.getNameKind() != DeclarationName::Identifier) {
554 Diag(MemberLoc, diag::err_invalid_property_name)
555 << MemberName << QualType(OPT, 0);
556 return ExprError();
557 }
558
Chris Lattner7f816522010-04-11 07:45:24 +0000559 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
560
Fariborz Jahanian8b1aba42010-12-16 00:56:28 +0000561 if (IFace->isForwardDecl()) {
562 Diag(MemberLoc, diag::err_property_not_found_forward_class)
563 << MemberName << QualType(OPT, 0);
564 Diag(IFace->getLocation(), diag::note_forward_class);
565 return ExprError();
566 }
Chris Lattner7f816522010-04-11 07:45:24 +0000567 // Search for a declared property first.
568 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
569 // Check whether we can reference this property.
570 if (DiagnoseUseOfDecl(PD, MemberLoc))
571 return ExprError();
572 QualType ResTy = PD->getType();
Fariborz Jahanian14086762011-03-28 23:47:18 +0000573 ResTy = ResTy.getNonLValueExprType(Context);
Chris Lattner7f816522010-04-11 07:45:24 +0000574 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
575 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000576 if (Getter &&
577 (Getter->hasRelatedResultType()
578 || DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc)))
579 ResTy = getMessageSendResultType(QualType(OPT, 0), Getter, false,
580 Super);
581
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000582 if (Super)
583 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
John McCallf89e55a2010-11-18 06:31:45 +0000584 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000585 MemberLoc,
586 SuperLoc, SuperType));
587 else
588 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
John McCallf89e55a2010-11-18 06:31:45 +0000589 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000590 MemberLoc, BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000591 }
592 // Check protocols on qualified interfaces.
593 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
594 E = OPT->qual_end(); I != E; ++I)
595 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
596 // Check whether we can reference this property.
597 if (DiagnoseUseOfDecl(PD, MemberLoc))
598 return ExprError();
Douglas Gregor926df6c2011-06-11 01:09:30 +0000599
600 QualType T = PD->getType();
601 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
602 T = getMessageSendResultType(QualType(OPT, 0), Getter, false, Super);
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000603 if (Super)
Douglas Gregor926df6c2011-06-11 01:09:30 +0000604 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
John McCallf89e55a2010-11-18 06:31:45 +0000605 VK_LValue,
606 OK_ObjCProperty,
607 MemberLoc,
608 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000609 else
Douglas Gregor926df6c2011-06-11 01:09:30 +0000610 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
John McCallf89e55a2010-11-18 06:31:45 +0000611 VK_LValue,
612 OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000613 MemberLoc,
614 BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000615 }
616 // If that failed, look for an "implicit" property by seeing if the nullary
617 // selector is implemented.
618
619 // FIXME: The logic for looking up nullary and unary selectors should be
620 // shared with the code in ActOnInstanceMessage.
621
622 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
623 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000624
625 // May be founf in property's qualified list.
626 if (!Getter)
627 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner7f816522010-04-11 07:45:24 +0000628
629 // If this reference is in an @implementation, check for 'private' methods.
630 if (!Getter)
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000631 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner7f816522010-04-11 07:45:24 +0000632
633 // Look through local category implementations associated with the class.
634 if (!Getter)
635 Getter = IFace->getCategoryInstanceMethod(Sel);
636 if (Getter) {
637 // Check if we can reference this property.
638 if (DiagnoseUseOfDecl(Getter, MemberLoc))
639 return ExprError();
640 }
641 // If we found a getter then this may be a valid dot-reference, we
642 // will look for the matching setter, in case it is needed.
643 Selector SetterSel =
644 SelectorTable::constructSetterName(PP.getIdentifierTable(),
645 PP.getSelectorTable(), Member);
646 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000647
648 // May be founf in property's qualified list.
649 if (!Setter)
650 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
651
Chris Lattner7f816522010-04-11 07:45:24 +0000652 if (!Setter) {
653 // If this reference is in an @implementation, also check for 'private'
654 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000655 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner7f816522010-04-11 07:45:24 +0000656 }
657 // Look through local category implementations associated with the class.
658 if (!Setter)
659 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000660
Chris Lattner7f816522010-04-11 07:45:24 +0000661 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
662 return ExprError();
663
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000664 if (Getter || Setter) {
665 QualType PType;
666 if (Getter)
Douglas Gregor926df6c2011-06-11 01:09:30 +0000667 PType = getMessageSendResultType(QualType(OPT, 0), Getter, false, Super);
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000668 else {
669 ParmVarDecl *ArgDecl = *Setter->param_begin();
670 PType = ArgDecl->getType();
671 }
672
John McCall09431682010-11-18 19:01:18 +0000673 ExprValueKind VK = VK_LValue;
674 ExprObjectKind OK = OK_ObjCProperty;
675 if (!getLangOptions().CPlusPlus && !PType.hasQualifiers() &&
676 PType->isVoidType())
677 VK = VK_RValue, OK = OK_Ordinary;
678
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000679 if (Super)
John McCall12f78a62010-12-02 01:19:52 +0000680 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
681 PType, VK, OK,
682 MemberLoc,
683 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000684 else
John McCall12f78a62010-12-02 01:19:52 +0000685 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
686 PType, VK, OK,
687 MemberLoc, BaseExpr));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000688
Chris Lattner7f816522010-04-11 07:45:24 +0000689 }
690
691 // Attempt to correct for typos in property names.
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000692 TypoCorrection Corrected = CorrectTypo(
693 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
694 NULL, IFace, false, CTC_NoKeywords, OPT);
695 if (ObjCPropertyDecl *Property =
696 Corrected.getCorrectionDeclAs<ObjCPropertyDecl>()) {
697 DeclarationName TypoResult = Corrected.getCorrection();
Chris Lattner7f816522010-04-11 07:45:24 +0000698 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000699 << MemberName << QualType(OPT, 0) << TypoResult
700 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +0000701 Diag(Property->getLocation(), diag::note_previous_decl)
702 << Property->getDeclName();
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000703 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
704 TypoResult, MemberLoc,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000705 SuperLoc, SuperType, Super);
Chris Lattner7f816522010-04-11 07:45:24 +0000706 }
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000707 ObjCInterfaceDecl *ClassDeclared;
708 if (ObjCIvarDecl *Ivar =
709 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
710 QualType T = Ivar->getType();
711 if (const ObjCObjectPointerType * OBJPT =
712 T->getAsObjCInterfacePointerType()) {
713 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
714 if (ObjCInterfaceDecl *IFace = IFaceT->getDecl())
715 if (IFace->isForwardDecl()) {
716 Diag(MemberLoc, diag::err_property_not_as_forward_class)
Fariborz Jahanian2a96bf52011-02-17 17:30:05 +0000717 << MemberName << IFace;
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000718 Diag(IFace->getLocation(), diag::note_forward_class);
719 return ExprError();
720 }
721 }
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000722 Diag(MemberLoc,
723 diag::err_ivar_access_using_property_syntax_suggest)
724 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
725 << FixItHint::CreateReplacement(OpLoc, "->");
726 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000727 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000728
Chris Lattner7f816522010-04-11 07:45:24 +0000729 Diag(MemberLoc, diag::err_property_not_found)
730 << MemberName << QualType(OPT, 0);
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000731 if (Setter)
Chris Lattner7f816522010-04-11 07:45:24 +0000732 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000733 << MemberName << BaseExpr->getSourceRange();
Chris Lattner7f816522010-04-11 07:45:24 +0000734 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +0000735}
736
737
738
John McCall60d7b3a2010-08-24 06:29:42 +0000739ExprResult Sema::
Chris Lattnereb483eb2010-04-11 08:28:14 +0000740ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
741 IdentifierInfo &propertyName,
742 SourceLocation receiverNameLoc,
743 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000744
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000745 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +0000746 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
747 receiverNameLoc);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000748
749 bool IsSuper = false;
Chris Lattnereb483eb2010-04-11 08:28:14 +0000750 if (IFace == 0) {
751 // If the "receiver" is 'super' in a method, handle it as an expression-like
752 // property reference.
John McCall26743b22011-02-03 09:00:02 +0000753 if (receiverNamePtr->isStr("super")) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000754 IsSuper = true;
755
John McCall26743b22011-02-03 09:00:02 +0000756 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf()) {
Chris Lattnereb483eb2010-04-11 08:28:14 +0000757 if (CurMethod->isInstanceMethod()) {
758 QualType T =
759 Context.getObjCInterfaceType(CurMethod->getClassInterface());
760 T = Context.getObjCObjectPointerType(T);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000761
762 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000763 /*BaseExpr*/0,
764 SourceLocation()/*OpLoc*/,
765 &propertyName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000766 propertyNameLoc,
767 receiverNameLoc, T, true);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000768 }
Mike Stump1eb44332009-09-09 15:08:12 +0000769
Chris Lattnereb483eb2010-04-11 08:28:14 +0000770 // Otherwise, if this is a class method, try dispatching to our
771 // superclass.
772 IFace = CurMethod->getClassInterface()->getSuperClass();
773 }
John McCall26743b22011-02-03 09:00:02 +0000774 }
Chris Lattnereb483eb2010-04-11 08:28:14 +0000775
776 if (IFace == 0) {
777 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
778 return ExprError();
779 }
780 }
781
782 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +0000783 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000784 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000785
786 // If this reference is in an @implementation, check for 'private' methods.
787 if (!Getter)
788 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
789 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000790 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000791 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000792
793 if (Getter) {
794 // FIXME: refactor/share with ActOnMemberReference().
795 // Check if we can reference this property.
796 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
797 return ExprError();
798 }
Mike Stump1eb44332009-09-09 15:08:12 +0000799
Steve Naroff61f72cb2009-03-09 21:12:44 +0000800 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +0000801 Selector SetterSel =
802 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +0000803 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +0000804
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000805 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000806 if (!Setter) {
807 // If this reference is in an @implementation, also check for 'private'
808 // methods.
809 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
810 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000811 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000812 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000813 }
814 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000815 if (!Setter)
816 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000817
818 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
819 return ExprError();
820
821 if (Getter || Setter) {
822 QualType PType;
823
John McCall09431682010-11-18 19:01:18 +0000824 ExprValueKind VK = VK_LValue;
825 if (Getter) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000826 PType = getMessageSendResultType(Context.getObjCInterfaceType(IFace),
827 Getter, true,
828 receiverNamePtr->isStr("super"));
John McCall09431682010-11-18 19:01:18 +0000829 if (!getLangOptions().CPlusPlus &&
830 !PType.hasQualifiers() && PType->isVoidType())
831 VK = VK_RValue;
832 } else {
Steve Naroff61f72cb2009-03-09 21:12:44 +0000833 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
834 E = Setter->param_end(); PI != E; ++PI)
835 PType = (*PI)->getType();
John McCall09431682010-11-18 19:01:18 +0000836 VK = VK_LValue;
Steve Naroff61f72cb2009-03-09 21:12:44 +0000837 }
John McCall09431682010-11-18 19:01:18 +0000838
839 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
840
Douglas Gregor926df6c2011-06-11 01:09:30 +0000841 if (IsSuper)
842 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
843 PType, VK, OK,
844 propertyNameLoc,
845 receiverNameLoc,
846 Context.getObjCInterfaceType(IFace)));
847
John McCall12f78a62010-12-02 01:19:52 +0000848 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
849 PType, VK, OK,
850 propertyNameLoc,
851 receiverNameLoc, IFace));
Steve Naroff61f72cb2009-03-09 21:12:44 +0000852 }
853 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
854 << &propertyName << Context.getObjCInterfaceType(IFace));
855}
856
Douglas Gregor47bd5432010-04-14 02:46:37 +0000857Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +0000858 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +0000859 SourceLocation NameLoc,
860 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +0000861 bool HasTrailingDot,
John McCallb3d87482010-08-24 05:47:05 +0000862 ParsedType &ReceiverType) {
863 ReceiverType = ParsedType();
Douglas Gregor1569f952010-04-21 20:38:13 +0000864
Douglas Gregor47bd5432010-04-14 02:46:37 +0000865 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor95f42922010-10-14 22:11:03 +0000866 // messaging super. If the identifier is "super" and there is a
867 // trailing dot, it's an instance message.
868 if (IsSuper && S->isInObjcMethodScope())
869 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000870
871 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
872 LookupName(Result, S);
873
874 switch (Result.getResultKind()) {
875 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +0000876 // Normal name lookup didn't find anything. If we're in an
877 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor95f42922010-10-14 22:11:03 +0000878 // FIXME: This is a hack. Ivar lookup should be part of normal
879 // lookup.
Douglas Gregored464422010-04-19 20:09:36 +0000880 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
881 ObjCInterfaceDecl *ClassDeclared;
882 if (Method->getClassInterface()->lookupInstanceVariable(Name,
883 ClassDeclared))
884 return ObjCInstanceMessage;
885 }
Douglas Gregor95f42922010-10-14 22:11:03 +0000886
Douglas Gregor47bd5432010-04-14 02:46:37 +0000887 // Break out; we'll perform typo correction below.
888 break;
889
890 case LookupResult::NotFoundInCurrentInstantiation:
891 case LookupResult::FoundOverloaded:
892 case LookupResult::FoundUnresolvedValue:
893 case LookupResult::Ambiguous:
894 Result.suppressDiagnostics();
895 return ObjCInstanceMessage;
896
897 case LookupResult::Found: {
Fariborz Jahanian8348de32011-02-08 00:23:07 +0000898 // If the identifier is a class or not, and there is a trailing dot,
899 // it's an instance message.
900 if (HasTrailingDot)
901 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000902 // We found something. If it's a type, then we have a class
903 // message. Otherwise, it's an instance message.
904 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000905 QualType T;
906 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
907 T = Context.getObjCInterfaceType(Class);
908 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
909 T = Context.getTypeDeclType(Type);
910 else
911 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000912
Douglas Gregor1569f952010-04-21 20:38:13 +0000913 // We have a class message, and T is the type we're
914 // messaging. Build source-location information for it.
915 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000916 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregor1569f952010-04-21 20:38:13 +0000917 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000918 }
919 }
920
Douglas Gregoraaf87162010-04-14 20:04:41 +0000921 // Determine our typo-correction context.
922 CorrectTypoContext CTC = CTC_Expression;
923 if (ObjCMethodDecl *Method = getCurMethodDecl())
924 if (Method->getClassInterface() &&
925 Method->getClassInterface()->getSuperClass())
926 CTC = CTC_ObjCMessageReceiver;
927
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000928 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
929 Result.getLookupKind(), S, NULL,
930 NULL, false, CTC)) {
931 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000932 // If we found a declaration, correct when it refers to an Objective-C
933 // class.
Douglas Gregor1569f952010-04-21 20:38:13 +0000934 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000935 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000936 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +0000937 << FixItHint::CreateReplacement(SourceRange(NameLoc),
938 ND->getNameAsString());
939 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000940 << Corrected.getCorrection();
Douglas Gregor47bd5432010-04-14 02:46:37 +0000941
Douglas Gregor1569f952010-04-21 20:38:13 +0000942 QualType T = Context.getObjCInterfaceType(Class);
943 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000944 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000945 return ObjCClassMessage;
946 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000947 } else if (Corrected.isKeyword() &&
948 Corrected.getCorrectionAsIdentifierInfo()->isStr("super")) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000949 // If we've found the keyword "super", this is a send to super.
950 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000951 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +0000952 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
Douglas Gregoraaf87162010-04-14 20:04:41 +0000953 return ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000954 }
955 }
956
957 // Fall back: let the parser try to parse it as an instance message.
958 return ObjCInstanceMessage;
959}
Steve Naroff61f72cb2009-03-09 21:12:44 +0000960
John McCall60d7b3a2010-08-24 06:29:42 +0000961ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000962 SourceLocation SuperLoc,
963 Selector Sel,
964 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +0000965 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000966 SourceLocation RBracLoc,
967 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000968 // Determine whether we are inside a method or not.
John McCall26743b22011-02-03 09:00:02 +0000969 ObjCMethodDecl *Method = tryCaptureObjCSelf();
Douglas Gregorf95861a2010-04-21 20:01:04 +0000970 if (!Method) {
971 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
972 return ExprError();
973 }
Chris Lattner85a932e2008-01-04 22:32:30 +0000974
Douglas Gregorf95861a2010-04-21 20:01:04 +0000975 ObjCInterfaceDecl *Class = Method->getClassInterface();
976 if (!Class) {
977 Diag(SuperLoc, diag::error_no_super_class_message)
978 << Method->getDeclName();
979 return ExprError();
980 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000981
Douglas Gregorf95861a2010-04-21 20:01:04 +0000982 ObjCInterfaceDecl *Super = Class->getSuperClass();
983 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000984 // The current class does not have a superclass.
Ted Kremeneke00909a2011-01-23 17:21:34 +0000985 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
986 << Class->getIdentifier();
Douglas Gregor2725ca82010-04-21 19:57:20 +0000987 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +0000988 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000989
Douglas Gregorf95861a2010-04-21 20:01:04 +0000990 // We are in a method whose class has a superclass, so 'super'
991 // is acting as a keyword.
992 if (Method->isInstanceMethod()) {
Nico Weber9a1ecf02011-08-22 17:25:57 +0000993 if (Sel.getMethodFamily() == OMF_dealloc)
994 ObjCShouldCallSuperDealloc = false;
Nico Weber80cb6e62011-08-28 22:35:17 +0000995 if (Sel.getMethodFamily() == OMF_finalize)
996 ObjCShouldCallSuperFinalize = false;
Nico Weber9a1ecf02011-08-22 17:25:57 +0000997
Douglas Gregorf95861a2010-04-21 20:01:04 +0000998 // Since we are in an instance method, this is an instance
999 // message to the superclass instance.
1000 QualType SuperTy = Context.getObjCInterfaceType(Super);
1001 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall9ae2f072010-08-23 23:25:46 +00001002 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001003 Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001004 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001005 }
Douglas Gregorf95861a2010-04-21 20:01:04 +00001006
1007 // Since we are in a class method, this is a class message to
1008 // the superclass.
1009 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1010 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001011 SuperLoc, Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001012 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001013}
1014
1015/// \brief Build an Objective-C class message expression.
1016///
1017/// This routine takes care of both normal class messages and
1018/// class messages to the superclass.
1019///
1020/// \param ReceiverTypeInfo Type source information that describes the
1021/// receiver of this message. This may be NULL, in which case we are
1022/// sending to the superclass and \p SuperLoc must be a valid source
1023/// location.
1024
1025/// \param ReceiverType The type of the object receiving the
1026/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
1027/// type as that refers to. For a superclass send, this is the type of
1028/// the superclass.
1029///
1030/// \param SuperLoc The location of the "super" keyword in a
1031/// superclass message.
1032///
1033/// \param Sel The selector to which the message is being sent.
1034///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001035/// \param Method The method that this class message is invoking, if
1036/// already known.
1037///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001038/// \param LBracLoc The location of the opening square bracket ']'.
1039///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001040/// \param RBrac The location of the closing square bracket ']'.
1041///
1042/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001043ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001044 QualType ReceiverType,
1045 SourceLocation SuperLoc,
1046 Selector Sel,
1047 ObjCMethodDecl *Method,
1048 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001049 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001050 SourceLocation RBracLoc,
1051 MultiExprArg ArgsIn) {
1052 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregor9497a732010-09-16 01:51:54 +00001053 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor0fbda682010-09-15 14:51:05 +00001054 if (LBracLoc.isInvalid()) {
1055 Diag(Loc, diag::err_missing_open_square_message_send)
1056 << FixItHint::CreateInsertion(Loc, "[");
1057 LBracLoc = Loc;
1058 }
1059
Douglas Gregor92e986e2010-04-22 16:44:27 +00001060 if (ReceiverType->isDependentType()) {
1061 // If the receiver type is dependent, we can't type-check anything
1062 // at this point. Build a dependent expression.
1063 unsigned NumArgs = ArgsIn.size();
1064 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1065 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCallf89e55a2010-11-18 06:31:45 +00001066 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1067 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001068 Sel, SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001069 makeArrayRef(Args, NumArgs),RBracLoc));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001070 }
Chris Lattner15faee12010-04-12 05:38:43 +00001071
Douglas Gregor2725ca82010-04-21 19:57:20 +00001072 // Find the class to which we are sending this message.
1073 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00001074 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1075 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001076 Diag(Loc, diag::err_invalid_receiver_class_message)
1077 << ReceiverType;
1078 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +00001079 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001080 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanian43bcdb22011-10-15 19:18:36 +00001081 // objc++ diagnoses during typename annotation.
1082 if (!getLangOptions().CPlusPlus)
1083 (void)DiagnoseUseOfDecl(Class, Loc);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001084 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001085 if (!Method) {
1086 if (Class->isForwardDecl()) {
John McCallf85e1932011-06-15 23:02:42 +00001087 if (getLangOptions().ObjCAutoRefCount) {
1088 Diag(Loc, diag::err_arc_receiver_forward_class) << ReceiverType;
1089 } else {
1090 Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
1091 }
1092
Douglas Gregorf49bb082010-04-22 17:01:48 +00001093 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorf49bb082010-04-22 17:01:48 +00001094 Method = LookupFactoryMethodInGlobalPool(Sel,
1095 SourceRange(LBracLoc, RBracLoc));
John McCallf85e1932011-06-15 23:02:42 +00001096 if (Method && !getLangOptions().ObjCAutoRefCount)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001097 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1098 << Method->getDeclName();
1099 }
1100 if (!Method)
1101 Method = Class->lookupClassMethod(Sel);
1102
1103 // If we have an implementation in scope, check "private" methods.
1104 if (!Method)
1105 Method = LookupPrivateClassMethod(Sel, Class);
1106
1107 if (Method && DiagnoseUseOfDecl(Method, Loc))
1108 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +00001109 }
Mike Stump1eb44332009-09-09 15:08:12 +00001110
Douglas Gregor2725ca82010-04-21 19:57:20 +00001111 // Check the argument types and determine the result type.
1112 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001113 ExprValueKind VK = VK_RValue;
1114
Douglas Gregor2725ca82010-04-21 19:57:20 +00001115 unsigned NumArgs = ArgsIn.size();
1116 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001117 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1118 SuperLoc.isValid(), LBracLoc, RBracLoc,
1119 ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001120 return ExprError();
Ted Kremenek4df728e2008-06-24 15:50:53 +00001121
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001122 if (Method && !Method->getResultType()->isVoidType() &&
1123 RequireCompleteType(LBracLoc, Method->getResultType(),
1124 diag::err_illegal_message_expr_incomplete_type))
1125 return ExprError();
1126
Douglas Gregor2725ca82010-04-21 19:57:20 +00001127 // Construct the appropriate ObjCMessageExpr.
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001128 Expr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001129 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001130 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001131 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001132 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001133 Method, makeArrayRef(Args, NumArgs),
1134 RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001135 else
John McCallf89e55a2010-11-18 06:31:45 +00001136 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001137 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001138 Method, makeArrayRef(Args, NumArgs),
1139 RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001140 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +00001141}
1142
Douglas Gregor2725ca82010-04-21 19:57:20 +00001143// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +00001144// ArgExprs is optional - if it is present, the number of expressions
1145// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001146ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor77328d12010-09-15 23:19:31 +00001147 ParsedType Receiver,
1148 Selector Sel,
1149 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001150 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor77328d12010-09-15 23:19:31 +00001151 SourceLocation RBracLoc,
1152 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001153 TypeSourceInfo *ReceiverTypeInfo;
1154 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
1155 if (ReceiverType.isNull())
1156 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001157
Mike Stump1eb44332009-09-09 15:08:12 +00001158
Douglas Gregor2725ca82010-04-21 19:57:20 +00001159 if (!ReceiverTypeInfo)
1160 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
1161
1162 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +00001163 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001164 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001165}
1166
1167/// \brief Build an Objective-C instance message expression.
1168///
1169/// This routine takes care of both normal instance messages and
1170/// instance messages to the superclass instance.
1171///
1172/// \param Receiver The expression that computes the object that will
1173/// receive this message. This may be empty, in which case we are
1174/// sending to the superclass instance and \p SuperLoc must be a valid
1175/// source location.
1176///
1177/// \param ReceiverType The (static) type of the object receiving the
1178/// message. When a \p Receiver expression is provided, this is the
1179/// same type as that expression. For a superclass instance send, this
1180/// is a pointer to the type of the superclass.
1181///
1182/// \param SuperLoc The location of the "super" keyword in a
1183/// superclass instance message.
1184///
1185/// \param Sel The selector to which the message is being sent.
1186///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001187/// \param Method The method that this instance message is invoking, if
1188/// already known.
1189///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001190/// \param LBracLoc The location of the opening square bracket ']'.
1191///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001192/// \param RBrac The location of the closing square bracket ']'.
1193///
1194/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001195ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001196 QualType ReceiverType,
1197 SourceLocation SuperLoc,
1198 Selector Sel,
1199 ObjCMethodDecl *Method,
1200 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001201 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001202 SourceLocation RBracLoc,
1203 MultiExprArg ArgsIn) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00001204 // The location of the receiver.
1205 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
1206
1207 if (LBracLoc.isInvalid()) {
1208 Diag(Loc, diag::err_missing_open_square_message_send)
1209 << FixItHint::CreateInsertion(Loc, "[");
1210 LBracLoc = Loc;
1211 }
1212
Douglas Gregor2725ca82010-04-21 19:57:20 +00001213 // If we have a receiver expression, perform appropriate promotions
1214 // and determine receiver type.
Douglas Gregor2725ca82010-04-21 19:57:20 +00001215 if (Receiver) {
Douglas Gregor92e986e2010-04-22 16:44:27 +00001216 if (Receiver->isTypeDependent()) {
1217 // If the receiver is type-dependent, we can't type-check anything
1218 // at this point. Build a dependent expression.
1219 unsigned NumArgs = ArgsIn.size();
1220 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1221 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1222 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00001223 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001224 SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001225 makeArrayRef(Args, NumArgs),
1226 RBracLoc));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001227 }
1228
Douglas Gregor2725ca82010-04-21 19:57:20 +00001229 // If necessary, apply function/array conversion to the receiver.
1230 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00001231 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
1232 if (Result.isInvalid())
1233 return ExprError();
1234 Receiver = Result.take();
Douglas Gregor2725ca82010-04-21 19:57:20 +00001235 ReceiverType = Receiver->getType();
1236 }
1237
Douglas Gregorf49bb082010-04-22 17:01:48 +00001238 if (!Method) {
1239 // Handle messages to id.
Fariborz Jahanianba551982010-08-10 18:10:50 +00001240 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001241 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorf49bb082010-04-22 17:01:48 +00001242 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
1243 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001244 SourceRange(LBracLoc, RBracLoc),
1245 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001246 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +00001247 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001248 SourceRange(LBracLoc, RBracLoc),
1249 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001250 } else if (ReceiverType->isObjCClassType() ||
1251 ReceiverType->isObjCQualifiedClassType()) {
1252 // Handle messages to Class.
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001253 // We allow sending a message to a qualified Class ("Class<foo>"), which
1254 // is ok as long as one of the protocols implements the selector (if not, warn).
1255 if (const ObjCObjectPointerType *QClassTy
1256 = ReceiverType->getAsObjCQualifiedClassType()) {
1257 // Search protocols for class methods.
1258 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
1259 if (!Method) {
1260 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
1261 // warn if instance method found for a Class message.
1262 if (Method) {
1263 Diag(Loc, diag::warn_instance_method_on_class_found)
1264 << Method->getSelector() << Sel;
1265 Diag(Method->getLocation(), diag::note_method_declared_at);
1266 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +00001267 }
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001268 } else {
1269 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
1270 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
1271 // First check the public methods in the class interface.
1272 Method = ClassDecl->lookupClassMethod(Sel);
1273
1274 if (!Method)
1275 Method = LookupPrivateClassMethod(Sel, ClassDecl);
1276 }
1277 if (Method && DiagnoseUseOfDecl(Method, Loc))
1278 return ExprError();
1279 }
1280 if (!Method) {
1281 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregorc737acb2011-09-27 16:10:05 +00001282 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001283 Method = LookupFactoryMethodInGlobalPool(Sel,
1284 SourceRange(LBracLoc, RBracLoc),
1285 true);
1286 if (!Method) {
1287 // If no class (factory) method was found, check if an _instance_
1288 // method of the same name exists in the root class only.
1289 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001290 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001291 true);
1292 if (Method)
1293 if (const ObjCInterfaceDecl *ID =
1294 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
1295 if (ID->getSuperClass())
1296 Diag(Loc, diag::warn_root_inst_method_not_found)
1297 << Sel << SourceRange(LBracLoc, RBracLoc);
1298 }
1299 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001300 }
1301 }
1302 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001303 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001304 ObjCInterfaceDecl* ClassDecl = 0;
1305
1306 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
1307 // long as one of the protocols implements the selector (if not, warn).
1308 if (const ObjCObjectPointerType *QIdTy
1309 = ReceiverType->getAsObjCQualifiedIdType()) {
1310 // Search protocols for instance methods.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001311 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
1312 if (!Method)
1313 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001314 } else if (const ObjCObjectPointerType *OCIType
1315 = ReceiverType->getAsObjCInterfacePointerType()) {
1316 // We allow sending a message to a pointer to an interface (an object).
1317 ClassDecl = OCIType->getInterfaceDecl();
John McCallf85e1932011-06-15 23:02:42 +00001318
1319 if (ClassDecl->isForwardDecl() && getLangOptions().ObjCAutoRefCount) {
1320 Diag(Loc, diag::err_arc_receiver_forward_instance)
1321 << OCIType->getPointeeType()
1322 << (Receiver ? Receiver->getSourceRange() : SourceRange(SuperLoc));
1323 return ExprError();
1324 }
1325
Douglas Gregorf49bb082010-04-22 17:01:48 +00001326 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
1327 // faster than the following method (which can do *many* linear searches).
Sebastian Redldb9d2142010-08-02 23:18:59 +00001328 // The idea is to add class info to MethodPool.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001329 Method = ClassDecl->lookupInstanceMethod(Sel);
1330
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001331 if (!Method)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001332 // Search protocol qualifiers.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001333 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
1334
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +00001335 const ObjCInterfaceDecl *forwardClass = 0;
Douglas Gregorf49bb082010-04-22 17:01:48 +00001336 if (!Method) {
1337 // If we have implementations in scope, check "private" methods.
1338 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1339
John McCallf85e1932011-06-15 23:02:42 +00001340 if (!Method && getLangOptions().ObjCAutoRefCount) {
1341 Diag(Loc, diag::err_arc_may_not_respond)
1342 << OCIType->getPointeeType() << Sel;
1343 return ExprError();
1344 }
1345
Douglas Gregorc737acb2011-09-27 16:10:05 +00001346 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001347 // If we still haven't found a method, look in the global pool. This
1348 // behavior isn't very desirable, however we need it for GCC
1349 // compatibility. FIXME: should we deviate??
1350 if (OCIType->qual_empty()) {
1351 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001352 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +00001353 if (OCIType->getInterfaceDecl()->isForwardDecl())
1354 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001355 if (Method && !forwardClass)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001356 Diag(Loc, diag::warn_maynot_respond)
1357 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
1358 }
1359 }
1360 }
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001361 if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
Douglas Gregorf49bb082010-04-22 17:01:48 +00001362 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +00001363 } else if (!getLangOptions().ObjCAutoRefCount &&
1364 !Context.getObjCIdType().isNull() &&
Douglas Gregorf6094622010-07-23 15:58:24 +00001365 (ReceiverType->isPointerType() ||
1366 ReceiverType->isIntegerType())) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001367 // Implicitly convert integers and pointers to 'id' but emit a warning.
John McCallf85e1932011-06-15 23:02:42 +00001368 // But not in ARC.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001369 Diag(Loc, diag::warn_bad_receiver_type)
1370 << ReceiverType
1371 << Receiver->getSourceRange();
1372 if (ReceiverType->isPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00001373 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00001374 CK_CPointerToObjCPointerCast).take();
John McCall404cd162010-11-13 01:35:44 +00001375 else {
1376 // TODO: specialized warning on null receivers?
1377 bool IsNull = Receiver->isNullPointerConstant(Context,
1378 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00001379 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1380 IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
John McCall404cd162010-11-13 01:35:44 +00001381 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001382 ReceiverType = Receiver->getType();
John McCall0bcc9bc2011-09-09 06:11:02 +00001383 } else {
John Wiegley429bb272011-04-08 18:41:53 +00001384 ExprResult ReceiverRes;
1385 if (getLangOptions().CPlusPlus)
John McCall0bcc9bc2011-09-09 06:11:02 +00001386 ReceiverRes = PerformContextuallyConvertToObjCPointer(Receiver);
John Wiegley429bb272011-04-08 18:41:53 +00001387 if (ReceiverRes.isUsable()) {
1388 Receiver = ReceiverRes.take();
John Wiegley429bb272011-04-08 18:41:53 +00001389 return BuildInstanceMessage(Receiver,
1390 ReceiverType,
1391 SuperLoc,
1392 Sel,
1393 Method,
1394 LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001395 SelectorLocs,
John Wiegley429bb272011-04-08 18:41:53 +00001396 RBracLoc,
1397 move(ArgsIn));
1398 } else {
1399 // Reject other random receiver types (e.g. structs).
1400 Diag(Loc, diag::err_bad_receiver_type)
1401 << ReceiverType << Receiver->getSourceRange();
1402 return ExprError();
Fariborz Jahanian3ba60612010-05-13 17:19:25 +00001403 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001404 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001405 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00001406 }
Mike Stump1eb44332009-09-09 15:08:12 +00001407
Douglas Gregor2725ca82010-04-21 19:57:20 +00001408 // Check the message arguments.
1409 unsigned NumArgs = ArgsIn.size();
1410 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1411 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001412 ExprValueKind VK = VK_RValue;
Fariborz Jahanian26005032010-12-01 01:07:24 +00001413 bool ClassMessage = (ReceiverType->isObjCClassType() ||
1414 ReceiverType->isObjCQualifiedClassType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001415 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
1416 ClassMessage, SuperLoc.isValid(),
John McCallf89e55a2010-11-18 06:31:45 +00001417 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001418 return ExprError();
Fariborz Jahanianda59e092010-06-16 19:56:08 +00001419
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001420 if (Method && !Method->getResultType()->isVoidType() &&
1421 RequireCompleteType(LBracLoc, Method->getResultType(),
1422 diag::err_illegal_message_expr_incomplete_type))
1423 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001424
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001425 SourceLocation SelLoc = SelectorLocs.front();
1426
John McCallf85e1932011-06-15 23:02:42 +00001427 // In ARC, forbid the user from sending messages to
1428 // retain/release/autorelease/dealloc/retainCount explicitly.
1429 if (getLangOptions().ObjCAutoRefCount) {
1430 ObjCMethodFamily family =
1431 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
1432 switch (family) {
1433 case OMF_init:
1434 if (Method)
1435 checkInitMethod(Method, ReceiverType);
1436
1437 case OMF_None:
1438 case OMF_alloc:
1439 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +00001440 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +00001441 case OMF_mutableCopy:
1442 case OMF_new:
1443 case OMF_self:
1444 break;
1445
1446 case OMF_dealloc:
1447 case OMF_retain:
1448 case OMF_release:
1449 case OMF_autorelease:
1450 case OMF_retainCount:
1451 Diag(Loc, diag::err_arc_illegal_explicit_message)
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001452 << Sel << SelLoc;
John McCallf85e1932011-06-15 23:02:42 +00001453 break;
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001454
1455 case OMF_performSelector:
1456 if (Method && NumArgs >= 1) {
1457 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
1458 Selector ArgSel = SelExp->getSelector();
1459 ObjCMethodDecl *SelMethod =
1460 LookupInstanceMethodInGlobalPool(ArgSel,
1461 SelExp->getSourceRange());
1462 if (!SelMethod)
1463 SelMethod =
1464 LookupFactoryMethodInGlobalPool(ArgSel,
1465 SelExp->getSourceRange());
1466 if (SelMethod) {
1467 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
1468 switch (SelFamily) {
1469 case OMF_alloc:
1470 case OMF_copy:
1471 case OMF_mutableCopy:
1472 case OMF_new:
1473 case OMF_self:
1474 case OMF_init:
1475 // Issue error, unless ns_returns_not_retained.
1476 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
1477 // selector names a +1 method
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001478 Diag(SelLoc,
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001479 diag::err_arc_perform_selector_retains);
1480 Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1481 }
1482 break;
1483 default:
1484 // +0 call. OK. unless ns_returns_retained.
1485 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
1486 // selector names a +1 method
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001487 Diag(SelLoc,
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001488 diag::err_arc_perform_selector_retains);
1489 Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1490 }
1491 break;
1492 }
1493 }
1494 } else {
1495 // error (may leak).
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001496 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001497 Diag(Args[0]->getExprLoc(), diag::note_used_here);
1498 }
1499 }
1500 break;
John McCallf85e1932011-06-15 23:02:42 +00001501 }
1502 }
1503
Douglas Gregor2725ca82010-04-21 19:57:20 +00001504 // Construct the appropriate ObjCMessageExpr instance.
John McCallf85e1932011-06-15 23:02:42 +00001505 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001506 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001507 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001508 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001509 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001510 makeArrayRef(Args, NumArgs), RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001511 else
John McCallf89e55a2010-11-18 06:31:45 +00001512 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001513 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001514 makeArrayRef(Args, NumArgs), RBracLoc);
John McCallf85e1932011-06-15 23:02:42 +00001515
1516 if (getLangOptions().ObjCAutoRefCount) {
1517 // In ARC, annotate delegate init calls.
1518 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregorc737acb2011-09-27 16:10:05 +00001519 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCallf85e1932011-06-15 23:02:42 +00001520 // Only consider init calls *directly* in init implementations,
1521 // not within blocks.
1522 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
1523 if (method && method->getMethodFamily() == OMF_init) {
1524 // The implicit assignment to self means we also don't want to
1525 // consume the result.
1526 Result->setDelegateInitCall(true);
1527 return Owned(Result);
1528 }
1529 }
1530
1531 // In ARC, check for message sends which are likely to introduce
1532 // retain cycles.
1533 checkRetainCycles(Result);
1534 }
1535
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001536 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001537}
1538
1539// ActOnInstanceMessage - used for both unary and keyword messages.
1540// ArgExprs is optional - if it is present, the number of expressions
1541// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001542ExprResult Sema::ActOnInstanceMessage(Scope *S,
1543 Expr *Receiver,
1544 Selector Sel,
1545 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001546 ArrayRef<SourceLocation> SelectorLocs,
John McCall60d7b3a2010-08-24 06:29:42 +00001547 SourceLocation RBracLoc,
1548 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001549 if (!Receiver)
1550 return ExprError();
1551
John McCall9ae2f072010-08-23 23:25:46 +00001552 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00001553 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001554 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00001555}
Chris Lattnereca7be62008-04-07 05:30:13 +00001556
John McCallf85e1932011-06-15 23:02:42 +00001557enum ARCConversionTypeClass {
John McCall2cf031d2011-10-01 01:01:08 +00001558 /// int, void, struct A
John McCallf85e1932011-06-15 23:02:42 +00001559 ACTC_none,
John McCall2cf031d2011-10-01 01:01:08 +00001560
1561 /// id, void (^)()
John McCallf85e1932011-06-15 23:02:42 +00001562 ACTC_retainable,
John McCall2cf031d2011-10-01 01:01:08 +00001563
1564 /// id*, id***, void (^*)(),
1565 ACTC_indirectRetainable,
1566
1567 /// void* might be a normal C type, or it might a CF type.
1568 ACTC_voidPtr,
1569
1570 /// struct A*
1571 ACTC_coreFoundation
John McCallf85e1932011-06-15 23:02:42 +00001572};
John McCall2cf031d2011-10-01 01:01:08 +00001573static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
1574 return (ACTC == ACTC_retainable ||
1575 ACTC == ACTC_coreFoundation ||
1576 ACTC == ACTC_voidPtr);
1577}
1578static bool isAnyCLike(ARCConversionTypeClass ACTC) {
1579 return ACTC == ACTC_none ||
1580 ACTC == ACTC_voidPtr ||
1581 ACTC == ACTC_coreFoundation;
1582}
1583
John McCallf85e1932011-06-15 23:02:42 +00001584static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCall2cf031d2011-10-01 01:01:08 +00001585 bool isIndirect = false;
John McCallf85e1932011-06-15 23:02:42 +00001586
1587 // Ignore an outermost reference type.
John McCall2cf031d2011-10-01 01:01:08 +00001588 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCallf85e1932011-06-15 23:02:42 +00001589 type = ref->getPointeeType();
John McCall2cf031d2011-10-01 01:01:08 +00001590 isIndirect = true;
1591 }
John McCallf85e1932011-06-15 23:02:42 +00001592
1593 // Drill through pointers and arrays recursively.
1594 while (true) {
1595 if (const PointerType *ptr = type->getAs<PointerType>()) {
1596 type = ptr->getPointeeType();
John McCall2cf031d2011-10-01 01:01:08 +00001597
1598 // The first level of pointer may be the innermost pointer on a CF type.
1599 if (!isIndirect) {
1600 if (type->isVoidType()) return ACTC_voidPtr;
1601 if (type->isRecordType()) return ACTC_coreFoundation;
1602 }
John McCallf85e1932011-06-15 23:02:42 +00001603 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
1604 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
1605 } else {
1606 break;
1607 }
John McCall2cf031d2011-10-01 01:01:08 +00001608 isIndirect = true;
John McCallf85e1932011-06-15 23:02:42 +00001609 }
1610
John McCall2cf031d2011-10-01 01:01:08 +00001611 if (isIndirect) {
1612 if (type->isObjCARCBridgableType())
1613 return ACTC_indirectRetainable;
1614 return ACTC_none;
1615 }
1616
1617 if (type->isObjCARCBridgableType())
1618 return ACTC_retainable;
1619
1620 return ACTC_none;
John McCallf85e1932011-06-15 23:02:42 +00001621}
1622
1623namespace {
John McCall2cf031d2011-10-01 01:01:08 +00001624 /// A result from the cast checker.
1625 enum ACCResult {
1626 /// Cannot be casted.
1627 ACC_invalid,
1628
1629 /// Can be safely retained or not retained.
1630 ACC_bottom,
1631
1632 /// Can be casted at +0.
1633 ACC_plusZero,
1634
1635 /// Can be casted at +1.
1636 ACC_plusOne
1637 };
1638 ACCResult merge(ACCResult left, ACCResult right) {
1639 if (left == right) return left;
1640 if (left == ACC_bottom) return right;
1641 if (right == ACC_bottom) return left;
1642 return ACC_invalid;
1643 }
1644
1645 /// A checker which white-lists certain expressions whose conversion
1646 /// to or from retainable type would otherwise be forbidden in ARC.
1647 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
1648 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
1649
John McCallf85e1932011-06-15 23:02:42 +00001650 ASTContext &Context;
John McCall2cf031d2011-10-01 01:01:08 +00001651 ARCConversionTypeClass SourceClass;
1652 ARCConversionTypeClass TargetClass;
1653
1654 static bool isCFType(QualType type) {
1655 // Someday this can use ns_bridged. For now, it has to do this.
1656 return type->isCARCBridgableType();
John McCallf85e1932011-06-15 23:02:42 +00001657 }
John McCall2cf031d2011-10-01 01:01:08 +00001658
1659 public:
1660 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
1661 ARCConversionTypeClass target)
1662 : Context(Context), SourceClass(source), TargetClass(target) {}
1663
1664 using super::Visit;
1665 ACCResult Visit(Expr *e) {
1666 return super::Visit(e->IgnoreParens());
1667 }
1668
1669 ACCResult VisitStmt(Stmt *s) {
1670 return ACC_invalid;
1671 }
1672
1673 /// Null pointer constants can be casted however you please.
1674 ACCResult VisitExpr(Expr *e) {
1675 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1676 return ACC_bottom;
1677 return ACC_invalid;
1678 }
1679
1680 /// Objective-C string literals can be safely casted.
1681 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
1682 // If we're casting to any retainable type, go ahead. Global
1683 // strings are immune to retains, so this is bottom.
1684 if (isAnyRetainable(TargetClass)) return ACC_bottom;
1685
1686 return ACC_invalid;
John McCallf85e1932011-06-15 23:02:42 +00001687 }
1688
John McCall2cf031d2011-10-01 01:01:08 +00001689 /// Look through certain implicit and explicit casts.
1690 ACCResult VisitCastExpr(CastExpr *e) {
John McCallf85e1932011-06-15 23:02:42 +00001691 switch (e->getCastKind()) {
1692 case CK_NullToPointer:
John McCall2cf031d2011-10-01 01:01:08 +00001693 return ACC_bottom;
1694
John McCallf85e1932011-06-15 23:02:42 +00001695 case CK_NoOp:
1696 case CK_LValueToRValue:
1697 case CK_BitCast:
John McCall2cf031d2011-10-01 01:01:08 +00001698 case CK_GetObjCProperty:
John McCall1d9b3b22011-09-09 05:25:32 +00001699 case CK_CPointerToObjCPointerCast:
1700 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00001701 case CK_AnyPointerToBlockPointerCast:
1702 return Visit(e->getSubExpr());
John McCall2cf031d2011-10-01 01:01:08 +00001703
John McCallf85e1932011-06-15 23:02:42 +00001704 default:
John McCall2cf031d2011-10-01 01:01:08 +00001705 return ACC_invalid;
John McCallf85e1932011-06-15 23:02:42 +00001706 }
1707 }
John McCall2cf031d2011-10-01 01:01:08 +00001708
1709 /// Look through unary extension.
1710 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCallf85e1932011-06-15 23:02:42 +00001711 return Visit(e->getSubExpr());
1712 }
John McCall2cf031d2011-10-01 01:01:08 +00001713
1714 /// Ignore the LHS of a comma operator.
1715 ACCResult VisitBinComma(BinaryOperator *e) {
John McCallf85e1932011-06-15 23:02:42 +00001716 return Visit(e->getRHS());
1717 }
John McCall2cf031d2011-10-01 01:01:08 +00001718
1719 /// Conditional operators are okay if both sides are okay.
1720 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
1721 ACCResult left = Visit(e->getTrueExpr());
1722 if (left == ACC_invalid) return ACC_invalid;
1723 return merge(left, Visit(e->getFalseExpr()));
John McCallf85e1932011-06-15 23:02:42 +00001724 }
John McCall2cf031d2011-10-01 01:01:08 +00001725
1726 /// Statement expressions are okay if their result expression is okay.
1727 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCallf85e1932011-06-15 23:02:42 +00001728 return Visit(e->getSubStmt()->body_back());
1729 }
John McCallf85e1932011-06-15 23:02:42 +00001730
John McCall2cf031d2011-10-01 01:01:08 +00001731 /// Some declaration references are okay.
1732 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
1733 // References to global constants from system headers are okay.
1734 // These are things like 'kCFStringTransformToLatin'. They are
1735 // can also be assumed to be immune to retains.
1736 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
1737 if (isAnyRetainable(TargetClass) &&
1738 isAnyRetainable(SourceClass) &&
1739 var &&
1740 var->getStorageClass() == SC_Extern &&
1741 var->getType().isConstQualified() &&
1742 Context.getSourceManager().isInSystemHeader(var->getLocation())) {
1743 return ACC_bottom;
1744 }
1745
1746 // Nothing else.
1747 return ACC_invalid;
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001748 }
John McCall2cf031d2011-10-01 01:01:08 +00001749
1750 /// Some calls are okay.
1751 ACCResult VisitCallExpr(CallExpr *e) {
1752 if (FunctionDecl *fn = e->getDirectCallee())
1753 if (ACCResult result = checkCallToFunction(fn))
1754 return result;
1755
1756 return super::VisitCallExpr(e);
1757 }
1758
1759 ACCResult checkCallToFunction(FunctionDecl *fn) {
1760 // Require a CF*Ref return type.
1761 if (!isCFType(fn->getResultType()))
1762 return ACC_invalid;
1763
1764 if (!isAnyRetainable(TargetClass))
1765 return ACC_invalid;
1766
1767 // Honor an explicit 'not retained' attribute.
1768 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
1769 return ACC_plusZero;
1770
1771 // Honor an explicit 'retained' attribute, except that for
1772 // now we're not going to permit implicit handling of +1 results,
1773 // because it's a bit frightening.
1774 if (fn->hasAttr<CFReturnsRetainedAttr>())
1775 return ACC_invalid; // ACC_plusOne if we start accepting this
1776
1777 // Recognize this specific builtin function, which is used by CFSTR.
1778 unsigned builtinID = fn->getBuiltinID();
1779 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
1780 return ACC_bottom;
1781
1782 // Otherwise, don't do anything implicit with an unaudited function.
1783 if (!fn->hasAttr<CFAuditedTransferAttr>())
1784 return ACC_invalid;
1785
1786 // Otherwise, it's +0 unless it follows the create convention.
1787 if (ento::coreFoundation::followsCreateRule(fn))
1788 return ACC_invalid; // ACC_plusOne if we start accepting this
1789
1790 return ACC_plusZero;
1791 }
1792
1793 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
1794 return checkCallToMethod(e->getMethodDecl());
1795 }
1796
1797 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
1798 ObjCMethodDecl *method;
1799 if (e->isExplicitProperty())
1800 method = e->getExplicitProperty()->getGetterMethodDecl();
1801 else
1802 method = e->getImplicitPropertyGetter();
1803 return checkCallToMethod(method);
1804 }
1805
1806 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
1807 if (!method) return ACC_invalid;
1808
1809 // Check for message sends to functions returning CF types. We
1810 // just obey the Cocoa conventions with these, even though the
1811 // return type is CF.
1812 if (!isAnyRetainable(TargetClass) || !isCFType(method->getResultType()))
1813 return ACC_invalid;
1814
1815 // If the method is explicitly marked not-retained, it's +0.
1816 if (method->hasAttr<CFReturnsNotRetainedAttr>())
1817 return ACC_plusZero;
1818
1819 // If the method is explicitly marked as returning retained, or its
1820 // selector follows a +1 Cocoa convention, treat it as +1.
1821 if (method->hasAttr<CFReturnsRetainedAttr>())
1822 return ACC_plusOne;
1823
1824 switch (method->getSelector().getMethodFamily()) {
1825 case OMF_alloc:
1826 case OMF_copy:
1827 case OMF_mutableCopy:
1828 case OMF_new:
1829 return ACC_plusOne;
1830
1831 default:
1832 // Otherwise, treat it as +0.
1833 return ACC_plusZero;
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001834 }
1835 }
John McCall2cf031d2011-10-01 01:01:08 +00001836 };
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001837}
1838
John McCallf85e1932011-06-15 23:02:42 +00001839void
1840Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001841 Expr *&castExpr, CheckedConversionKind CCK) {
John McCallf85e1932011-06-15 23:02:42 +00001842 QualType castExprType = castExpr->getType();
John McCall2cf031d2011-10-01 01:01:08 +00001843
1844 // For the purposes of the classification, we assume reference types
1845 // will bind to temporaries.
1846 QualType effCastType = castType;
1847 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
1848 effCastType = ref->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00001849
1850 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
John McCall2cf031d2011-10-01 01:01:08 +00001851 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
John McCallf85e1932011-06-15 23:02:42 +00001852 if (exprACTC == castACTC) return;
John McCall2cf031d2011-10-01 01:01:08 +00001853 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return;
1854
1855 // Allow all of these types to be cast to integer types (but not
1856 // vice-versa).
1857 if (castACTC == ACTC_none && castType->isIntegralType(Context))
1858 return;
John McCallf85e1932011-06-15 23:02:42 +00001859
1860 // Allow casts between pointers to lifetime types (e.g., __strong id*)
1861 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
1862 // must be explicit.
John McCall2cf031d2011-10-01 01:01:08 +00001863 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
1864 return;
1865 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
1866 CCK != CCK_ImplicitConversion)
1867 return;
1868
1869 switch (ARCCastChecker(Context, exprACTC, castACTC).Visit(castExpr)) {
1870 // For invalid casts, fall through.
1871 case ACC_invalid:
1872 break;
1873
1874 // Do nothing for both bottom and +0.
1875 case ACC_bottom:
1876 case ACC_plusZero:
1877 return;
1878
1879 // If the result is +1, consume it here.
1880 case ACC_plusOne:
1881 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
1882 CK_ARCConsumeObject, castExpr,
1883 0, VK_RValue);
1884 ExprNeedsCleanups = true;
1885 return;
John McCallf85e1932011-06-15 23:02:42 +00001886 }
1887
John McCallf85e1932011-06-15 23:02:42 +00001888 SourceLocation loc =
John McCall2cf031d2011-10-01 01:01:08 +00001889 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCallf85e1932011-06-15 23:02:42 +00001890
1891 if (makeUnavailableInSystemHeader(loc,
John McCall2cf031d2011-10-01 01:01:08 +00001892 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCallf85e1932011-06-15 23:02:42 +00001893 return;
1894
John McCall71c482c2011-06-17 06:50:50 +00001895 unsigned srcKind = 0;
John McCallf85e1932011-06-15 23:02:42 +00001896 switch (exprACTC) {
John McCall2cf031d2011-10-01 01:01:08 +00001897 case ACTC_none:
1898 case ACTC_coreFoundation:
1899 case ACTC_voidPtr:
1900 srcKind = (castExprType->isPointerType() ? 1 : 0);
1901 break;
1902 case ACTC_retainable:
1903 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
1904 break;
1905 case ACTC_indirectRetainable:
1906 srcKind = 4;
1907 break;
John McCallf85e1932011-06-15 23:02:42 +00001908 }
1909
1910 if (CCK == CCK_CStyleCast) {
1911 // Check whether this could be fixed with a bridge cast.
1912 SourceLocation AfterLParen = PP.getLocForEndOfToken(castRange.getBegin());
1913 SourceLocation NoteLoc = AfterLParen.isValid()? AfterLParen : loc;
1914
John McCall2cf031d2011-10-01 01:01:08 +00001915 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
John McCallf85e1932011-06-15 23:02:42 +00001916 Diag(loc, diag::err_arc_cast_requires_bridge)
1917 << 2
1918 << castExprType
1919 << (castType->isBlockPointerType()? 1 : 0)
1920 << castType
1921 << castRange
1922 << castExpr->getSourceRange();
1923 Diag(NoteLoc, diag::note_arc_bridge)
1924 << FixItHint::CreateInsertion(AfterLParen, "__bridge ");
1925 Diag(NoteLoc, diag::note_arc_bridge_transfer)
1926 << castExprType
1927 << FixItHint::CreateInsertion(AfterLParen, "__bridge_transfer ");
1928
1929 return;
1930 }
1931
John McCall2cf031d2011-10-01 01:01:08 +00001932 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
John McCallf85e1932011-06-15 23:02:42 +00001933 Diag(loc, diag::err_arc_cast_requires_bridge)
1934 << (castExprType->isBlockPointerType()? 1 : 0)
1935 << castExprType
1936 << 2
1937 << castType
1938 << castRange
1939 << castExpr->getSourceRange();
1940
1941 Diag(NoteLoc, diag::note_arc_bridge)
1942 << FixItHint::CreateInsertion(AfterLParen, "__bridge ");
1943 Diag(NoteLoc, diag::note_arc_bridge_retained)
1944 << castType
1945 << FixItHint::CreateInsertion(AfterLParen, "__bridge_retained ");
1946 return;
1947 }
1948 }
1949
1950 Diag(loc, diag::err_arc_mismatched_cast)
1951 << (CCK != CCK_ImplicitConversion) << srcKind << castExprType << castType
1952 << castRange << castExpr->getSourceRange();
1953}
1954
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00001955bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
1956 QualType exprType) {
1957 QualType canCastType =
1958 Context.getCanonicalType(castType).getUnqualifiedType();
1959 QualType canExprType =
1960 Context.getCanonicalType(exprType).getUnqualifiedType();
1961 if (isa<ObjCObjectPointerType>(canCastType) &&
1962 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
1963 canExprType->isObjCObjectPointerType()) {
1964 if (const ObjCObjectPointerType *ObjT =
1965 canExprType->getAs<ObjCObjectPointerType>())
1966 if (ObjT->getInterfaceDecl()->isArcWeakrefUnavailable())
1967 return false;
1968 }
1969 return true;
1970}
1971
John McCall7e5e5f42011-07-07 06:58:02 +00001972/// Look for an ObjCReclaimReturnedObject cast and destroy it.
1973static Expr *maybeUndoReclaimObject(Expr *e) {
1974 // For now, we just undo operands that are *immediately* reclaim
1975 // expressions, which prevents the vast majority of potential
1976 // problems here. To catch them all, we'd need to rebuild arbitrary
1977 // value-propagating subexpressions --- we can't reliably rebuild
1978 // in-place because of expression sharing.
1979 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall33e56f32011-09-10 06:18:15 +00001980 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall7e5e5f42011-07-07 06:58:02 +00001981 return ice->getSubExpr();
1982
1983 return e;
1984}
1985
John McCallf85e1932011-06-15 23:02:42 +00001986ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
1987 ObjCBridgeCastKind Kind,
1988 SourceLocation BridgeKeywordLoc,
1989 TypeSourceInfo *TSInfo,
1990 Expr *SubExpr) {
John McCall4906cf92011-08-26 00:48:42 +00001991 ExprResult SubResult = UsualUnaryConversions(SubExpr);
1992 if (SubResult.isInvalid()) return ExprError();
1993 SubExpr = SubResult.take();
1994
John McCallf85e1932011-06-15 23:02:42 +00001995 QualType T = TSInfo->getType();
1996 QualType FromType = SubExpr->getType();
1997
John McCall1d9b3b22011-09-09 05:25:32 +00001998 CastKind CK;
1999
John McCallf85e1932011-06-15 23:02:42 +00002000 bool MustConsume = false;
2001 if (T->isDependentType() || SubExpr->isTypeDependent()) {
2002 // Okay: we'll build a dependent expression type.
John McCall1d9b3b22011-09-09 05:25:32 +00002003 CK = CK_Dependent;
John McCallf85e1932011-06-15 23:02:42 +00002004 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
2005 // Casting CF -> id
John McCall1d9b3b22011-09-09 05:25:32 +00002006 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
2007 : CK_CPointerToObjCPointerCast);
John McCallf85e1932011-06-15 23:02:42 +00002008 switch (Kind) {
2009 case OBC_Bridge:
2010 break;
2011
2012 case OBC_BridgeRetained:
2013 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
2014 << 2
2015 << FromType
2016 << (T->isBlockPointerType()? 1 : 0)
2017 << T
2018 << SubExpr->getSourceRange()
2019 << Kind;
2020 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
2021 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
2022 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
2023 << FromType
2024 << FixItHint::CreateReplacement(BridgeKeywordLoc,
2025 "__bridge_transfer ");
2026
2027 Kind = OBC_Bridge;
2028 break;
2029
2030 case OBC_BridgeTransfer:
2031 // We must consume the Objective-C object produced by the cast.
2032 MustConsume = true;
2033 break;
2034 }
2035 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
2036 // Okay: id -> CF
John McCall1d9b3b22011-09-09 05:25:32 +00002037 CK = CK_BitCast;
John McCallf85e1932011-06-15 23:02:42 +00002038 switch (Kind) {
2039 case OBC_Bridge:
John McCall7e5e5f42011-07-07 06:58:02 +00002040 // Reclaiming a value that's going to be __bridge-casted to CF
2041 // is very dangerous, so we don't do it.
2042 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCallf85e1932011-06-15 23:02:42 +00002043 break;
2044
2045 case OBC_BridgeRetained:
2046 // Produce the object before casting it.
2047 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall33e56f32011-09-10 06:18:15 +00002048 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00002049 SubExpr, 0, VK_RValue);
2050 break;
2051
2052 case OBC_BridgeTransfer:
2053 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
2054 << (FromType->isBlockPointerType()? 1 : 0)
2055 << FromType
2056 << 2
2057 << T
2058 << SubExpr->getSourceRange()
2059 << Kind;
2060
2061 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
2062 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
2063 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
2064 << T
2065 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge_retained ");
2066
2067 Kind = OBC_Bridge;
2068 break;
2069 }
2070 } else {
2071 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
2072 << FromType << T << Kind
2073 << SubExpr->getSourceRange()
2074 << TSInfo->getTypeLoc().getSourceRange();
2075 return ExprError();
2076 }
2077
John McCall1d9b3b22011-09-09 05:25:32 +00002078 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCallf85e1932011-06-15 23:02:42 +00002079 BridgeKeywordLoc,
2080 TSInfo, SubExpr);
2081
2082 if (MustConsume) {
2083 ExprNeedsCleanups = true;
John McCall33e56f32011-09-10 06:18:15 +00002084 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
John McCallf85e1932011-06-15 23:02:42 +00002085 0, VK_RValue);
2086 }
2087
2088 return Result;
2089}
2090
2091ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
2092 SourceLocation LParenLoc,
2093 ObjCBridgeCastKind Kind,
2094 SourceLocation BridgeKeywordLoc,
2095 ParsedType Type,
2096 SourceLocation RParenLoc,
2097 Expr *SubExpr) {
2098 TypeSourceInfo *TSInfo = 0;
2099 QualType T = GetTypeFromParser(Type, &TSInfo);
2100 if (!TSInfo)
2101 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
2102 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
2103 SubExpr);
2104}