blob: b4d3d4de3634b86616893aca8e41d4f3ddc770a8 [file] [log] [blame]
Chris Lattnera3fc41d2008-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 McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Chris Lattnera3fc41d2008-01-04 22:32:30 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclObjC.h"
Steve Naroff021ca182008-05-29 21:12:08 +000017#include "clang/AST/ExprObjC.h"
John McCall31168b02011-06-15 23:02:42 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor0c78ad92010-04-21 19:57:20 +000019#include "clang/AST/TypeLoc.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
21#include "clang/Edit/Commit.h"
22#include "clang/Edit/Rewriters.h"
Steve Naroff9527bbf2009-03-09 21:12:44 +000023#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Sema/Initialization.h"
25#include "clang/Sema/Lookup.h"
26#include "clang/Sema/Scope.h"
27#include "clang/Sema/ScopeInfo.h"
28#include "llvm/ADT/SmallString.h"
Steve Naroff9527bbf2009-03-09 21:12:44 +000029
Chris Lattnera3fc41d2008-01-04 22:32:30 +000030using namespace clang;
John McCall5f2d5562011-02-03 09:00:02 +000031using namespace sema;
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +000032using llvm::makeArrayRef;
Chris Lattnera3fc41d2008-01-04 22:32:30 +000033
John McCallfaf5fb42010-08-26 23:41:50 +000034ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
35 Expr **strings,
36 unsigned NumStrings) {
Chris Lattner163ffd22009-02-18 06:48:40 +000037 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
38
Chris Lattnerd7670d92009-02-18 06:13:04 +000039 // Most ObjC strings are formed out of a single piece. However, we *can*
40 // have strings formed out of multiple @ strings with multiple pptokens in
41 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
42 // StringLiteral for ObjCStringLiteral to hold onto.
Chris Lattner163ffd22009-02-18 06:48:40 +000043 StringLiteral *S = Strings[0];
Mike Stump11289f42009-09-09 15:08:12 +000044
Chris Lattnerd7670d92009-02-18 06:13:04 +000045 // If we have a multi-part string, merge it all together.
46 if (NumStrings != 1) {
Chris Lattnera3fc41d2008-01-04 22:32:30 +000047 // Concatenate objc strings.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000048 SmallString<128> StrBuf;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000049 SmallVector<SourceLocation, 8> StrLocs;
Mike Stump11289f42009-09-09 15:08:12 +000050
Chris Lattner630970d2009-02-18 05:49:11 +000051 for (unsigned i = 0; i != NumStrings; ++i) {
Chris Lattner163ffd22009-02-18 06:48:40 +000052 S = Strings[i];
Mike Stump11289f42009-09-09 15:08:12 +000053
Douglas Gregorfb65e592011-07-27 05:40:30 +000054 // ObjC strings can't be wide or UTF.
55 if (!S->isAscii()) {
Chris Lattnerd7670d92009-02-18 06:13:04 +000056 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
57 << S->getSourceRange();
58 return true;
59 }
Mike Stump11289f42009-09-09 15:08:12 +000060
Benjamin Kramer35b077e2010-08-17 12:54:38 +000061 // Append the string.
62 StrBuf += S->getString();
Mike Stump11289f42009-09-09 15:08:12 +000063
Chris Lattner163ffd22009-02-18 06:48:40 +000064 // Get the locations of the string tokens.
65 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Chris Lattnera3fc41d2008-01-04 22:32:30 +000066 }
Mike Stump11289f42009-09-09 15:08:12 +000067
Chris Lattner163ffd22009-02-18 06:48:40 +000068 // Create the aggregate string with the appropriate content and location
69 // information.
Benjamin Kramercdac7612014-02-25 12:26:20 +000070 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
71 assert(CAT && "String literal not of constant array type!");
72 QualType StrTy = Context.getConstantArrayType(
73 CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1),
74 CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers());
75 S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii,
76 /*Pascal=*/false, StrTy, &StrLocs[0],
77 StrLocs.size());
Chris Lattnera3fc41d2008-01-04 22:32:30 +000078 }
Ted Kremeneke65b0862012-03-06 20:05:56 +000079
80 return BuildObjCStringLiteral(AtLocs[0], S);
81}
Mike Stump11289f42009-09-09 15:08:12 +000082
Ted Kremeneke65b0862012-03-06 20:05:56 +000083ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
Chris Lattner6436fb62009-02-18 06:01:06 +000084 // Verify that this composite string is acceptable for ObjC strings.
85 if (CheckObjCString(S))
Chris Lattnera3fc41d2008-01-04 22:32:30 +000086 return true;
Chris Lattnerfffd6a72009-02-18 06:06:56 +000087
88 // Initialize the constant string interface lazily. This assumes
Steve Naroff54e59452009-04-07 14:18:33 +000089 // the NSString interface is seen in this translation unit. Note: We
90 // don't use NSConstantString, since the runtime team considers this
91 // interface private (even though it appears in the header files).
Chris Lattnerfffd6a72009-02-18 06:06:56 +000092 QualType Ty = Context.getObjCConstantStringInterface();
93 if (!Ty.isNull()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +000094 Ty = Context.getObjCObjectPointerType(Ty);
David Blaikiebbafb8a2012-03-11 07:00:24 +000095 } else if (getLangOpts().NoConstantCFStrings) {
Craig Topperc3ec1492014-05-26 06:22:03 +000096 IdentifierInfo *NSIdent=nullptr;
David Blaikiebbafb8a2012-03-11 07:00:24 +000097 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Fariborz Jahanian50c925f2010-10-19 17:19:29 +000098
99 if (StringClass.empty())
100 NSIdent = &Context.Idents.get("NSConstantString");
101 else
102 NSIdent = &Context.Idents.get(StringClass);
103
Ted Kremeneke65b0862012-03-06 20:05:56 +0000104 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Fariborz Jahanian07317632010-04-23 23:19:04 +0000105 LookupOrdinaryName);
106 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
107 Context.setObjCConstantStringInterface(StrIF);
108 Ty = Context.getObjCConstantStringInterface();
109 Ty = Context.getObjCObjectPointerType(Ty);
110 } else {
111 // If there is no NSConstantString interface defined then treat this
112 // as error and recover from it.
113 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
114 << S->getSourceRange();
115 Ty = Context.getObjCIdType();
116 }
Chris Lattner091f6982008-06-21 21:44:18 +0000117 } else {
Patrick Beard0caa3942012-04-19 00:25:12 +0000118 IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000119 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000120 LookupOrdinaryName);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000121 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
122 Context.setObjCConstantStringInterface(StrIF);
123 Ty = Context.getObjCConstantStringInterface();
Steve Naroff7cae42b2009-07-10 23:34:53 +0000124 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000125 } else {
Fariborz Jahanian86f82662012-02-23 22:51:36 +0000126 // If there is no NSString interface defined, implicitly declare
127 // a @class NSString; and use that instead. This is to make sure
128 // type of an NSString literal is represented correctly, instead of
129 // being an 'id' type.
130 Ty = Context.getObjCNSStringType();
131 if (Ty.isNull()) {
132 ObjCInterfaceDecl *NSStringIDecl =
133 ObjCInterfaceDecl::Create (Context,
134 Context.getTranslationUnitDecl(),
135 SourceLocation(), NSIdent,
Craig Topperc3ec1492014-05-26 06:22:03 +0000136 nullptr, SourceLocation());
Fariborz Jahanian86f82662012-02-23 22:51:36 +0000137 Ty = Context.getObjCInterfaceType(NSStringIDecl);
138 Context.setObjCNSStringType(Ty);
139 }
140 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000141 }
Chris Lattner091f6982008-06-21 21:44:18 +0000142 }
Mike Stump11289f42009-09-09 15:08:12 +0000143
Ted Kremeneke65b0862012-03-06 20:05:56 +0000144 return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
145}
146
Jordy Rose08e500c2012-05-12 17:32:44 +0000147/// \brief Emits an error if the given method does not exist, or if the return
148/// type is not an Objective-C object.
149static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
150 const ObjCInterfaceDecl *Class,
151 Selector Sel, const ObjCMethodDecl *Method) {
152 if (!Method) {
153 // FIXME: Is there a better way to avoid quotes than using getName()?
154 S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
155 return false;
156 }
157
158 // Make sure the return type is reasonable.
Alp Toker314cc812014-01-25 16:55:45 +0000159 QualType ReturnType = Method->getReturnType();
Jordy Rose08e500c2012-05-12 17:32:44 +0000160 if (!ReturnType->isObjCObjectPointerType()) {
161 S.Diag(Loc, diag::err_objc_literal_method_sig)
162 << Sel;
163 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
164 << ReturnType;
165 return false;
166 }
167
168 return true;
169}
170
Ted Kremeneke65b0862012-03-06 20:05:56 +0000171/// \brief Retrieve the NSNumber factory method that should be used to create
172/// an Objective-C literal for the given type.
173static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
Patrick Beard0caa3942012-04-19 00:25:12 +0000174 QualType NumberType,
175 bool isLiteral = false,
176 SourceRange R = SourceRange()) {
David Blaikie05785d12013-02-20 22:23:23 +0000177 Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
178 S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
179
Ted Kremeneke65b0862012-03-06 20:05:56 +0000180 if (!Kind) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000181 if (isLiteral) {
182 S.Diag(Loc, diag::err_invalid_nsnumber_type)
183 << NumberType << R;
184 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000185 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000186 }
Patrick Beard0caa3942012-04-19 00:25:12 +0000187
Ted Kremeneke65b0862012-03-06 20:05:56 +0000188 // If we already looked up this method, we're done.
189 if (S.NSNumberLiteralMethods[*Kind])
190 return S.NSNumberLiteralMethods[*Kind];
191
192 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
193 /*Instance=*/false);
194
Patrick Beard0caa3942012-04-19 00:25:12 +0000195 ASTContext &CX = S.Context;
196
197 // Look up the NSNumber class, if we haven't done so already. It's cached
198 // in the Sema instance.
199 if (!S.NSNumberDecl) {
Jordy Roseaca01f92012-05-12 17:32:52 +0000200 IdentifierInfo *NSNumberId =
201 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber);
Patrick Beard0caa3942012-04-19 00:25:12 +0000202 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSNumberId,
203 Loc, Sema::LookupOrdinaryName);
204 S.NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
205 if (!S.NSNumberDecl) {
206 if (S.getLangOpts().DebuggerObjCLiteral) {
207 // Create a stub definition of NSNumber.
Jordy Roseaca01f92012-05-12 17:32:52 +0000208 S.NSNumberDecl = ObjCInterfaceDecl::Create(CX,
209 CX.getTranslationUnitDecl(),
210 SourceLocation(), NSNumberId,
Craig Topperc3ec1492014-05-26 06:22:03 +0000211 nullptr, SourceLocation());
Patrick Beard0caa3942012-04-19 00:25:12 +0000212 } else {
213 // Otherwise, require a declaration of NSNumber.
214 S.Diag(Loc, diag::err_undeclared_nsnumber);
Craig Topperc3ec1492014-05-26 06:22:03 +0000215 return nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000216 }
217 } else if (!S.NSNumberDecl->hasDefinition()) {
218 S.Diag(Loc, diag::err_undeclared_nsnumber);
Craig Topperc3ec1492014-05-26 06:22:03 +0000219 return nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000220 }
221
222 // generate the pointer to NSNumber type.
Jordy Roseaca01f92012-05-12 17:32:52 +0000223 QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
224 S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000225 }
226
Ted Kremeneke65b0862012-03-06 20:05:56 +0000227 // Look for the appropriate method within NSNumber.
Jordy Roseaca01f92012-05-12 17:32:52 +0000228 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000229 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000230 // create a stub definition this NSNumber factory method.
Craig Topperc3ec1492014-05-26 06:22:03 +0000231 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000232 Method =
233 ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
234 S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
235 /*isInstance=*/false, /*isVariadic=*/false,
236 /*isPropertyAccessor=*/false,
237 /*isImplicitlyDeclared=*/true,
238 /*isDefined=*/false, ObjCMethodDecl::Required,
239 /*HasRelatedResultType=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000240 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
241 SourceLocation(), SourceLocation(),
Patrick Beard0caa3942012-04-19 00:25:12 +0000242 &CX.Idents.get("value"),
Craig Topperc3ec1492014-05-26 06:22:03 +0000243 NumberType, /*TInfo=*/nullptr,
244 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000245 Method->setMethodParams(S.Context, value, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000246 }
247
Jordy Rose08e500c2012-05-12 17:32:44 +0000248 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
Craig Topperc3ec1492014-05-26 06:22:03 +0000249 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000250
251 // Note: if the parameter type is out-of-line, we'll catch it later in the
252 // implicit conversion.
253
254 S.NSNumberLiteralMethods[*Kind] = Method;
255 return Method;
256}
257
Patrick Beard0caa3942012-04-19 00:25:12 +0000258/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
259/// numeric literal expression. Type of the expression will be "NSNumber *".
Ted Kremeneke65b0862012-03-06 20:05:56 +0000260ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000261 // Determine the type of the literal.
262 QualType NumberType = Number->getType();
263 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
264 // In C, character literals have type 'int'. That's not the type we want
265 // to use to determine the Objective-c literal kind.
266 switch (Char->getKind()) {
267 case CharacterLiteral::Ascii:
268 NumberType = Context.CharTy;
269 break;
270
271 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000272 NumberType = Context.getWideCharType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000273 break;
274
275 case CharacterLiteral::UTF16:
276 NumberType = Context.Char16Ty;
277 break;
278
279 case CharacterLiteral::UTF32:
280 NumberType = Context.Char32Ty;
281 break;
282 }
283 }
284
Ted Kremeneke65b0862012-03-06 20:05:56 +0000285 // Look for the appropriate method within NSNumber.
286 // Construct the literal.
Patrick Beard2565c592012-05-01 21:47:19 +0000287 SourceRange NR(Number->getSourceRange());
Patrick Beard0caa3942012-04-19 00:25:12 +0000288 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
Patrick Beard2565c592012-05-01 21:47:19 +0000289 true, NR);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000290 if (!Method)
291 return ExprError();
292
293 // Convert the number to the type that the parameter expects.
Alp Toker03376dc2014-07-07 09:02:20 +0000294 ParmVarDecl *ParamDecl = Method->parameters()[0];
Patrick Beard2565c592012-05-01 21:47:19 +0000295 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
296 ParamDecl);
297 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
298 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000299 Number);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000300 if (ConvertedNumber.isInvalid())
301 return ExprError();
302 Number = ConvertedNumber.get();
303
Patrick Beard2565c592012-05-01 21:47:19 +0000304 // Use the effective source range of the literal, including the leading '@'.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000305 return MaybeBindToTemporary(
Patrick Beard2565c592012-05-01 21:47:19 +0000306 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
307 SourceRange(AtLoc, NR.getEnd())));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000308}
309
310ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
311 SourceLocation ValueLoc,
312 bool Value) {
313 ExprResult Inner;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000314 if (getLangOpts().CPlusPlus) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000315 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
316 } else {
317 // C doesn't actually have a way to represent literal values of type
318 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
319 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
320 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
321 CK_IntegralToBoolean);
322 }
323
324 return BuildObjCNumericLiteral(AtLoc, Inner.get());
325}
326
327/// \brief Check that the given expression is a valid element of an Objective-C
328/// collection literal.
329static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000330 QualType T,
331 bool ArrayLiteral = false) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000332 // If the expression is type-dependent, there's nothing for us to do.
333 if (Element->isTypeDependent())
334 return Element;
335
336 ExprResult Result = S.CheckPlaceholderExpr(Element);
337 if (Result.isInvalid())
338 return ExprError();
339 Element = Result.get();
340
341 // In C++, check for an implicit conversion to an Objective-C object pointer
342 // type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000343 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000344 InitializedEntity Entity
Jordy Roseaca01f92012-05-12 17:32:52 +0000345 = InitializedEntity::InitializeParameter(S.Context, T,
346 /*Consumed=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000347 InitializationKind Kind
Jordy Roseaca01f92012-05-12 17:32:52 +0000348 = InitializationKind::CreateCopy(Element->getLocStart(),
349 SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000350 InitializationSequence Seq(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000351 if (!Seq.Failed())
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000352 return Seq.Perform(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000353 }
354
355 Expr *OrigElement = Element;
356
357 // Perform lvalue-to-rvalue conversion.
358 Result = S.DefaultLvalueConversion(Element);
359 if (Result.isInvalid())
360 return ExprError();
361 Element = Result.get();
362
363 // Make sure that we have an Objective-C pointer type or block.
364 if (!Element->getType()->isObjCObjectPointerType() &&
365 !Element->getType()->isBlockPointerType()) {
366 bool Recovered = false;
367
368 // If this is potentially an Objective-C numeric literal, add the '@'.
369 if (isa<IntegerLiteral>(OrigElement) ||
370 isa<CharacterLiteral>(OrigElement) ||
371 isa<FloatingLiteral>(OrigElement) ||
372 isa<ObjCBoolLiteralExpr>(OrigElement) ||
373 isa<CXXBoolLiteralExpr>(OrigElement)) {
374 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
375 int Which = isa<CharacterLiteral>(OrigElement) ? 1
376 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
377 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
378 : 3;
379
380 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
381 << Which << OrigElement->getSourceRange()
382 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
383
384 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
385 OrigElement);
386 if (Result.isInvalid())
387 return ExprError();
388
389 Element = Result.get();
390 Recovered = true;
391 }
392 }
393 // If this is potentially an Objective-C string literal, add the '@'.
394 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
395 if (String->isAscii()) {
396 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
397 << 0 << OrigElement->getSourceRange()
398 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
399
400 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
401 if (Result.isInvalid())
402 return ExprError();
403
404 Element = Result.get();
405 Recovered = true;
406 }
407 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000408
Ted Kremeneke65b0862012-03-06 20:05:56 +0000409 if (!Recovered) {
410 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
411 << Element->getType();
412 return ExprError();
413 }
414 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000415 if (ArrayLiteral)
Ted Kremenek197fee42013-10-09 22:34:33 +0000416 if (ObjCStringLiteral *getString =
417 dyn_cast<ObjCStringLiteral>(OrigElement)) {
418 if (StringLiteral *SL = getString->getString()) {
419 unsigned numConcat = SL->getNumConcatenated();
420 if (numConcat > 1) {
421 // Only warn if the concatenated string doesn't come from a macro.
422 bool hasMacro = false;
423 for (unsigned i = 0; i < numConcat ; ++i)
424 if (SL->getStrTokenLoc(i).isMacroID()) {
425 hasMacro = true;
426 break;
427 }
428 if (!hasMacro)
429 S.Diag(Element->getLocStart(),
430 diag::warn_concatenated_nsarray_literal)
431 << Element->getType();
432 }
433 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000434 }
435
Ted Kremeneke65b0862012-03-06 20:05:56 +0000436 // Make sure that the element has the type that the container factory
437 // function expects.
438 return S.PerformCopyInitialization(
439 InitializedEntity::InitializeParameter(S.Context, T,
440 /*Consumed=*/false),
441 Element->getLocStart(), Element);
442}
443
Patrick Beard0caa3942012-04-19 00:25:12 +0000444ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
445 if (ValueExpr->isTypeDependent()) {
446 ObjCBoxedExpr *BoxedExpr =
Craig Topperc3ec1492014-05-26 06:22:03 +0000447 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000448 return BoxedExpr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000449 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000450 ObjCMethodDecl *BoxingMethod = nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000451 QualType BoxedType;
452 // Convert the expression to an RValue, so we can check for pointer types...
453 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
454 if (RValue.isInvalid()) {
455 return ExprError();
456 }
457 ValueExpr = RValue.get();
Patrick Beard2565c592012-05-01 21:47:19 +0000458 QualType ValueType(ValueExpr->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +0000459 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
460 QualType PointeeType = PT->getPointeeType();
461 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
462
463 if (!NSStringDecl) {
464 IdentifierInfo *NSStringId =
465 NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
466 NamedDecl *Decl = LookupSingleName(TUScope, NSStringId,
467 SR.getBegin(), LookupOrdinaryName);
468 NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl);
469 if (!NSStringDecl) {
470 if (getLangOpts().DebuggerObjCLiteral) {
471 // Support boxed expressions in the debugger w/o NSString declaration.
Jordy Roseaca01f92012-05-12 17:32:52 +0000472 DeclContext *TU = Context.getTranslationUnitDecl();
473 NSStringDecl = ObjCInterfaceDecl::Create(Context, TU,
474 SourceLocation(),
475 NSStringId,
Craig Topperc3ec1492014-05-26 06:22:03 +0000476 nullptr, SourceLocation());
Patrick Beard0caa3942012-04-19 00:25:12 +0000477 } else {
478 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
479 return ExprError();
480 }
481 } else if (!NSStringDecl->hasDefinition()) {
482 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
483 return ExprError();
484 }
485 assert(NSStringDecl && "NSStringDecl should not be NULL");
Jordy Roseaca01f92012-05-12 17:32:52 +0000486 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
487 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000488 }
489
490 if (!StringWithUTF8StringMethod) {
491 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
492 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
493
494 // Look for the appropriate method within NSString.
Jordy Rose08e500c2012-05-12 17:32:44 +0000495 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
496 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000497 // Debugger needs to work even if NSString hasn't been defined.
Craig Topperc3ec1492014-05-26 06:22:03 +0000498 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000499 ObjCMethodDecl *M = ObjCMethodDecl::Create(
500 Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
501 NSStringPointer, ReturnTInfo, NSStringDecl,
502 /*isInstance=*/false, /*isVariadic=*/false,
503 /*isPropertyAccessor=*/false,
504 /*isImplicitlyDeclared=*/true,
505 /*isDefined=*/false, ObjCMethodDecl::Required,
506 /*HasRelatedResultType=*/false);
Jordy Roseaca01f92012-05-12 17:32:52 +0000507 QualType ConstCharType = Context.CharTy.withConst();
Patrick Beard0caa3942012-04-19 00:25:12 +0000508 ParmVarDecl *value =
509 ParmVarDecl::Create(Context, M,
510 SourceLocation(), SourceLocation(),
511 &Context.Idents.get("value"),
Jordy Roseaca01f92012-05-12 17:32:52 +0000512 Context.getPointerType(ConstCharType),
Craig Topperc3ec1492014-05-26 06:22:03 +0000513 /*TInfo=*/nullptr,
514 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000515 M->setMethodParams(Context, value, None);
Jordy Rose08e500c2012-05-12 17:32:44 +0000516 BoxingMethod = M;
Patrick Beard0caa3942012-04-19 00:25:12 +0000517 }
Jordy Rose890f4572012-05-12 15:53:41 +0000518
Jordy Rose08e500c2012-05-12 17:32:44 +0000519 if (!validateBoxingMethod(*this, SR.getBegin(), NSStringDecl,
520 stringWithUTF8String, BoxingMethod))
521 return ExprError();
522
523 StringWithUTF8StringMethod = BoxingMethod;
Patrick Beard0caa3942012-04-19 00:25:12 +0000524 }
525
526 BoxingMethod = StringWithUTF8StringMethod;
527 BoxedType = NSStringPointer;
528 }
Patrick Beard2565c592012-05-01 21:47:19 +0000529 } else if (ValueType->isBuiltinType()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000530 // The other types we support are numeric, char and BOOL/bool. We could also
531 // provide limited support for structure types, such as NSRange, NSRect, and
532 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
533 // for more details.
534
535 // Check for a top-level character literal.
536 if (const CharacterLiteral *Char =
537 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
538 // In C, character literals have type 'int'. That's not the type we want
539 // to use to determine the Objective-c literal kind.
540 switch (Char->getKind()) {
541 case CharacterLiteral::Ascii:
542 ValueType = Context.CharTy;
543 break;
544
545 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000546 ValueType = Context.getWideCharType();
Patrick Beard0caa3942012-04-19 00:25:12 +0000547 break;
548
549 case CharacterLiteral::UTF16:
550 ValueType = Context.Char16Ty;
551 break;
552
553 case CharacterLiteral::UTF32:
554 ValueType = Context.Char32Ty;
555 break;
556 }
557 }
Fariborz Jahanian5d64abb2014-06-18 20:49:02 +0000558 CheckForIntOverflow(ValueExpr);
Patrick Beard0caa3942012-04-19 00:25:12 +0000559 // FIXME: Do I need to do anything special with BoolTy expressions?
560
561 // Look for the appropriate method within NSNumber.
562 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType);
563 BoxedType = NSNumberPointer;
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000564
565 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
566 if (!ET->getDecl()->isComplete()) {
567 Diag(SR.getBegin(), diag::err_objc_incomplete_boxed_expression_type)
568 << ValueType << ValueExpr->getSourceRange();
569 return ExprError();
570 }
571
572 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(),
573 ET->getDecl()->getIntegerType());
574 BoxedType = NSNumberPointer;
Patrick Beard0caa3942012-04-19 00:25:12 +0000575 }
576
577 if (!BoxingMethod) {
578 Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type)
579 << ValueType << ValueExpr->getSourceRange();
580 return ExprError();
581 }
582
583 // Convert the expression to the type that the parameter requires.
Alp Toker03376dc2014-07-07 09:02:20 +0000584 ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
Patrick Beard2565c592012-05-01 21:47:19 +0000585 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
586 ParamDecl);
587 ExprResult ConvertedValueExpr = PerformCopyInitialization(Entity,
588 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000589 ValueExpr);
Patrick Beard0caa3942012-04-19 00:25:12 +0000590 if (ConvertedValueExpr.isInvalid())
591 return ExprError();
592 ValueExpr = ConvertedValueExpr.get();
593
594 ObjCBoxedExpr *BoxedExpr =
595 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
596 BoxingMethod, SR);
597 return MaybeBindToTemporary(BoxedExpr);
598}
599
John McCallf2538342012-07-31 05:14:30 +0000600/// Build an ObjC subscript pseudo-object expression, given that
601/// that's supported by the runtime.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000602ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
603 Expr *IndexExpr,
604 ObjCMethodDecl *getterMethod,
605 ObjCMethodDecl *setterMethod) {
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +0000606 assert(!LangOpts.isSubscriptPointerArithmetic());
John McCall5fb5df92012-06-20 06:18:46 +0000607
John McCallf2538342012-07-31 05:14:30 +0000608 // We can't get dependent types here; our callers should have
609 // filtered them out.
610 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
611 "base or index cannot have dependent type here");
612
613 // Filter out placeholders in the index. In theory, overloads could
614 // be preserved here, although that might not actually work correctly.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000615 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
616 if (Result.isInvalid())
617 return ExprError();
618 IndexExpr = Result.get();
619
John McCallf2538342012-07-31 05:14:30 +0000620 // Perform lvalue-to-rvalue conversion on the base.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000621 Result = DefaultLvalueConversion(BaseExpr);
622 if (Result.isInvalid())
623 return ExprError();
624 BaseExpr = Result.get();
John McCallf2538342012-07-31 05:14:30 +0000625
626 // Build the pseudo-object expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000627 return ObjCSubscriptRefExpr::Create(Context, BaseExpr, IndexExpr,
628 Context.PseudoObjectTy, getterMethod,
629 setterMethod, RB);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000630}
631
632ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
633 // Look up the NSArray class, if we haven't done so already.
634 if (!NSArrayDecl) {
635 NamedDecl *IF = LookupSingleName(TUScope,
636 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
637 SR.getBegin(),
638 LookupOrdinaryName);
639 NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000640 if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000641 NSArrayDecl = ObjCInterfaceDecl::Create (Context,
642 Context.getTranslationUnitDecl(),
643 SourceLocation(),
644 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
Craig Topperc3ec1492014-05-26 06:22:03 +0000645 nullptr, SourceLocation());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000646
647 if (!NSArrayDecl) {
648 Diag(SR.getBegin(), diag::err_undeclared_nsarray);
649 return ExprError();
650 }
651 }
652
653 // Find the arrayWithObjects:count: method, if we haven't done so already.
654 QualType IdT = Context.getObjCIdType();
655 if (!ArrayWithObjectsMethod) {
656 Selector
657 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
Jordy Rose08e500c2012-05-12 17:32:44 +0000658 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
659 if (!Method && getLangOpts().DebuggerObjCLiteral) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000660 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000661 Method = ObjCMethodDecl::Create(
662 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
663 Context.getTranslationUnitDecl(), false /*Instance*/,
664 false /*isVariadic*/,
665 /*isPropertyAccessor=*/false,
666 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
667 ObjCMethodDecl::Required, false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000668 SmallVector<ParmVarDecl *, 2> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000669 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000670 SourceLocation(),
671 SourceLocation(),
672 &Context.Idents.get("objects"),
673 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000674 /*TInfo=*/nullptr,
675 SC_None, nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000676 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000677 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000678 SourceLocation(),
679 SourceLocation(),
680 &Context.Idents.get("cnt"),
681 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000682 /*TInfo=*/nullptr, SC_None,
683 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000684 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000685 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000686 }
687
Jordy Rose08e500c2012-05-12 17:32:44 +0000688 if (!validateBoxingMethod(*this, SR.getBegin(), NSArrayDecl, Sel, Method))
Ted Kremeneke65b0862012-03-06 20:05:56 +0000689 return ExprError();
Jordy Rose08e500c2012-05-12 17:32:44 +0000690
Jordy Rose4af44872012-05-12 17:32:56 +0000691 // Dig out the type that all elements should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000692 QualType T = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000693 const PointerType *PtrT = T->getAs<PointerType>();
694 if (!PtrT ||
695 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
696 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
697 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000698 Diag(Method->parameters()[0]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000699 diag::note_objc_literal_method_param)
700 << 0 << T
701 << Context.getPointerType(IdT.withConst());
702 return ExprError();
703 }
704
705 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000706 if (!Method->parameters()[1]->getType()->isIntegerType()) {
Jordy Rose4af44872012-05-12 17:32:56 +0000707 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
708 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000709 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000710 diag::note_objc_literal_method_param)
711 << 1
Alp Toker03376dc2014-07-07 09:02:20 +0000712 << Method->parameters()[1]->getType()
Jordy Rose4af44872012-05-12 17:32:56 +0000713 << "integral";
714 return ExprError();
715 }
716
717 // We've found a good +arrayWithObjects:count: method. Save it!
Jordy Rose08e500c2012-05-12 17:32:44 +0000718 ArrayWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000719 }
720
Alp Toker03376dc2014-07-07 09:02:20 +0000721 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000722 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000723
724 // Check that each of the elements provided is valid in a collection literal,
725 // performing conversions as necessary.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000726 Expr **ElementsBuffer = Elements.data();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000727 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
728 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
729 ElementsBuffer[I],
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000730 RequiredType, true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000731 if (Converted.isInvalid())
732 return ExprError();
733
734 ElementsBuffer[I] = Converted.get();
735 }
736
737 QualType Ty
738 = Context.getObjCObjectPointerType(
739 Context.getObjCInterfaceType(NSArrayDecl));
740
741 return MaybeBindToTemporary(
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000742 ObjCArrayLiteral::Create(Context, Elements, Ty,
Fariborz Jahanian413297c2014-08-06 18:13:46 +0000743 ArrayWithObjectsMethod, nullptr, SR));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000744}
745
746ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
747 ObjCDictionaryElement *Elements,
748 unsigned NumElements) {
Fariborz Jahanian2a25dba2014-08-06 23:40:31 +0000749 bool Arc = getLangOpts().ObjCAutoRefCount;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000750 // Look up the NSDictionary class, if we haven't done so already.
751 if (!NSDictionaryDecl) {
752 NamedDecl *IF = LookupSingleName(TUScope,
753 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
754 SR.getBegin(), LookupOrdinaryName);
755 NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000756 if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000757 NSDictionaryDecl = ObjCInterfaceDecl::Create (Context,
758 Context.getTranslationUnitDecl(),
759 SourceLocation(),
760 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
Craig Topperc3ec1492014-05-26 06:22:03 +0000761 nullptr, SourceLocation());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000762
763 if (!NSDictionaryDecl) {
764 Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
765 return ExprError();
766 }
767 }
768
Fariborz Jahanian2a25dba2014-08-06 23:40:31 +0000769 QualType IdT = Context.getObjCIdType();
770 if (Arc && !DictAllocObjectsMethod) {
771 // Find +[NSDictionary alloc] method.
772 IdentifierInfo *II = &Context.Idents.get("alloc");
773 Selector AllocSel = Context.Selectors.getSelector(0, &II);
774 DictAllocObjectsMethod = NSDictionaryDecl->lookupClassMethod(AllocSel);
775 if (!DictAllocObjectsMethod && getLangOpts().DebuggerObjCLiteral) {
776 DictAllocObjectsMethod = ObjCMethodDecl::Create(Context,
777 SourceLocation(), SourceLocation(), AllocSel,
778 IdT,
779 nullptr /*TypeSourceInfo */,
780 Context.getTranslationUnitDecl(),
781 false /*Instance*/, false/*isVariadic*/,
782 /*isPropertyAccessor=*/false,
783 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
784 ObjCMethodDecl::Required,
785 false);
786 SmallVector<ParmVarDecl *, 1> Params;
787 DictAllocObjectsMethod->setMethodParams(Context, Params, None);
788 }
789 if (!DictAllocObjectsMethod) {
790 Diag(SR.getBegin(), diag::err_undeclared_alloc);
791 return ExprError();
792 }
793 }
794
Ted Kremeneke65b0862012-03-06 20:05:56 +0000795 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
796 // so already.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000797 if (!DictionaryWithObjectsMethod) {
798 Selector Sel = NSAPIObj->getNSDictionarySelector(
Jordy Roseaca01f92012-05-12 17:32:52 +0000799 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
Jordy Rose08e500c2012-05-12 17:32:44 +0000800 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
801 if (!Method && getLangOpts().DebuggerObjCLiteral) {
802 Method = ObjCMethodDecl::Create(Context,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000803 SourceLocation(), SourceLocation(), Sel,
804 IdT,
Craig Topperc3ec1492014-05-26 06:22:03 +0000805 nullptr /*TypeSourceInfo */,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000806 Context.getTranslationUnitDecl(),
807 false /*Instance*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000808 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000809 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
810 ObjCMethodDecl::Required,
811 false);
812 SmallVector<ParmVarDecl *, 3> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000813 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000814 SourceLocation(),
815 SourceLocation(),
816 &Context.Idents.get("objects"),
817 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000818 /*TInfo=*/nullptr, SC_None,
819 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000820 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000821 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000822 SourceLocation(),
823 SourceLocation(),
824 &Context.Idents.get("keys"),
825 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000826 /*TInfo=*/nullptr, SC_None,
827 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000828 Params.push_back(keys);
Jordy Rose08e500c2012-05-12 17:32:44 +0000829 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000830 SourceLocation(),
831 SourceLocation(),
832 &Context.Idents.get("cnt"),
833 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000834 /*TInfo=*/nullptr, SC_None,
835 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000836 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000837 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000838 }
839
Jordy Rose08e500c2012-05-12 17:32:44 +0000840 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
841 Method))
842 return ExprError();
843
Jordy Rose4af44872012-05-12 17:32:56 +0000844 // Dig out the type that all values should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000845 QualType ValueT = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000846 const PointerType *PtrValue = ValueT->getAs<PointerType>();
847 if (!PtrValue ||
848 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000849 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
Jordy Rose4af44872012-05-12 17:32:56 +0000850 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000851 Diag(Method->parameters()[0]->getLocation(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000852 diag::note_objc_literal_method_param)
Jordy Rose4af44872012-05-12 17:32:56 +0000853 << 0 << ValueT
Ted Kremeneke65b0862012-03-06 20:05:56 +0000854 << Context.getPointerType(IdT.withConst());
855 return ExprError();
856 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000857
Jordy Rose4af44872012-05-12 17:32:56 +0000858 // Dig out the type that all keys should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000859 QualType KeyT = Method->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000860 const PointerType *PtrKey = KeyT->getAs<PointerType>();
861 if (!PtrKey ||
862 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
863 IdT)) {
864 bool err = true;
865 if (PtrKey) {
866 if (QIDNSCopying.isNull()) {
867 // key argument of selector is id<NSCopying>?
868 if (ObjCProtocolDecl *NSCopyingPDecl =
869 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
870 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
871 QIDNSCopying =
872 Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
873 (ObjCProtocolDecl**) PQ,1);
874 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
875 }
876 }
877 if (!QIDNSCopying.isNull())
878 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
879 QIDNSCopying);
880 }
881
882 if (err) {
883 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
884 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000885 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000886 diag::note_objc_literal_method_param)
887 << 1 << KeyT
888 << Context.getPointerType(IdT.withConst());
889 return ExprError();
890 }
891 }
892
893 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000894 QualType CountType = Method->parameters()[2]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000895 if (!CountType->isIntegerType()) {
896 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
897 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000898 Diag(Method->parameters()[2]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000899 diag::note_objc_literal_method_param)
900 << 2 << CountType
901 << "integral";
902 return ExprError();
903 }
904
905 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
906 DictionaryWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000907 }
908
Alp Toker03376dc2014-07-07 09:02:20 +0000909 QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000910 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
Alp Toker03376dc2014-07-07 09:02:20 +0000911 QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000912 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
913
Ted Kremeneke65b0862012-03-06 20:05:56 +0000914 // Check that each of the keys and values provided is valid in a collection
915 // literal, performing conversions as necessary.
916 bool HasPackExpansions = false;
917 for (unsigned I = 0, N = NumElements; I != N; ++I) {
918 // Check the key.
919 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
920 KeyT);
921 if (Key.isInvalid())
922 return ExprError();
923
924 // Check the value.
925 ExprResult Value
926 = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
927 if (Value.isInvalid())
928 return ExprError();
929
930 Elements[I].Key = Key.get();
931 Elements[I].Value = Value.get();
932
933 if (Elements[I].EllipsisLoc.isInvalid())
934 continue;
935
936 if (!Elements[I].Key->containsUnexpandedParameterPack() &&
937 !Elements[I].Value->containsUnexpandedParameterPack()) {
938 Diag(Elements[I].EllipsisLoc,
939 diag::err_pack_expansion_without_parameter_packs)
940 << SourceRange(Elements[I].Key->getLocStart(),
941 Elements[I].Value->getLocEnd());
942 return ExprError();
943 }
944
945 HasPackExpansions = true;
946 }
947
948
949 QualType Ty
950 = Context.getObjCObjectPointerType(
Robert Wilhelm88e02492013-08-19 07:57:02 +0000951 Context.getObjCInterfaceType(NSDictionaryDecl));
952 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
953 Context, makeArrayRef(Elements, NumElements), HasPackExpansions, Ty,
Fariborz Jahanian2a25dba2014-08-06 23:40:31 +0000954 DictionaryWithObjectsMethod, DictAllocObjectsMethod, SR));
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000955}
956
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000957ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregorabd9e962010-04-20 15:39:42 +0000958 TypeSourceInfo *EncodedTypeInfo,
Anders Carlsson315d2292009-06-07 18:45:35 +0000959 SourceLocation RParenLoc) {
Douglas Gregorabd9e962010-04-20 15:39:42 +0000960 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlsson315d2292009-06-07 18:45:35 +0000961 QualType StrTy;
Mike Stump11289f42009-09-09 15:08:12 +0000962 if (EncodedType->isDependentType())
Anders Carlsson315d2292009-06-07 18:45:35 +0000963 StrTy = Context.DependentTy;
964 else {
Fariborz Jahaniand9bc6c32011-06-16 22:34:44 +0000965 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
966 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000967 if (RequireCompleteType(AtLoc, EncodedType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000968 diag::err_incomplete_type_objc_at_encode,
969 EncodedTypeInfo->getTypeLoc()))
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000970 return ExprError();
971
Anders Carlsson315d2292009-06-07 18:45:35 +0000972 std::string Str;
973 Context.getObjCEncodingForType(EncodedType, Str);
974
975 // The type of @encode is the same as the type of the corresponding string,
976 // which is an array type.
977 StrTy = Context.CharTy;
978 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +0000979 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Anders Carlsson315d2292009-06-07 18:45:35 +0000980 StrTy.addConst();
981 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
982 ArrayType::Normal, 0);
983 }
Mike Stump11289f42009-09-09 15:08:12 +0000984
Douglas Gregorabd9e962010-04-20 15:39:42 +0000985 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlsson315d2292009-06-07 18:45:35 +0000986}
987
John McCallfaf5fb42010-08-26 23:41:50 +0000988ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
989 SourceLocation EncodeLoc,
990 SourceLocation LParenLoc,
991 ParsedType ty,
992 SourceLocation RParenLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000993 // FIXME: Preserve type source info ?
Douglas Gregorabd9e962010-04-20 15:39:42 +0000994 TypeSourceInfo *TInfo;
995 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
996 if (!TInfo)
997 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
998 PP.getLocForEndOfToken(LParenLoc));
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000999
Douglas Gregorabd9e962010-04-20 15:39:42 +00001000 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001001}
1002
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001003static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
1004 SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001005 SourceLocation LParenLoc,
1006 SourceLocation RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001007 ObjCMethodDecl *Method,
1008 ObjCMethodList &MethList) {
1009 ObjCMethodList *M = &MethList;
1010 bool Warned = false;
1011 for (M = M->getNext(); M; M=M->getNext()) {
1012 ObjCMethodDecl *MatchingMethodDecl = M->Method;
1013 if (MatchingMethodDecl == Method ||
1014 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
1015 MatchingMethodDecl->getSelector() != Method->getSelector())
1016 continue;
1017 if (!S.MatchTwoMethodDeclarations(Method,
1018 MatchingMethodDecl, Sema::MMS_loose)) {
1019 if (!Warned) {
1020 Warned = true;
1021 S.Diag(AtLoc, diag::warning_multiple_selectors)
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001022 << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
1023 << FixItHint::CreateInsertion(RParenLoc, ")");
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001024 S.Diag(Method->getLocation(), diag::note_method_declared_at)
1025 << Method->getDeclName();
1026 }
1027 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
1028 << MatchingMethodDecl->getDeclName();
1029 }
1030 }
1031 return Warned;
1032}
1033
1034static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001035 ObjCMethodDecl *Method,
1036 SourceLocation LParenLoc,
1037 SourceLocation RParenLoc,
1038 bool WarnMultipleSelectors) {
1039 if (!WarnMultipleSelectors ||
1040 S.Diags.isIgnored(diag::warning_multiple_selectors, SourceLocation()))
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001041 return;
1042 bool Warned = false;
1043 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1044 e = S.MethodPool.end(); b != e; b++) {
1045 // first, instance methods
1046 ObjCMethodList &InstMethList = b->second.first;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001047 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001048 Method, InstMethList))
1049 Warned = true;
1050
1051 // second, class methods
1052 ObjCMethodList &ClsMethList = b->second.second;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001053 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1054 Method, ClsMethList) || Warned)
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001055 return;
1056 }
1057}
1058
John McCallfaf5fb42010-08-26 23:41:50 +00001059ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1060 SourceLocation AtLoc,
1061 SourceLocation SelLoc,
1062 SourceLocation LParenLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001063 SourceLocation RParenLoc,
1064 bool WarnMultipleSelectors) {
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001065 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
1066 SourceRange(LParenLoc, RParenLoc), false, false);
1067 if (!Method)
1068 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian0571d9b2009-06-16 16:25:00 +00001069 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00001070 if (!Method) {
1071 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1072 Selector MatchedSel = OM->getSelector();
1073 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1074 RParenLoc.getLocWithOffset(-1));
1075 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1076 << Sel << MatchedSel
1077 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1078
1079 } else
1080 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001081 } else
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001082 DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
1083 WarnMultipleSelectors);
Fariborz Jahanian9a881012011-07-13 19:05:43 +00001084
Fariborz Jahanian65a78b52014-05-09 19:51:39 +00001085 if (Method &&
1086 Method->getImplementationControl() != ObjCMethodDecl::Optional &&
1087 !getSourceManager().isInSystemHeader(Method->getLocation())) {
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001088 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
1089 = ReferencedSelectors.find(Sel);
1090 if (Pos == ReferencedSelectors.end())
1091 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
Fariborz Jahanian9a881012011-07-13 19:05:43 +00001092 }
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00001093
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001094 // In ARC, forbid the user from using @selector for
John McCall31168b02011-06-15 23:02:42 +00001095 // retain/release/autorelease/dealloc/retainCount.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001096 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001097 switch (Sel.getMethodFamily()) {
1098 case OMF_retain:
1099 case OMF_release:
1100 case OMF_autorelease:
1101 case OMF_retainCount:
1102 case OMF_dealloc:
1103 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1104 Sel << SourceRange(LParenLoc, RParenLoc);
1105 break;
1106
1107 case OMF_None:
1108 case OMF_alloc:
1109 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00001110 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00001111 case OMF_init:
1112 case OMF_mutableCopy:
1113 case OMF_new:
1114 case OMF_self:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00001115 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00001116 break;
1117 }
1118 }
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001119 QualType Ty = Context.getObjCSelType();
Daniel Dunbar45858d22010-02-03 20:11:42 +00001120 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001121}
1122
John McCallfaf5fb42010-08-26 23:41:50 +00001123ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1124 SourceLocation AtLoc,
1125 SourceLocation ProtoLoc,
1126 SourceLocation LParenLoc,
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001127 SourceLocation ProtoIdLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00001128 SourceLocation RParenLoc) {
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001129 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001130 if (!PDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001131 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001132 return true;
1133 }
Fariborz Jahaniana57d91c22014-07-25 19:45:01 +00001134 if (PDecl->hasDefinition())
1135 PDecl = PDecl->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00001136
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001137 QualType Ty = Context.getObjCProtoType();
1138 if (Ty.isNull())
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001139 return true;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001140 Ty = Context.getObjCObjectPointerType(Ty);
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001141 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001142}
1143
John McCall5f2d5562011-02-03 09:00:02 +00001144/// Try to capture an implicit reference to 'self'.
Eli Friedman24af8502012-02-03 22:47:37 +00001145ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1146 DeclContext *DC = getFunctionLevelDeclContext();
John McCall5f2d5562011-02-03 09:00:02 +00001147
1148 // If we're not in an ObjC method, error out. Note that, unlike the
1149 // C++ case, we don't require an instance method --- class methods
1150 // still have a 'self', and we really do still need to capture it!
1151 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1152 if (!method)
Craig Topperc3ec1492014-05-26 06:22:03 +00001153 return nullptr;
John McCall5f2d5562011-02-03 09:00:02 +00001154
Douglas Gregorfdf598e2012-02-18 09:37:24 +00001155 tryCaptureVariable(method->getSelfDecl(), Loc);
John McCall5f2d5562011-02-03 09:00:02 +00001156
1157 return method;
1158}
1159
Douglas Gregor64910ca2011-09-09 20:05:21 +00001160static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1161 if (T == Context.getObjCInstanceType())
1162 return Context.getObjCIdType();
1163
1164 return T;
1165}
1166
Douglas Gregor33823722011-06-11 01:09:30 +00001167QualType Sema::getMessageSendResultType(QualType ReceiverType,
1168 ObjCMethodDecl *Method,
1169 bool isClassMessage, bool isSuperMessage) {
1170 assert(Method && "Must have a method");
1171 if (!Method->hasRelatedResultType())
1172 return Method->getSendResultType();
1173
1174 // If a method has a related return type:
1175 // - if the method found is an instance method, but the message send
1176 // was a class message send, T is the declared return type of the method
1177 // found
1178 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregor64910ca2011-09-09 20:05:21 +00001179 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor33823722011-06-11 01:09:30 +00001180
1181 // - if the receiver is super, T is a pointer to the class of the
1182 // enclosing method definition
1183 if (isSuperMessage) {
1184 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
1185 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
1186 return Context.getObjCObjectPointerType(
1187 Context.getObjCInterfaceType(Class));
1188 }
1189
1190 // - if the receiver is the name of a class U, T is a pointer to U
1191 if (ReceiverType->getAs<ObjCInterfaceType>() ||
1192 ReceiverType->isObjCQualifiedInterfaceType())
1193 return Context.getObjCObjectPointerType(ReceiverType);
1194 // - if the receiver is of type Class or qualified Class type,
1195 // T is the declared return type of the method.
1196 if (ReceiverType->isObjCClassType() ||
1197 ReceiverType->isObjCQualifiedClassType())
Douglas Gregor64910ca2011-09-09 20:05:21 +00001198 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor33823722011-06-11 01:09:30 +00001199
1200 // - if the receiver is id, qualified id, Class, or qualified Class, T
1201 // is the receiver type, otherwise
1202 // - T is the type of the receiver expression.
1203 return ReceiverType;
1204}
John McCall5f2d5562011-02-03 09:00:02 +00001205
John McCall5ec7e7d2013-03-19 07:04:25 +00001206/// Look for an ObjC method whose result type exactly matches the given type.
1207static const ObjCMethodDecl *
1208findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1209 QualType instancetype) {
Alp Toker314cc812014-01-25 16:55:45 +00001210 if (MD->getReturnType() == instancetype)
1211 return MD;
John McCall5ec7e7d2013-03-19 07:04:25 +00001212
1213 // For these purposes, a method in an @implementation overrides a
1214 // declaration in the @interface.
1215 if (const ObjCImplDecl *impl =
1216 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1217 const ObjCContainerDecl *iface;
1218 if (const ObjCCategoryImplDecl *catImpl =
1219 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1220 iface = catImpl->getCategoryDecl();
1221 } else {
1222 iface = impl->getClassInterface();
1223 }
1224
1225 const ObjCMethodDecl *ifaceMD =
1226 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1227 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1228 }
1229
1230 SmallVector<const ObjCMethodDecl *, 4> overrides;
1231 MD->getOverriddenMethods(overrides);
1232 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1233 if (const ObjCMethodDecl *result =
1234 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1235 return result;
1236 }
1237
Craig Topperc3ec1492014-05-26 06:22:03 +00001238 return nullptr;
John McCall5ec7e7d2013-03-19 07:04:25 +00001239}
1240
1241void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1242 // Only complain if we're in an ObjC method and the required return
1243 // type doesn't match the method's declared return type.
1244 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1245 if (!MD || !MD->hasRelatedResultType() ||
Alp Toker314cc812014-01-25 16:55:45 +00001246 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
John McCall5ec7e7d2013-03-19 07:04:25 +00001247 return;
1248
1249 // Look for a method overridden by this method which explicitly uses
1250 // 'instancetype'.
1251 if (const ObjCMethodDecl *overridden =
1252 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
Aaron Ballman41b10ac2014-08-01 13:20:09 +00001253 SourceRange range = overridden->getReturnTypeSourceRange();
1254 SourceLocation loc = range.getBegin();
John McCall5ec7e7d2013-03-19 07:04:25 +00001255 if (loc.isInvalid())
1256 loc = overridden->getLocation();
1257 Diag(loc, diag::note_related_result_type_explicit)
1258 << /*current method*/ 1 << range;
1259 return;
1260 }
1261
1262 // Otherwise, if we have an interesting method family, note that.
1263 // This should always trigger if the above didn't.
1264 if (ObjCMethodFamily family = MD->getMethodFamily())
1265 Diag(MD->getLocation(), diag::note_related_result_type_family)
1266 << /*current method*/ 1
1267 << family;
1268}
1269
Douglas Gregor33823722011-06-11 01:09:30 +00001270void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1271 E = E->IgnoreParenImpCasts();
1272 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1273 if (!MsgSend)
1274 return;
1275
1276 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1277 if (!Method)
1278 return;
1279
1280 if (!Method->hasRelatedResultType())
1281 return;
Alp Toker314cc812014-01-25 16:55:45 +00001282
1283 if (Context.hasSameUnqualifiedType(
1284 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
Douglas Gregor33823722011-06-11 01:09:30 +00001285 return;
Alp Toker314cc812014-01-25 16:55:45 +00001286
1287 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
Douglas Gregorbab8a962011-09-08 01:46:34 +00001288 Context.getObjCInstanceType()))
1289 return;
1290
Douglas Gregor33823722011-06-11 01:09:30 +00001291 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1292 << Method->isInstanceMethod() << Method->getSelector()
1293 << MsgSend->getType();
1294}
1295
1296bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001297 MultiExprArg Args,
1298 Selector Sel,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001299 ArrayRef<SourceLocation> SelectorLocs,
1300 ObjCMethodDecl *Method,
Douglas Gregor33823722011-06-11 01:09:30 +00001301 bool isClassMessage, bool isSuperMessage,
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001302 SourceLocation lbrac, SourceLocation rbrac,
John McCall7decc9e2010-11-18 06:31:45 +00001303 QualType &ReturnType, ExprValueKind &VK) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001304 SourceLocation SelLoc;
1305 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1306 SelLoc = SelectorLocs.front();
1307 else
1308 SelLoc = lbrac;
1309
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001310 if (!Method) {
Daniel Dunbar83876b42008-09-11 00:04:36 +00001311 // Apply default argument promotion as for (C99 6.5.2.2p6).
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001312 for (unsigned i = 0, e = Args.size(); i != e; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001313 if (Args[i]->isTypeDependent())
1314 continue;
1315
John McCallcc5788c2013-03-04 07:34:02 +00001316 ExprResult result;
1317 if (getLangOpts().DebuggerSupport) {
1318 QualType paramTy; // ignored
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001319 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
John McCallcc5788c2013-03-04 07:34:02 +00001320 } else {
1321 result = DefaultArgumentPromotion(Args[i]);
1322 }
1323 if (result.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001324 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001325 Args[i] = result.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001326 }
Daniel Dunbar83876b42008-09-11 00:04:36 +00001327
John McCall31168b02011-06-15 23:02:42 +00001328 unsigned DiagID;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001329 if (getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00001330 DiagID = diag::err_arc_method_not_found;
1331 else
1332 DiagID = isClassMessage ? diag::warn_class_method_not_found
1333 : diag::warn_inst_method_not_found;
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001334 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001335 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
Fariborz Jahanian06499232013-06-18 17:10:58 +00001336 if (OMD && !OMD->isInvalidDecl()) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001337 if (getLangOpts().ObjCAutoRefCount)
1338 DiagID = diag::error_method_not_found_with_typo;
1339 else
1340 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1341 : diag::warn_instance_method_not_found_with_typo;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001342 Selector MatchedSel = OMD->getSelector();
1343 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001344 Diag(SelLoc, DiagID)
1345 << Sel<< isClassMessage << MatchedSel
Fariborz Jahanian75481672013-06-17 17:10:54 +00001346 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1347 }
1348 else
1349 Diag(SelLoc, DiagID)
1350 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001351 SelectorLocs.back());
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001352 // Find the class to which we are sending this message.
1353 if (ReceiverType->isObjCObjectPointerType()) {
Fariborz Jahanian478536b2013-05-15 15:27:35 +00001354 if (ObjCInterfaceDecl *Class =
1355 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl())
1356 Diag(Class->getLocation(), diag::note_receiver_class_declared);
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001357 }
1358 }
John McCall3f4138c2011-07-13 17:56:40 +00001359
1360 // In debuggers, we want to use __unknown_anytype for these
1361 // results so that clients can cast them.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001362 if (getLangOpts().DebuggerSupport) {
John McCall3f4138c2011-07-13 17:56:40 +00001363 ReturnType = Context.UnknownAnyTy;
1364 } else {
1365 ReturnType = Context.getObjCIdType();
1366 }
John McCall7decc9e2010-11-18 06:31:45 +00001367 VK = VK_RValue;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001368 return false;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001369 }
Mike Stump11289f42009-09-09 15:08:12 +00001370
Douglas Gregor33823722011-06-11 01:09:30 +00001371 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1372 isSuperMessage);
Alp Toker314cc812014-01-25 16:55:45 +00001373 VK = Expr::getValueKindForType(Method->getReturnType());
Mike Stump11289f42009-09-09 15:08:12 +00001374
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001375 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian60462092010-04-08 00:30:06 +00001376 // Method might have more arguments than selector indicates. This is due
1377 // to addition of c-style arguments in method.
1378 if (Method->param_size() > Sel.getNumArgs())
1379 NumNamedArgs = Method->param_size();
1380 // FIXME. This need be cleaned up.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001381 if (Args.size() < NumNamedArgs) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001382 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001383 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
Fariborz Jahanian60462092010-04-08 00:30:06 +00001384 return false;
1385 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001386
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001387 bool IsError = false;
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001388 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001389 // We can't do any type-checking on a type-dependent argument.
1390 if (Args[i]->isTypeDependent())
1391 continue;
1392
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001393 Expr *argExpr = Args[i];
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001394
Alp Toker03376dc2014-07-07 09:02:20 +00001395 ParmVarDecl *param = Method->parameters()[i];
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001396 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump11289f42009-09-09 15:08:12 +00001397
John McCall4124c492011-10-17 18:40:02 +00001398 // Strip the unbridged-cast placeholder expression off unless it's
1399 // a consumed argument.
1400 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1401 !param->hasAttr<CFConsumedAttr>())
1402 argExpr = stripARCUnbridgedCast(argExpr);
1403
John McCallea0a39e2012-11-14 00:49:39 +00001404 // If the parameter is __unknown_anytype, infer its type
1405 // from the argument.
1406 if (param->getType() == Context.UnknownAnyTy) {
John McCallcc5788c2013-03-04 07:34:02 +00001407 QualType paramType;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001408 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
John McCallcc5788c2013-03-04 07:34:02 +00001409 if (argE.isInvalid()) {
John McCallea0a39e2012-11-14 00:49:39 +00001410 IsError = true;
John McCallcc5788c2013-03-04 07:34:02 +00001411 } else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001412 Args[i] = argE.get();
John McCallea0a39e2012-11-14 00:49:39 +00001413
John McCallcc5788c2013-03-04 07:34:02 +00001414 // Update the parameter type in-place.
1415 param->setType(paramType);
1416 }
1417 continue;
John McCallea0a39e2012-11-14 00:49:39 +00001418 }
1419
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001420 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
John McCall4124c492011-10-17 18:40:02 +00001421 param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001422 diag::err_call_incomplete_argument, argExpr))
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001423 return true;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001424
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001425 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
John McCall4124c492011-10-17 18:40:02 +00001426 param);
Fariborz Jahaniana1db7df2014-07-31 17:39:50 +00001427 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001428 if (ArgE.isInvalid())
1429 IsError = true;
1430 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001431 Args[i] = ArgE.getAs<Expr>();
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001432 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001433
1434 // Promote additional arguments to variadic methods.
1435 if (Method->isVariadic()) {
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001436 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001437 if (Args[i]->isTypeDependent())
1438 continue;
1439
Jordy Roseaca01f92012-05-12 17:32:52 +00001440 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
Craig Topperc3ec1492014-05-26 06:22:03 +00001441 nullptr);
John Wiegley01296292011-04-08 18:41:53 +00001442 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001443 Args[i] = Arg.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001444 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001445 } else {
1446 // Check for extra arguments to non-variadic methods.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001447 if (Args.size() != NumNamedArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00001448 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001449 diag::err_typecheck_call_too_many_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001450 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001451 << Method->getSourceRange()
Chris Lattner3b054132008-11-19 05:08:23 +00001452 << SourceRange(Args[NumNamedArgs]->getLocStart(),
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001453 Args.back()->getLocEnd());
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001454 }
1455 }
1456
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001457 DiagnoseSentinelCalls(Method, SelLoc, Args);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001458
1459 // Do additional checkings on method.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001460 IsError |= CheckObjCMethodCall(
Robert Wilhelm88e02492013-08-19 07:57:02 +00001461 Method, SelLoc, makeArrayRef<const Expr *>(Args.data(), Args.size()));
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001462
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001463 return IsError;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001464}
1465
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001466bool Sema::isSelfExpr(Expr *RExpr) {
Fariborz Jahanianb3b1e172011-03-27 19:53:47 +00001467 // 'self' is objc 'self' in an objc method only.
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001468 ObjCMethodDecl *Method =
1469 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1470 return isSelfExpr(RExpr, Method);
1471}
1472
1473bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
John McCallfe96e0b2011-11-06 09:01:30 +00001474 if (!method) return false;
1475
John McCall31168b02011-06-15 23:02:42 +00001476 receiver = receiver->IgnoreParenLValueCasts();
1477 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCallfe96e0b2011-11-06 09:01:30 +00001478 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregor486b74e2011-09-27 16:10:05 +00001479 return true;
1480 return false;
Steve Naroff3f49fee2009-03-04 15:11:40 +00001481}
1482
John McCall526ab472011-10-25 17:37:35 +00001483/// LookupMethodInType - Look up a method in an ObjCObjectType.
1484ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1485 bool isInstance) {
1486 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1487 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1488 // Look it up in the main interface (and categories, etc.)
1489 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1490 return method;
1491
1492 // Okay, look for "private" methods declared in any
1493 // @implementations we've seen.
Anna Zaksc77a3b12012-07-27 19:07:44 +00001494 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1495 return method;
John McCall526ab472011-10-25 17:37:35 +00001496 }
1497
1498 // Check qualifiers.
Aaron Ballman1683f7b2014-03-17 15:55:30 +00001499 for (const auto *I : objType->quals())
1500 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
John McCall526ab472011-10-25 17:37:35 +00001501 return method;
1502
Craig Topperc3ec1492014-05-26 06:22:03 +00001503 return nullptr;
John McCall526ab472011-10-25 17:37:35 +00001504}
1505
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001506/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1507/// list of a qualified objective pointer type.
1508ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1509 const ObjCObjectPointerType *OPT,
1510 bool Instance)
1511{
Craig Topperc3ec1492014-05-26 06:22:03 +00001512 ObjCMethodDecl *MD = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +00001513 for (const auto *PROTO : OPT->quals()) {
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001514 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1515 return MD;
1516 }
1517 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001518 return nullptr;
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001519}
1520
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001521static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) {
1522 if (!Receiver)
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001523 return;
1524
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001525 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Receiver))
1526 Receiver = OVE->getSourceExpr();
1527
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001528 Expr *RExpr = Receiver->IgnoreParenImpCasts();
1529 SourceLocation Loc = RExpr->getLocStart();
1530 QualType T = RExpr->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00001531 const ObjCPropertyDecl *PDecl = nullptr;
1532 const ObjCMethodDecl *GDecl = nullptr;
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001533 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) {
1534 RExpr = POE->getSyntacticForm();
1535 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) {
1536 if (PRE->isImplicitProperty()) {
1537 GDecl = PRE->getImplicitPropertyGetter();
1538 if (GDecl) {
Alp Toker314cc812014-01-25 16:55:45 +00001539 T = GDecl->getReturnType();
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001540 }
1541 }
1542 else {
1543 PDecl = PRE->getExplicitProperty();
1544 if (PDecl) {
1545 T = PDecl->getType();
1546 }
1547 }
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001548 }
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001549 }
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001550 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RExpr)) {
1551 // See if receiver is a method which envokes a synthesized getter
1552 // backing a 'weak' property.
1553 ObjCMethodDecl *Method = ME->getMethodDecl();
Jordan Rose2bd991a2012-10-10 16:42:54 +00001554 if (Method && Method->getSelector().getNumArgs() == 0) {
1555 PDecl = Method->findPropertyDecl();
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001556 if (PDecl)
1557 T = PDecl->getType();
1558 }
1559 }
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001560
Jordan Rose13d6b712012-09-28 22:21:42 +00001561 if (T.getObjCLifetime() != Qualifiers::OCL_Weak) {
1562 if (!PDecl)
1563 return;
1564 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak))
1565 return;
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001566 }
Jordan Rose13d6b712012-09-28 22:21:42 +00001567
1568 S.Diag(Loc, diag::warn_receiver_is_weak)
1569 << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2));
1570
1571 if (PDecl)
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001572 S.Diag(PDecl->getLocation(), diag::note_property_declare);
Jordan Rose13d6b712012-09-28 22:21:42 +00001573 else if (GDecl)
1574 S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl;
1575
1576 S.Diag(Loc, diag::note_arc_assign_to_strong);
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001577}
1578
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001579/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1580/// objective C interface. This is a property reference expression.
John McCalldadc5752010-08-24 06:29:42 +00001581ExprResult Sema::
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001582HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001583 Expr *BaseExpr, SourceLocation OpLoc,
1584 DeclarationName MemberName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001585 SourceLocation MemberLoc,
1586 SourceLocation SuperLoc, QualType SuperType,
1587 bool Super) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001588 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1589 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00001590
Benjamin Kramer365082d2012-05-19 16:34:46 +00001591 if (!MemberName.isIdentifier()) {
Douglas Gregord6459312011-04-20 18:19:55 +00001592 Diag(MemberLoc, diag::err_invalid_property_name)
1593 << MemberName << QualType(OPT, 0);
1594 return ExprError();
1595 }
Benjamin Kramer365082d2012-05-19 16:34:46 +00001596
1597 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregord6459312011-04-20 18:19:55 +00001598
Douglas Gregor4123a862011-11-14 22:10:01 +00001599 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1600 : BaseExpr->getSourceRange();
1601 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001602 diag::err_property_not_found_forward_class,
1603 MemberName, BaseRange))
Fariborz Jahanian7cabbe02010-12-16 00:56:28 +00001604 return ExprError();
Douglas Gregor4123a862011-11-14 22:10:01 +00001605
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001606 // Search for a declared property first.
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001607 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001608 // Check whether we can reference this property.
1609 if (DiagnoseUseOfDecl(PD, MemberLoc))
1610 return ExprError();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001611 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001612 return new (Context)
1613 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1614 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001615 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001616 return new (Context)
1617 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1618 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001619 }
1620 // Check protocols on qualified interfaces.
Aaron Ballman83731462014-03-17 16:14:00 +00001621 for (const auto *I : OPT->quals())
1622 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001623 // Check whether we can reference this property.
1624 if (DiagnoseUseOfDecl(PD, MemberLoc))
1625 return ExprError();
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001626
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001627 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001628 return new (Context) ObjCPropertyRefExpr(
1629 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
1630 SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001631 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001632 return new (Context)
1633 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1634 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001635 }
1636 // If that failed, look for an "implicit" property by seeing if the nullary
1637 // selector is implemented.
1638
1639 // FIXME: The logic for looking up nullary and unary selectors should be
1640 // shared with the code in ActOnInstanceMessage.
1641
1642 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1643 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001644
1645 // May be founf in property's qualified list.
1646 if (!Getter)
1647 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001648
1649 // If this reference is in an @implementation, check for 'private' methods.
1650 if (!Getter)
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001651 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001652
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001653 if (Getter) {
1654 // Check if we can reference this property.
1655 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1656 return ExprError();
1657 }
1658 // If we found a getter then this may be a valid dot-reference, we
1659 // will look for the matching setter, in case it is needed.
1660 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001661 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1662 PP.getSelectorTable(), Member);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001663 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001664
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001665 // May be founf in property's qualified list.
1666 if (!Setter)
1667 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1668
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001669 if (!Setter) {
1670 // If this reference is in an @implementation, also check for 'private'
1671 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001672 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001673 }
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001674
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001675 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1676 return ExprError();
1677
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001678 if (Getter || Setter) {
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001679 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001680 return new (Context)
1681 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1682 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001683 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001684 return new (Context)
1685 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1686 OK_ObjCProperty, MemberLoc, BaseExpr);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001687
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001688 }
1689
1690 // Attempt to correct for typos in property names.
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001691 DeclFilterCCC<ObjCPropertyDecl> Validator;
1692 if (TypoCorrection Corrected = CorrectTypo(
Craig Topperc3ec1492014-05-26 06:22:03 +00001693 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName,
1694 nullptr, nullptr, Validator, CTK_ErrorRecovery, IFace, false, OPT)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001695 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1696 << MemberName << QualType(OPT, 0));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001697 DeclarationName TypoResult = Corrected.getCorrection();
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001698 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1699 TypoResult, MemberLoc,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001700 SuperLoc, SuperType, Super);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001701 }
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001702 ObjCInterfaceDecl *ClassDeclared;
1703 if (ObjCIvarDecl *Ivar =
1704 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1705 QualType T = Ivar->getType();
1706 if (const ObjCObjectPointerType * OBJPT =
1707 T->getAsObjCInterfacePointerType()) {
Douglas Gregor4123a862011-11-14 22:10:01 +00001708 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001709 diag::err_property_not_as_forward_class,
1710 MemberName, BaseExpr))
Douglas Gregor4123a862011-11-14 22:10:01 +00001711 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001712 }
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001713 Diag(MemberLoc,
1714 diag::err_ivar_access_using_property_syntax_suggest)
1715 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1716 << FixItHint::CreateReplacement(OpLoc, "->");
1717 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001718 }
Chris Lattner90c58fa2010-04-11 07:51:10 +00001719
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001720 Diag(MemberLoc, diag::err_property_not_found)
1721 << MemberName << QualType(OPT, 0);
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001722 if (Setter)
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001723 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001724 << MemberName << BaseExpr->getSourceRange();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001725 return ExprError();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001726}
1727
1728
1729
John McCalldadc5752010-08-24 06:29:42 +00001730ExprResult Sema::
Chris Lattnera36ec422010-04-11 08:28:14 +00001731ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1732 IdentifierInfo &propertyName,
1733 SourceLocation receiverNameLoc,
1734 SourceLocation propertyNameLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00001735
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001736 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001737 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1738 receiverNameLoc);
Douglas Gregor33823722011-06-11 01:09:30 +00001739
1740 bool IsSuper = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00001741 if (!IFace) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001742 // If the "receiver" is 'super' in a method, handle it as an expression-like
1743 // property reference.
John McCall5f2d5562011-02-03 09:00:02 +00001744 if (receiverNamePtr->isStr("super")) {
Douglas Gregor33823722011-06-11 01:09:30 +00001745 IsSuper = true;
1746
Eli Friedman24af8502012-02-03 22:47:37 +00001747 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001748 if (CurMethod->isInstanceMethod()) {
Fariborz Jahanian05e2aaa2013-03-11 22:26:33 +00001749 ObjCInterfaceDecl *Super =
1750 CurMethod->getClassInterface()->getSuperClass();
1751 if (!Super) {
1752 // The current class does not have a superclass.
1753 Diag(receiverNameLoc, diag::error_root_class_cannot_use_super)
1754 << CurMethod->getClassInterface()->getIdentifier();
1755 return ExprError();
1756 }
1757 QualType T = Context.getObjCInterfaceType(Super);
Chris Lattnera36ec422010-04-11 08:28:14 +00001758 T = Context.getObjCObjectPointerType(T);
Craig Topperc3ec1492014-05-26 06:22:03 +00001759
Chris Lattnera36ec422010-04-11 08:28:14 +00001760 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001761 /*BaseExpr*/nullptr,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001762 SourceLocation()/*OpLoc*/,
1763 &propertyName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001764 propertyNameLoc,
1765 receiverNameLoc, T, true);
Chris Lattnera36ec422010-04-11 08:28:14 +00001766 }
Mike Stump11289f42009-09-09 15:08:12 +00001767
Chris Lattnera36ec422010-04-11 08:28:14 +00001768 // Otherwise, if this is a class method, try dispatching to our
1769 // superclass.
1770 IFace = CurMethod->getClassInterface()->getSuperClass();
1771 }
John McCall5f2d5562011-02-03 09:00:02 +00001772 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001773
1774 if (!IFace) {
Alp Tokerec543272013-12-24 09:48:30 +00001775 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
1776 << tok::l_paren;
Chris Lattnera36ec422010-04-11 08:28:14 +00001777 return ExprError();
1778 }
1779 }
1780
1781 // Search for a declared property first.
Steve Naroff9527bbf2009-03-09 21:12:44 +00001782 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001783 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001784
1785 // If this reference is in an @implementation, check for 'private' methods.
1786 if (!Getter)
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001787 Getter = IFace->lookupPrivateClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001788
1789 if (Getter) {
1790 // FIXME: refactor/share with ActOnMemberReference().
1791 // Check if we can reference this property.
1792 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1793 return ExprError();
1794 }
Mike Stump11289f42009-09-09 15:08:12 +00001795
Steve Naroff9527bbf2009-03-09 21:12:44 +00001796 // Look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00001797 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001798 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1799 PP.getSelectorTable(),
1800 &propertyName);
Mike Stump11289f42009-09-09 15:08:12 +00001801
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001802 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001803 if (!Setter) {
1804 // If this reference is in an @implementation, also check for 'private'
1805 // methods.
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001806 Setter = IFace->lookupPrivateClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001807 }
1808 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00001809 if (!Setter)
1810 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001811
1812 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1813 return ExprError();
1814
1815 if (Getter || Setter) {
Douglas Gregor33823722011-06-11 01:09:30 +00001816 if (IsSuper)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001817 return new (Context)
1818 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1819 OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
1820 Context.getObjCInterfaceType(IFace));
Douglas Gregor33823722011-06-11 01:09:30 +00001821
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001822 return new (Context) ObjCPropertyRefExpr(
1823 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
1824 propertyNameLoc, receiverNameLoc, IFace);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001825 }
1826 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1827 << &propertyName << Context.getObjCInterfaceType(IFace));
1828}
1829
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001830namespace {
1831
1832class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1833 public:
1834 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1835 // Determine whether "super" is acceptable in the current context.
1836 if (Method && Method->getClassInterface())
1837 WantObjCSuper = Method->getClassInterface()->getSuperClass();
1838 }
1839
Craig Toppere14c0f82014-03-12 04:55:44 +00001840 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001841 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1842 candidate.isKeyword("super");
1843 }
1844};
1845
1846}
1847
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001848Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001849 IdentifierInfo *Name,
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001850 SourceLocation NameLoc,
1851 bool IsSuper,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001852 bool HasTrailingDot,
John McCallba7bf592010-08-24 05:47:05 +00001853 ParsedType &ReceiverType) {
1854 ReceiverType = ParsedType();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001855
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001856 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor57756ea2010-10-14 22:11:03 +00001857 // messaging super. If the identifier is "super" and there is a
1858 // trailing dot, it's an instance message.
1859 if (IsSuper && S->isInObjcMethodScope())
1860 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001861
1862 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1863 LookupName(Result, S);
1864
1865 switch (Result.getResultKind()) {
1866 case LookupResult::NotFound:
Douglas Gregorca7136b2010-04-19 20:09:36 +00001867 // Normal name lookup didn't find anything. If we're in an
1868 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor57756ea2010-10-14 22:11:03 +00001869 // FIXME: This is a hack. Ivar lookup should be part of normal
1870 // lookup.
Douglas Gregorca7136b2010-04-19 20:09:36 +00001871 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidis3a8de5b2011-11-09 00:22:48 +00001872 if (!Method->getClassInterface()) {
1873 // Fall back: let the parser try to parse it as an instance message.
1874 return ObjCInstanceMessage;
1875 }
1876
Douglas Gregorca7136b2010-04-19 20:09:36 +00001877 ObjCInterfaceDecl *ClassDeclared;
1878 if (Method->getClassInterface()->lookupInstanceVariable(Name,
1879 ClassDeclared))
1880 return ObjCInstanceMessage;
1881 }
Douglas Gregor57756ea2010-10-14 22:11:03 +00001882
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001883 // Break out; we'll perform typo correction below.
1884 break;
1885
1886 case LookupResult::NotFoundInCurrentInstantiation:
1887 case LookupResult::FoundOverloaded:
1888 case LookupResult::FoundUnresolvedValue:
1889 case LookupResult::Ambiguous:
1890 Result.suppressDiagnostics();
1891 return ObjCInstanceMessage;
1892
1893 case LookupResult::Found: {
Fariborz Jahanian14889fc2011-02-08 00:23:07 +00001894 // If the identifier is a class or not, and there is a trailing dot,
1895 // it's an instance message.
1896 if (HasTrailingDot)
1897 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001898 // We found something. If it's a type, then we have a class
1899 // message. Otherwise, it's an instance message.
1900 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001901 QualType T;
1902 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1903 T = Context.getObjCInterfaceType(Class);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001904 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
Douglas Gregore5798dc2010-04-21 20:38:13 +00001905 T = Context.getTypeDeclType(Type);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001906 DiagnoseUseOfDecl(Type, NameLoc);
1907 }
1908 else
Douglas Gregore5798dc2010-04-21 20:38:13 +00001909 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001910
Douglas Gregore5798dc2010-04-21 20:38:13 +00001911 // We have a class message, and T is the type we're
1912 // messaging. Build source-location information for it.
1913 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +00001914 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregore5798dc2010-04-21 20:38:13 +00001915 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001916 }
1917 }
1918
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001919 ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00001920 if (TypoCorrection Corrected =
1921 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
Craig Topperc3ec1492014-05-26 06:22:03 +00001922 nullptr, Validator, CTK_ErrorRecovery, nullptr, false,
1923 nullptr, false)) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001924 if (Corrected.isKeyword()) {
1925 // If we've found the keyword "super" (the only keyword that would be
1926 // returned by CorrectTypo), this is a send to super.
Richard Smithf9b15102013-08-17 00:46:16 +00001927 diagnoseTypo(Corrected,
1928 PDiag(diag::err_unknown_receiver_suggest) << Name);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001929 return ObjCSuperMessage;
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001930 } else if (ObjCInterfaceDecl *Class =
Richard Smithf9b15102013-08-17 00:46:16 +00001931 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001932 // If we found a declaration, correct when it refers to an Objective-C
1933 // class.
Richard Smithf9b15102013-08-17 00:46:16 +00001934 diagnoseTypo(Corrected,
1935 PDiag(diag::err_unknown_receiver_suggest) << Name);
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001936 QualType T = Context.getObjCInterfaceType(Class);
1937 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1938 ReceiverType = CreateParsedType(T, TSInfo);
1939 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001940 }
1941 }
Richard Smithf9b15102013-08-17 00:46:16 +00001942
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001943 // Fall back: let the parser try to parse it as an instance message.
1944 return ObjCInstanceMessage;
1945}
Steve Naroff9527bbf2009-03-09 21:12:44 +00001946
John McCalldadc5752010-08-24 06:29:42 +00001947ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001948 SourceLocation SuperLoc,
1949 Selector Sel,
1950 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00001951 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001952 SourceLocation RBracLoc,
1953 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001954 // Determine whether we are inside a method or not.
Eli Friedman24af8502012-02-03 22:47:37 +00001955 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregor4fdba132010-04-21 20:01:04 +00001956 if (!Method) {
1957 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1958 return ExprError();
1959 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001960
Douglas Gregor4fdba132010-04-21 20:01:04 +00001961 ObjCInterfaceDecl *Class = Method->getClassInterface();
1962 if (!Class) {
1963 Diag(SuperLoc, diag::error_no_super_class_message)
1964 << Method->getDeclName();
1965 return ExprError();
1966 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001967
Douglas Gregor4fdba132010-04-21 20:01:04 +00001968 ObjCInterfaceDecl *Super = Class->getSuperClass();
1969 if (!Super) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001970 // The current class does not have a superclass.
Ted Kremenek499897b2011-01-23 17:21:34 +00001971 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
1972 << Class->getIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001973 return ExprError();
Chris Lattnerc2ebb032010-04-12 05:38:43 +00001974 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001975
Douglas Gregor4fdba132010-04-21 20:01:04 +00001976 // We are in a method whose class has a superclass, so 'super'
1977 // is acting as a keyword.
Jordan Rose2afd6612012-10-19 16:05:26 +00001978 if (Method->getSelector() == Sel)
1979 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber715abaf2011-08-22 17:25:57 +00001980
Jordan Rose2afd6612012-10-19 16:05:26 +00001981 if (Method->isInstanceMethod()) {
Douglas Gregor4fdba132010-04-21 20:01:04 +00001982 // Since we are in an instance method, this is an instance
1983 // message to the superclass instance.
1984 QualType SuperTy = Context.getObjCInterfaceType(Super);
1985 SuperTy = Context.getObjCObjectPointerType(SuperTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00001986 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
1987 Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001988 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001989 }
Douglas Gregor4fdba132010-04-21 20:01:04 +00001990
1991 // Since we are in a class method, this is a class message to
1992 // the superclass.
Craig Topperc3ec1492014-05-26 06:22:03 +00001993 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
Douglas Gregor4fdba132010-04-21 20:01:04 +00001994 Context.getObjCInterfaceType(Super),
Craig Topperc3ec1492014-05-26 06:22:03 +00001995 SuperLoc, Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001996 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001997}
1998
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001999
2000ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
2001 bool isSuperReceiver,
2002 SourceLocation Loc,
2003 Selector Sel,
2004 ObjCMethodDecl *Method,
2005 MultiExprArg Args) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002006 TypeSourceInfo *receiverTypeInfo = nullptr;
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002007 if (!ReceiverType.isNull())
2008 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
2009
2010 return BuildClassMessage(receiverTypeInfo, ReceiverType,
2011 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
2012 Sel, Method, Loc, Loc, Loc, Args,
2013 /*isImplicit=*/true);
2014
2015}
2016
Ted Kremeneke65b0862012-03-06 20:05:56 +00002017static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2018 unsigned DiagID,
2019 bool (*refactor)(const ObjCMessageExpr *,
2020 const NSAPI &, edit::Commit &)) {
2021 SourceLocation MsgLoc = Msg->getExprLoc();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002022 if (S.Diags.isIgnored(DiagID, MsgLoc))
Ted Kremeneke65b0862012-03-06 20:05:56 +00002023 return;
2024
2025 SourceManager &SM = S.SourceMgr;
2026 edit::Commit ECommit(SM, S.LangOpts);
2027 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2028 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2029 << Msg->getSelector() << Msg->getSourceRange();
2030 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2031 if (!ECommit.isCommitable())
2032 return;
2033 for (edit::Commit::edit_iterator
2034 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2035 const edit::Commit::Edit &Edit = *I;
2036 switch (Edit.Kind) {
2037 case edit::Commit::Act_Insert:
2038 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2039 Edit.Text,
2040 Edit.BeforePrev));
2041 break;
2042 case edit::Commit::Act_InsertFromRange:
2043 Builder.AddFixItHint(
2044 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2045 Edit.getInsertFromRange(SM),
2046 Edit.BeforePrev));
2047 break;
2048 case edit::Commit::Act_Remove:
2049 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2050 break;
2051 }
2052 }
2053 }
2054}
2055
2056static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2057 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2058 edit::rewriteObjCRedundantCallWithLiteral);
2059}
2060
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002061/// \brief Build an Objective-C class message expression.
2062///
2063/// This routine takes care of both normal class messages and
2064/// class messages to the superclass.
2065///
2066/// \param ReceiverTypeInfo Type source information that describes the
2067/// receiver of this message. This may be NULL, in which case we are
2068/// sending to the superclass and \p SuperLoc must be a valid source
2069/// location.
2070
2071/// \param ReceiverType The type of the object receiving the
2072/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2073/// type as that refers to. For a superclass send, this is the type of
2074/// the superclass.
2075///
2076/// \param SuperLoc The location of the "super" keyword in a
2077/// superclass message.
2078///
2079/// \param Sel The selector to which the message is being sent.
2080///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002081/// \param Method The method that this class message is invoking, if
2082/// already known.
2083///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002084/// \param LBracLoc The location of the opening square bracket ']'.
2085///
James Dennettffad8b72012-06-22 08:10:18 +00002086/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002087///
James Dennettffad8b72012-06-22 08:10:18 +00002088/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002089ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002090 QualType ReceiverType,
2091 SourceLocation SuperLoc,
2092 Selector Sel,
2093 ObjCMethodDecl *Method,
2094 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002095 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002096 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002097 MultiExprArg ArgsIn,
2098 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002099 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00002100 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002101 if (LBracLoc.isInvalid()) {
2102 Diag(Loc, diag::err_missing_open_square_message_send)
2103 << FixItHint::CreateInsertion(Loc, "[");
2104 LBracLoc = Loc;
2105 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002106 SourceLocation SelLoc;
2107 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2108 SelLoc = SelectorLocs.front();
2109 else
2110 SelLoc = Loc;
2111
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002112 if (ReceiverType->isDependentType()) {
2113 // If the receiver type is dependent, we can't type-check anything
2114 // at this point. Build a dependent expression.
2115 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002116 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002117 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002118 return ObjCMessageExpr::Create(
2119 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
2120 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2121 isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002122 }
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002123
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002124 // Find the class to which we are sending this message.
Craig Topperc3ec1492014-05-26 06:22:03 +00002125 ObjCInterfaceDecl *Class = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00002126 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2127 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002128 Diag(Loc, diag::err_invalid_receiver_class_message)
2129 << ReceiverType;
2130 return ExprError();
Steve Naroffe2177fb2008-07-25 19:39:00 +00002131 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002132 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanianc27cd1b2011-10-15 19:18:36 +00002133 // objc++ diagnoses during typename annotation.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002134 if (!getLangOpts().CPlusPlus)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002135 (void)DiagnoseUseOfDecl(Class, SelLoc);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002136 // Find the method we are messaging.
Douglas Gregorb5186b12010-04-22 17:01:48 +00002137 if (!Method) {
Douglas Gregor4123a862011-11-14 22:10:01 +00002138 SourceRange TypeRange
2139 = SuperLoc.isValid()? SourceRange(SuperLoc)
2140 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002141 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002142 (getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002143 ? diag::err_arc_receiver_forward_class
2144 : diag::warn_receiver_forward_class),
2145 TypeRange)) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002146 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorb5186b12010-04-22 17:01:48 +00002147 Method = LookupFactoryMethodInGlobalPool(Sel,
2148 SourceRange(LBracLoc, RBracLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00002149 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002150 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2151 << Method->getDeclName();
2152 }
2153 if (!Method)
2154 Method = Class->lookupClassMethod(Sel);
2155
2156 // If we have an implementation in scope, check "private" methods.
2157 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002158 Method = Class->lookupPrivateClassMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002159
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002160 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002161 return ExprError();
Fariborz Jahanian1bd844d2009-05-08 23:02:36 +00002162 }
Mike Stump11289f42009-09-09 15:08:12 +00002163
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002164 // Check the argument types and determine the result type.
2165 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002166 ExprValueKind VK = VK_RValue;
2167
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002168 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002169 Expr **Args = ArgsIn.data();
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002170 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2171 Sel, SelectorLocs,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00002172 Method, true,
Douglas Gregor33823722011-06-11 01:09:30 +00002173 SuperLoc.isValid(), LBracLoc, RBracLoc,
2174 ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002175 return ExprError();
Ted Kremeneka3a37ae2008-06-24 15:50:53 +00002176
Alp Toker314cc812014-01-25 16:55:45 +00002177 if (Method && !Method->getReturnType()->isVoidType() &&
2178 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002179 diag::err_illegal_message_expr_incomplete_type))
2180 return ExprError();
2181
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002182 // Construct the appropriate ObjCMessageExpr.
Ted Kremeneke65b0862012-03-06 20:05:56 +00002183 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002184 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002185 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002186 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002187 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002188 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002189 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002190 else {
John McCall7decc9e2010-11-18 06:31:45 +00002191 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002192 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002193 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002194 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002195 if (!isImplicit)
2196 checkCocoaAPI(*this, Result);
2197 }
Douglas Gregoraae38d62010-05-22 05:17:18 +00002198 return MaybeBindToTemporary(Result);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002199}
2200
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002201// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002202// ArgExprs is optional - if it is present, the number of expressions
2203// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002204ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor3e972002010-09-15 23:19:31 +00002205 ParsedType Receiver,
2206 Selector Sel,
2207 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002208 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor3e972002010-09-15 23:19:31 +00002209 SourceLocation RBracLoc,
2210 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002211 TypeSourceInfo *ReceiverTypeInfo;
2212 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2213 if (ReceiverType.isNull())
2214 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002215
Mike Stump11289f42009-09-09 15:08:12 +00002216
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002217 if (!ReceiverTypeInfo)
2218 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2219
2220 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002221 /*SuperLoc=*/SourceLocation(), Sel,
2222 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2223 Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002224}
2225
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002226ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2227 QualType ReceiverType,
2228 SourceLocation Loc,
2229 Selector Sel,
2230 ObjCMethodDecl *Method,
2231 MultiExprArg Args) {
2232 return BuildInstanceMessage(Receiver, ReceiverType,
2233 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2234 Sel, Method, Loc, Loc, Loc, Args,
2235 /*isImplicit=*/true);
2236}
2237
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002238/// \brief Build an Objective-C instance message expression.
2239///
2240/// This routine takes care of both normal instance messages and
2241/// instance messages to the superclass instance.
2242///
2243/// \param Receiver The expression that computes the object that will
2244/// receive this message. This may be empty, in which case we are
2245/// sending to the superclass instance and \p SuperLoc must be a valid
2246/// source location.
2247///
2248/// \param ReceiverType The (static) type of the object receiving the
2249/// message. When a \p Receiver expression is provided, this is the
2250/// same type as that expression. For a superclass instance send, this
2251/// is a pointer to the type of the superclass.
2252///
2253/// \param SuperLoc The location of the "super" keyword in a
2254/// superclass instance message.
2255///
2256/// \param Sel The selector to which the message is being sent.
2257///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002258/// \param Method The method that this instance message is invoking, if
2259/// already known.
2260///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002261/// \param LBracLoc The location of the opening square bracket ']'.
2262///
James Dennettffad8b72012-06-22 08:10:18 +00002263/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002264///
James Dennettffad8b72012-06-22 08:10:18 +00002265/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002266ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002267 QualType ReceiverType,
2268 SourceLocation SuperLoc,
2269 Selector Sel,
2270 ObjCMethodDecl *Method,
2271 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002272 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002273 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002274 MultiExprArg ArgsIn,
2275 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002276 // The location of the receiver.
2277 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002278 SourceRange RecRange =
2279 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2280 SourceLocation SelLoc;
2281 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2282 SelLoc = SelectorLocs.front();
2283 else
2284 SelLoc = Loc;
2285
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002286 if (LBracLoc.isInvalid()) {
2287 Diag(Loc, diag::err_missing_open_square_message_send)
2288 << FixItHint::CreateInsertion(Loc, "[");
2289 LBracLoc = Loc;
2290 }
2291
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002292 // If we have a receiver expression, perform appropriate promotions
2293 // and determine receiver type.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002294 if (Receiver) {
John McCall4124c492011-10-17 18:40:02 +00002295 if (Receiver->hasPlaceholderType()) {
Douglas Gregord8fb1e32011-12-01 01:37:36 +00002296 ExprResult Result;
2297 if (Receiver->getType() == Context.UnknownAnyTy)
2298 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2299 else
2300 Result = CheckPlaceholderExpr(Receiver);
2301 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002302 Receiver = Result.get();
John McCall4124c492011-10-17 18:40:02 +00002303 }
2304
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002305 if (Receiver->isTypeDependent()) {
2306 // If the receiver is type-dependent, we can't type-check anything
2307 // at this point. Build a dependent expression.
2308 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002309 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002310 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002311 return ObjCMessageExpr::Create(
2312 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
2313 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2314 RBracLoc, isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002315 }
2316
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002317 // If necessary, apply function/array conversion to the receiver.
2318 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00002319 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2320 if (Result.isInvalid())
2321 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002322 Receiver = Result.get();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002323 ReceiverType = Receiver->getType();
John McCall80c93a02013-03-01 09:20:14 +00002324
2325 // If the receiver is an ObjC pointer, a block pointer, or an
2326 // __attribute__((NSObject)) pointer, we don't need to do any
2327 // special conversion in order to look up a receiver.
2328 if (ReceiverType->isObjCRetainableType()) {
2329 // do nothing
2330 } else if (!getLangOpts().ObjCAutoRefCount &&
2331 !Context.getObjCIdType().isNull() &&
2332 (ReceiverType->isPointerType() ||
2333 ReceiverType->isIntegerType())) {
2334 // Implicitly convert integers and pointers to 'id' but emit a warning.
2335 // But not in ARC.
2336 Diag(Loc, diag::warn_bad_receiver_type)
2337 << ReceiverType
2338 << Receiver->getSourceRange();
2339 if (ReceiverType->isPointerType()) {
2340 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002341 CK_CPointerToObjCPointerCast).get();
John McCall80c93a02013-03-01 09:20:14 +00002342 } else {
2343 // TODO: specialized warning on null receivers?
2344 bool IsNull = Receiver->isNullPointerConstant(Context,
2345 Expr::NPC_ValueDependentIsNull);
2346 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2347 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002348 Kind).get();
John McCall80c93a02013-03-01 09:20:14 +00002349 }
2350 ReceiverType = Receiver->getType();
2351 } else if (getLangOpts().CPlusPlus) {
Douglas Gregor4b60a152013-11-07 22:34:54 +00002352 // The receiver must be a complete type.
2353 if (RequireCompleteType(Loc, Receiver->getType(),
2354 diag::err_incomplete_receiver_type))
2355 return ExprError();
2356
John McCall80c93a02013-03-01 09:20:14 +00002357 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2358 if (result.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002359 Receiver = result.get();
John McCall80c93a02013-03-01 09:20:14 +00002360 ReceiverType = Receiver->getType();
2361 }
2362 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002363 }
2364
John McCall80c93a02013-03-01 09:20:14 +00002365 // There's a somewhat weird interaction here where we assume that we
2366 // won't actually have a method unless we also don't need to do some
2367 // of the more detailed type-checking on the receiver.
2368
Douglas Gregorb5186b12010-04-22 17:01:48 +00002369 if (!Method) {
2370 // Handle messages to id.
Fariborz Jahanian32e59ba2010-08-10 18:10:50 +00002371 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002372 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002373 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2374 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002375 SourceRange(LBracLoc, RBracLoc),
2376 receiverIsId);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002377 if (!Method)
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002378 Method = LookupFactoryMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002379 SourceRange(LBracLoc,RBracLoc),
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002380 receiverIsId);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002381 } else if (ReceiverType->isObjCClassType() ||
2382 ReceiverType->isObjCQualifiedClassType()) {
2383 // Handle messages to Class.
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002384 // We allow sending a message to a qualified Class ("Class<foo>"), which
2385 // is ok as long as one of the protocols implements the selector (if not, warn).
2386 if (const ObjCObjectPointerType *QClassTy
2387 = ReceiverType->getAsObjCQualifiedClassType()) {
2388 // Search protocols for class methods.
2389 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2390 if (!Method) {
2391 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2392 // warn if instance method found for a Class message.
2393 if (Method) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002394 Diag(SelLoc, diag::warn_instance_method_on_class_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002395 << Method->getSelector() << Sel;
Ted Kremenek59b10db2012-02-27 22:55:11 +00002396 Diag(Method->getLocation(), diag::note_method_declared_at)
2397 << Method->getDeclName();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002398 }
Steve Naroff3f49fee2009-03-04 15:11:40 +00002399 }
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002400 } else {
2401 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2402 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2403 // First check the public methods in the class interface.
2404 Method = ClassDecl->lookupClassMethod(Sel);
2405
2406 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002407 Method = ClassDecl->lookupPrivateClassMethod(Sel);
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002408 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002409 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002410 return ExprError();
2411 }
2412 if (!Method) {
2413 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregor486b74e2011-09-27 16:10:05 +00002414 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002415 Method = LookupFactoryMethodInGlobalPool(Sel,
2416 SourceRange(LBracLoc, RBracLoc),
2417 true);
2418 if (!Method) {
2419 // If no class (factory) method was found, check if an _instance_
2420 // method of the same name exists in the root class only.
2421 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002422 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002423 true);
2424 if (Method)
2425 if (const ObjCInterfaceDecl *ID =
2426 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2427 if (ID->getSuperClass())
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002428 Diag(SelLoc, diag::warn_root_inst_method_not_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002429 << Sel << SourceRange(LBracLoc, RBracLoc);
2430 }
2431 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002432 }
2433 }
2434 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002435 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00002436 ObjCInterfaceDecl *ClassDecl = nullptr;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002437
2438 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2439 // long as one of the protocols implements the selector (if not, warn).
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002440 // And as long as message is not deprecated/unavailable (warn if it is).
Douglas Gregorb5186b12010-04-22 17:01:48 +00002441 if (const ObjCObjectPointerType *QIdTy
2442 = ReceiverType->getAsObjCQualifiedIdType()) {
2443 // Search protocols for instance methods.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002444 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2445 if (!Method)
2446 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002447 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002448 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002449 } else if (const ObjCObjectPointerType *OCIType
2450 = ReceiverType->getAsObjCInterfacePointerType()) {
2451 // We allow sending a message to a pointer to an interface (an object).
2452 ClassDecl = OCIType->getInterfaceDecl();
John McCall31168b02011-06-15 23:02:42 +00002453
Douglas Gregor4123a862011-11-14 22:10:01 +00002454 // Try to complete the type. Under ARC, this is a hard error from which
2455 // we don't try to recover.
Craig Topperc3ec1492014-05-26 06:22:03 +00002456 const ObjCInterfaceDecl *forwardClass = nullptr;
Douglas Gregor4123a862011-11-14 22:10:01 +00002457 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002458 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002459 ? diag::err_arc_receiver_forward_instance
2460 : diag::warn_receiver_forward_instance,
2461 Receiver? Receiver->getSourceRange()
2462 : SourceRange(SuperLoc))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002463 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregor4123a862011-11-14 22:10:01 +00002464 return ExprError();
2465
2466 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanianc934de62012-02-03 01:02:44 +00002467 Diag(Receiver ? Receiver->getLocStart()
2468 : SuperLoc, diag::note_receiver_is_id);
Craig Topperc3ec1492014-05-26 06:22:03 +00002469 Method = nullptr;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002470 } else {
2471 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCall31168b02011-06-15 23:02:42 +00002472 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002473
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002474 if (!Method)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002475 // Search protocol qualifiers.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002476 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2477
Douglas Gregorb5186b12010-04-22 17:01:48 +00002478 if (!Method) {
2479 // If we have implementations in scope, check "private" methods.
Anna Zaksc77a3b12012-07-27 19:07:44 +00002480 Method = ClassDecl->lookupPrivateMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002481
David Blaikiebbafb8a2012-03-11 07:00:24 +00002482 if (!Method && getLangOpts().ObjCAutoRefCount) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002483 Diag(SelLoc, diag::err_arc_may_not_respond)
2484 << OCIType->getPointeeType() << Sel << RecRange
Fariborz Jahanian32c13502012-11-28 01:27:44 +00002485 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
John McCall31168b02011-06-15 23:02:42 +00002486 return ExprError();
2487 }
2488
Douglas Gregor486b74e2011-09-27 16:10:05 +00002489 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002490 // If we still haven't found a method, look in the global pool. This
2491 // behavior isn't very desirable, however we need it for GCC
2492 // compatibility. FIXME: should we deviate??
2493 if (OCIType->qual_empty()) {
2494 Method = LookupInstanceMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002495 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +00002496 if (Method && !forwardClass)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002497 Diag(SelLoc, diag::warn_maynot_respond)
2498 << OCIType->getInterfaceDecl()->getIdentifier()
2499 << Sel << RecRange;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002500 }
2501 }
2502 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002503 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002504 return ExprError();
John McCallfec112d2011-09-09 06:11:02 +00002505 } else {
John McCall80c93a02013-03-01 09:20:14 +00002506 // Reject other random receiver types (e.g. structs).
2507 Diag(Loc, diag::err_bad_receiver_type)
2508 << ReceiverType << Receiver->getSourceRange();
2509 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002510 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002511 }
Chris Lattner6b946cc2008-07-21 05:57:44 +00002512 }
Mike Stump11289f42009-09-09 15:08:12 +00002513
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002514 FunctionScopeInfo *DIFunctionScopeInfo =
2515 (Method && Method->getMethodFamily() == OMF_init)
Craig Topperc3ec1492014-05-26 06:22:03 +00002516 ? getEnclosingFunction() : nullptr;
2517
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002518 if (DIFunctionScopeInfo &&
2519 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002520 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2521 bool isDesignatedInitChain = false;
2522 if (SuperLoc.isValid()) {
2523 if (const ObjCObjectPointerType *
2524 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2525 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
Argyrios Kyrtzidisd664a342013-12-13 03:48:17 +00002526 // Either we know this is a designated initializer or we
2527 // conservatively assume it because we don't know for sure.
2528 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2529 ID->isDesignatedInitializer(Sel)) {
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002530 isDesignatedInitChain = true;
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002531 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002532 }
2533 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002534 }
2535 }
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002536 if (!isDesignatedInitChain) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002537 const ObjCMethodDecl *InitMethod = nullptr;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002538 bool isDesignated =
2539 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2540 assert(isDesignated && InitMethod);
2541 (void)isDesignated;
2542 Diag(SelLoc, SuperLoc.isValid() ?
2543 diag::warn_objc_designated_init_non_designated_init_call :
2544 diag::warn_objc_designated_init_non_super_designated_init_call);
2545 Diag(InitMethod->getLocation(),
2546 diag::note_objc_designated_init_marked_here);
2547 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002548 }
2549
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002550 if (DIFunctionScopeInfo &&
2551 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002552 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2553 if (SuperLoc.isValid()) {
2554 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2555 } else {
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002556 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002557 }
2558 }
2559
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002560 // Check the message arguments.
2561 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002562 Expr **Args = ArgsIn.data();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002563 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002564 ExprValueKind VK = VK_RValue;
Fariborz Jahanian68500912010-12-01 01:07:24 +00002565 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2566 ReceiverType->isObjCQualifiedClassType());
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002567 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2568 Sel, SelectorLocs, Method,
Douglas Gregor33823722011-06-11 01:09:30 +00002569 ClassMessage, SuperLoc.isValid(),
John McCall7decc9e2010-11-18 06:31:45 +00002570 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002571 return ExprError();
Alp Toker314cc812014-01-25 16:55:45 +00002572
2573 if (Method && !Method->getReturnType()->isVoidType() &&
2574 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002575 diag::err_illegal_message_expr_incomplete_type))
2576 return ExprError();
Douglas Gregor9a129192010-04-21 00:45:42 +00002577
John McCall31168b02011-06-15 23:02:42 +00002578 // In ARC, forbid the user from sending messages to
2579 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002580 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002581 ObjCMethodFamily family =
2582 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2583 switch (family) {
2584 case OMF_init:
2585 if (Method)
2586 checkInitMethod(Method, ReceiverType);
2587
2588 case OMF_None:
2589 case OMF_alloc:
2590 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00002591 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002592 case OMF_mutableCopy:
2593 case OMF_new:
2594 case OMF_self:
2595 break;
2596
2597 case OMF_dealloc:
2598 case OMF_retain:
2599 case OMF_release:
2600 case OMF_autorelease:
2601 case OMF_retainCount:
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002602 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
2603 << Sel << RecRange;
John McCall31168b02011-06-15 23:02:42 +00002604 break;
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002605
2606 case OMF_performSelector:
2607 if (Method && NumArgs >= 1) {
2608 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2609 Selector ArgSel = SelExp->getSelector();
2610 ObjCMethodDecl *SelMethod =
2611 LookupInstanceMethodInGlobalPool(ArgSel,
2612 SelExp->getSourceRange());
2613 if (!SelMethod)
2614 SelMethod =
2615 LookupFactoryMethodInGlobalPool(ArgSel,
2616 SelExp->getSourceRange());
2617 if (SelMethod) {
2618 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2619 switch (SelFamily) {
2620 case OMF_alloc:
2621 case OMF_copy:
2622 case OMF_mutableCopy:
2623 case OMF_new:
2624 case OMF_self:
2625 case OMF_init:
2626 // Issue error, unless ns_returns_not_retained.
2627 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2628 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002629 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002630 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002631 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2632 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002633 }
2634 break;
2635 default:
2636 // +0 call. OK. unless ns_returns_retained.
2637 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2638 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002639 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002640 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002641 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2642 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002643 }
2644 break;
2645 }
2646 }
2647 } else {
2648 // error (may leak).
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002649 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002650 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2651 }
2652 }
2653 break;
John McCall31168b02011-06-15 23:02:42 +00002654 }
2655 }
2656
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002657 // Construct the appropriate ObjCMessageExpr instance.
John McCall31168b02011-06-15 23:02:42 +00002658 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002659 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002660 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002661 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002662 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002663 makeArrayRef(Args, NumArgs), RBracLoc,
2664 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002665 else {
John McCall7decc9e2010-11-18 06:31:45 +00002666 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002667 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002668 makeArrayRef(Args, NumArgs), RBracLoc,
2669 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002670 if (!isImplicit)
2671 checkCocoaAPI(*this, Result);
2672 }
John McCall31168b02011-06-15 23:02:42 +00002673
David Blaikiebbafb8a2012-03-11 07:00:24 +00002674 if (getLangOpts().ObjCAutoRefCount) {
Fariborz Jahanian9277ff42014-06-17 23:35:13 +00002675 // Do not warn about IBOutlet weak property receivers being set to null
2676 // as this cannot asynchronously happen.
2677 bool WarnWeakReceiver = true;
2678 if (isImplicit && Method)
2679 if (const ObjCPropertyDecl *PropertyDecl = Method->findPropertyDecl())
2680 WarnWeakReceiver = !PropertyDecl->hasAttr<IBOutletAttr>();
2681 if (WarnWeakReceiver)
2682 DiagnoseARCUseOfWeakReceiver(*this, Receiver);
Fariborz Jahanian6bd22262012-04-04 20:05:25 +00002683
John McCall31168b02011-06-15 23:02:42 +00002684 // In ARC, annotate delegate init calls.
2685 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregor486b74e2011-09-27 16:10:05 +00002686 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCall31168b02011-06-15 23:02:42 +00002687 // Only consider init calls *directly* in init implementations,
2688 // not within blocks.
2689 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2690 if (method && method->getMethodFamily() == OMF_init) {
2691 // The implicit assignment to self means we also don't want to
2692 // consume the result.
2693 Result->setDelegateInitCall(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002694 return Result;
John McCall31168b02011-06-15 23:02:42 +00002695 }
2696 }
2697
2698 // In ARC, check for message sends which are likely to introduce
2699 // retain cycles.
2700 checkRetainCycles(Result);
Jordan Rose22487652012-10-11 16:06:21 +00002701
2702 if (!isImplicit && Method) {
2703 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
2704 bool IsWeak =
2705 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
2706 if (!IsWeak && Sel.isUnarySelector())
2707 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002708 if (IsWeak &&
2709 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
2710 getCurFunction()->recordUseOfWeak(Result, Prop);
Jordan Rose22487652012-10-11 16:06:21 +00002711 }
2712 }
John McCall31168b02011-06-15 23:02:42 +00002713 }
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00002714
Douglas Gregoraae38d62010-05-22 05:17:18 +00002715 return MaybeBindToTemporary(Result);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002716}
2717
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002718static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
2719 if (ObjCSelectorExpr *OSE =
2720 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
2721 Selector Sel = OSE->getSelector();
2722 SourceLocation Loc = OSE->getAtLoc();
2723 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
2724 = S.ReferencedSelectors.find(Sel);
2725 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
2726 S.ReferencedSelectors.erase(Pos);
2727 }
2728}
2729
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002730// ActOnInstanceMessage - used for both unary and keyword messages.
2731// ArgExprs is optional - if it is present, the number of expressions
2732// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002733ExprResult Sema::ActOnInstanceMessage(Scope *S,
2734 Expr *Receiver,
2735 Selector Sel,
2736 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002737 ArrayRef<SourceLocation> SelectorLocs,
John McCalldadc5752010-08-24 06:29:42 +00002738 SourceLocation RBracLoc,
2739 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002740 if (!Receiver)
2741 return ExprError();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00002742
2743 // A ParenListExpr can show up while doing error recovery with invalid code.
2744 if (isa<ParenListExpr>(Receiver)) {
2745 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
2746 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002747 Receiver = Result.get();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00002748 }
Fariborz Jahanian17748062013-01-22 19:05:17 +00002749
2750 if (RespondsToSelectorSel.isNull()) {
2751 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
2752 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
2753 }
2754 if (Sel == RespondsToSelectorSel)
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002755 RemoveSelectorFromWarningCache(*this, Args[0]);
Craig Topperc3ec1492014-05-26 06:22:03 +00002756
John McCallb268a282010-08-23 23:25:46 +00002757 return BuildInstanceMessage(Receiver, Receiver->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002758 /*SuperLoc=*/SourceLocation(), Sel,
2759 /*Method=*/nullptr, LBracLoc, SelectorLocs,
2760 RBracLoc, Args);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002761}
Chris Lattner2a3569b2008-04-07 05:30:13 +00002762
John McCall31168b02011-06-15 23:02:42 +00002763enum ARCConversionTypeClass {
John McCalle4fe2452011-10-01 01:01:08 +00002764 /// int, void, struct A
John McCall31168b02011-06-15 23:02:42 +00002765 ACTC_none,
John McCalle4fe2452011-10-01 01:01:08 +00002766
2767 /// id, void (^)()
John McCall31168b02011-06-15 23:02:42 +00002768 ACTC_retainable,
John McCalle4fe2452011-10-01 01:01:08 +00002769
2770 /// id*, id***, void (^*)(),
2771 ACTC_indirectRetainable,
2772
2773 /// void* might be a normal C type, or it might a CF type.
2774 ACTC_voidPtr,
2775
2776 /// struct A*
2777 ACTC_coreFoundation
John McCall31168b02011-06-15 23:02:42 +00002778};
John McCalle4fe2452011-10-01 01:01:08 +00002779static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2780 return (ACTC == ACTC_retainable ||
2781 ACTC == ACTC_coreFoundation ||
2782 ACTC == ACTC_voidPtr);
2783}
2784static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2785 return ACTC == ACTC_none ||
2786 ACTC == ACTC_voidPtr ||
2787 ACTC == ACTC_coreFoundation;
2788}
2789
John McCall31168b02011-06-15 23:02:42 +00002790static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCalle4fe2452011-10-01 01:01:08 +00002791 bool isIndirect = false;
John McCall31168b02011-06-15 23:02:42 +00002792
2793 // Ignore an outermost reference type.
John McCalle4fe2452011-10-01 01:01:08 +00002794 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall31168b02011-06-15 23:02:42 +00002795 type = ref->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002796 isIndirect = true;
2797 }
John McCall31168b02011-06-15 23:02:42 +00002798
2799 // Drill through pointers and arrays recursively.
2800 while (true) {
2801 if (const PointerType *ptr = type->getAs<PointerType>()) {
2802 type = ptr->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002803
2804 // The first level of pointer may be the innermost pointer on a CF type.
2805 if (!isIndirect) {
2806 if (type->isVoidType()) return ACTC_voidPtr;
2807 if (type->isRecordType()) return ACTC_coreFoundation;
2808 }
John McCall31168b02011-06-15 23:02:42 +00002809 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2810 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2811 } else {
2812 break;
2813 }
John McCalle4fe2452011-10-01 01:01:08 +00002814 isIndirect = true;
John McCall31168b02011-06-15 23:02:42 +00002815 }
2816
John McCalle4fe2452011-10-01 01:01:08 +00002817 if (isIndirect) {
2818 if (type->isObjCARCBridgableType())
2819 return ACTC_indirectRetainable;
2820 return ACTC_none;
2821 }
2822
2823 if (type->isObjCARCBridgableType())
2824 return ACTC_retainable;
2825
2826 return ACTC_none;
John McCall31168b02011-06-15 23:02:42 +00002827}
2828
2829namespace {
John McCalle4fe2452011-10-01 01:01:08 +00002830 /// A result from the cast checker.
2831 enum ACCResult {
2832 /// Cannot be casted.
2833 ACC_invalid,
2834
2835 /// Can be safely retained or not retained.
2836 ACC_bottom,
2837
2838 /// Can be casted at +0.
2839 ACC_plusZero,
2840
2841 /// Can be casted at +1.
2842 ACC_plusOne
2843 };
2844 ACCResult merge(ACCResult left, ACCResult right) {
2845 if (left == right) return left;
2846 if (left == ACC_bottom) return right;
2847 if (right == ACC_bottom) return left;
2848 return ACC_invalid;
2849 }
2850
2851 /// A checker which white-lists certain expressions whose conversion
2852 /// to or from retainable type would otherwise be forbidden in ARC.
2853 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2854 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2855
John McCall31168b02011-06-15 23:02:42 +00002856 ASTContext &Context;
John McCalle4fe2452011-10-01 01:01:08 +00002857 ARCConversionTypeClass SourceClass;
2858 ARCConversionTypeClass TargetClass;
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002859 bool Diagnose;
John McCalle4fe2452011-10-01 01:01:08 +00002860
2861 static bool isCFType(QualType type) {
2862 // Someday this can use ns_bridged. For now, it has to do this.
2863 return type->isCARCBridgableType();
John McCall31168b02011-06-15 23:02:42 +00002864 }
John McCalle4fe2452011-10-01 01:01:08 +00002865
2866 public:
2867 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002868 ARCConversionTypeClass target, bool diagnose)
2869 : Context(Context), SourceClass(source), TargetClass(target),
2870 Diagnose(diagnose) {}
John McCalle4fe2452011-10-01 01:01:08 +00002871
2872 using super::Visit;
2873 ACCResult Visit(Expr *e) {
2874 return super::Visit(e->IgnoreParens());
2875 }
2876
2877 ACCResult VisitStmt(Stmt *s) {
2878 return ACC_invalid;
2879 }
2880
2881 /// Null pointer constants can be casted however you please.
2882 ACCResult VisitExpr(Expr *e) {
2883 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2884 return ACC_bottom;
2885 return ACC_invalid;
2886 }
2887
2888 /// Objective-C string literals can be safely casted.
2889 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2890 // If we're casting to any retainable type, go ahead. Global
2891 // strings are immune to retains, so this is bottom.
2892 if (isAnyRetainable(TargetClass)) return ACC_bottom;
2893
2894 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00002895 }
2896
John McCalle4fe2452011-10-01 01:01:08 +00002897 /// Look through certain implicit and explicit casts.
2898 ACCResult VisitCastExpr(CastExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00002899 switch (e->getCastKind()) {
2900 case CK_NullToPointer:
John McCalle4fe2452011-10-01 01:01:08 +00002901 return ACC_bottom;
2902
John McCall31168b02011-06-15 23:02:42 +00002903 case CK_NoOp:
2904 case CK_LValueToRValue:
2905 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002906 case CK_CPointerToObjCPointerCast:
2907 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00002908 case CK_AnyPointerToBlockPointerCast:
2909 return Visit(e->getSubExpr());
John McCalle4fe2452011-10-01 01:01:08 +00002910
John McCall31168b02011-06-15 23:02:42 +00002911 default:
John McCalle4fe2452011-10-01 01:01:08 +00002912 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00002913 }
2914 }
John McCalle4fe2452011-10-01 01:01:08 +00002915
2916 /// Look through unary extension.
2917 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00002918 return Visit(e->getSubExpr());
2919 }
John McCalle4fe2452011-10-01 01:01:08 +00002920
2921 /// Ignore the LHS of a comma operator.
2922 ACCResult VisitBinComma(BinaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00002923 return Visit(e->getRHS());
2924 }
John McCalle4fe2452011-10-01 01:01:08 +00002925
2926 /// Conditional operators are okay if both sides are okay.
2927 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
2928 ACCResult left = Visit(e->getTrueExpr());
2929 if (left == ACC_invalid) return ACC_invalid;
2930 return merge(left, Visit(e->getFalseExpr()));
John McCall31168b02011-06-15 23:02:42 +00002931 }
John McCalle4fe2452011-10-01 01:01:08 +00002932
John McCallfe96e0b2011-11-06 09:01:30 +00002933 /// Look through pseudo-objects.
2934 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
2935 // If we're getting here, we should always have a result.
2936 return Visit(e->getResultExpr());
2937 }
2938
John McCalle4fe2452011-10-01 01:01:08 +00002939 /// Statement expressions are okay if their result expression is okay.
2940 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00002941 return Visit(e->getSubStmt()->body_back());
2942 }
John McCall31168b02011-06-15 23:02:42 +00002943
John McCalle4fe2452011-10-01 01:01:08 +00002944 /// Some declaration references are okay.
2945 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
2946 // References to global constants from system headers are okay.
2947 // These are things like 'kCFStringTransformToLatin'. They are
2948 // can also be assumed to be immune to retains.
2949 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
2950 if (isAnyRetainable(TargetClass) &&
2951 isAnyRetainable(SourceClass) &&
2952 var &&
2953 var->getStorageClass() == SC_Extern &&
2954 var->getType().isConstQualified() &&
2955 Context.getSourceManager().isInSystemHeader(var->getLocation())) {
2956 return ACC_bottom;
2957 }
2958
2959 // Nothing else.
2960 return ACC_invalid;
Fariborz Jahanian78876372011-06-21 17:38:29 +00002961 }
John McCalle4fe2452011-10-01 01:01:08 +00002962
2963 /// Some calls are okay.
2964 ACCResult VisitCallExpr(CallExpr *e) {
2965 if (FunctionDecl *fn = e->getDirectCallee())
2966 if (ACCResult result = checkCallToFunction(fn))
2967 return result;
2968
2969 return super::VisitCallExpr(e);
2970 }
2971
2972 ACCResult checkCallToFunction(FunctionDecl *fn) {
2973 // Require a CF*Ref return type.
Alp Toker314cc812014-01-25 16:55:45 +00002974 if (!isCFType(fn->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00002975 return ACC_invalid;
2976
2977 if (!isAnyRetainable(TargetClass))
2978 return ACC_invalid;
2979
2980 // Honor an explicit 'not retained' attribute.
2981 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
2982 return ACC_plusZero;
2983
2984 // Honor an explicit 'retained' attribute, except that for
2985 // now we're not going to permit implicit handling of +1 results,
2986 // because it's a bit frightening.
2987 if (fn->hasAttr<CFReturnsRetainedAttr>())
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00002988 return Diagnose ? ACC_plusOne
2989 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00002990
2991 // Recognize this specific builtin function, which is used by CFSTR.
2992 unsigned builtinID = fn->getBuiltinID();
2993 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
2994 return ACC_bottom;
2995
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00002996 // Otherwise, don't do anything implicit with an unaudited function.
2997 if (!fn->hasAttr<CFAuditedTransferAttr>())
2998 return ACC_invalid;
2999
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003000 // Otherwise, it's +0 unless it follows the create convention.
3001 if (ento::coreFoundation::followsCreateRule(fn))
3002 return Diagnose ? ACC_plusOne
3003 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003004
John McCalle4fe2452011-10-01 01:01:08 +00003005 return ACC_plusZero;
3006 }
3007
3008 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3009 return checkCallToMethod(e->getMethodDecl());
3010 }
3011
3012 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3013 ObjCMethodDecl *method;
3014 if (e->isExplicitProperty())
3015 method = e->getExplicitProperty()->getGetterMethodDecl();
3016 else
3017 method = e->getImplicitPropertyGetter();
3018 return checkCallToMethod(method);
3019 }
3020
3021 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3022 if (!method) return ACC_invalid;
3023
3024 // Check for message sends to functions returning CF types. We
3025 // just obey the Cocoa conventions with these, even though the
3026 // return type is CF.
Alp Toker314cc812014-01-25 16:55:45 +00003027 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003028 return ACC_invalid;
3029
3030 // If the method is explicitly marked not-retained, it's +0.
3031 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3032 return ACC_plusZero;
3033
3034 // If the method is explicitly marked as returning retained, or its
3035 // selector follows a +1 Cocoa convention, treat it as +1.
3036 if (method->hasAttr<CFReturnsRetainedAttr>())
3037 return ACC_plusOne;
3038
3039 switch (method->getSelector().getMethodFamily()) {
3040 case OMF_alloc:
3041 case OMF_copy:
3042 case OMF_mutableCopy:
3043 case OMF_new:
3044 return ACC_plusOne;
3045
3046 default:
3047 // Otherwise, treat it as +0.
3048 return ACC_plusZero;
Fariborz Jahanian9b83be82011-06-21 19:42:38 +00003049 }
3050 }
John McCalle4fe2452011-10-01 01:01:08 +00003051 };
Fariborz Jahanian4ad56862011-06-20 20:54:42 +00003052}
3053
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003054bool Sema::isKnownName(StringRef name) {
3055 if (name.empty())
3056 return false;
3057 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003058 Sema::LookupOrdinaryName);
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003059 return LookupName(R, TUScope, false);
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003060}
3061
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003062static void addFixitForObjCARCConversion(Sema &S,
3063 DiagnosticBuilder &DiagB,
3064 Sema::CheckedConversionKind CCK,
3065 SourceLocation afterLParen,
3066 QualType castType,
3067 Expr *castExpr,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003068 Expr *realCast,
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003069 const char *bridgeKeyword,
3070 const char *CFBridgeName) {
3071 // We handle C-style and implicit casts here.
3072 switch (CCK) {
3073 case Sema::CCK_ImplicitConversion:
3074 case Sema::CCK_CStyleCast:
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003075 case Sema::CCK_OtherCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003076 break;
3077 case Sema::CCK_FunctionalCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003078 return;
3079 }
3080
3081 if (CFBridgeName) {
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003082 if (CCK == Sema::CCK_OtherCast) {
3083 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3084 SourceRange range(NCE->getOperatorLoc(),
3085 NCE->getAngleBrackets().getEnd());
3086 SmallString<32> BridgeCall;
3087
3088 SourceManager &SM = S.getSourceManager();
3089 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3090 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3091 BridgeCall += ' ';
3092
3093 BridgeCall += CFBridgeName;
3094 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3095 }
3096 return;
3097 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003098 Expr *castedE = castExpr;
3099 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3100 castedE = CCE->getSubExpr();
3101 castedE = castedE->IgnoreImpCasts();
3102 SourceRange range = castedE->getSourceRange();
Jordan Rose288c4212012-06-07 01:10:31 +00003103
3104 SmallString<32> BridgeCall;
3105
3106 SourceManager &SM = S.getSourceManager();
3107 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3108 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3109 BridgeCall += ' ';
3110
3111 BridgeCall += CFBridgeName;
3112
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003113 if (isa<ParenExpr>(castedE)) {
3114 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003115 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003116 } else {
Jordan Rose288c4212012-06-07 01:10:31 +00003117 BridgeCall += '(';
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003118 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003119 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003120 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3121 S.PP.getLocForEndOfToken(range.getEnd()),
3122 ")"));
3123 }
3124 return;
3125 }
3126
3127 if (CCK == Sema::CCK_CStyleCast) {
3128 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003129 } else if (CCK == Sema::CCK_OtherCast) {
3130 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3131 std::string castCode = "(";
3132 castCode += bridgeKeyword;
3133 castCode += castType.getAsString();
3134 castCode += ")";
3135 SourceRange Range(NCE->getOperatorLoc(),
3136 NCE->getAngleBrackets().getEnd());
3137 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3138 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003139 } else {
3140 std::string castCode = "(";
3141 castCode += bridgeKeyword;
3142 castCode += castType.getAsString();
3143 castCode += ")";
3144 Expr *castedE = castExpr->IgnoreImpCasts();
3145 SourceRange range = castedE->getSourceRange();
3146 if (isa<ParenExpr>(castedE)) {
3147 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3148 castCode));
3149 } else {
3150 castCode += "(";
3151 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3152 castCode));
3153 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3154 S.PP.getLocForEndOfToken(range.getEnd()),
3155 ")"));
3156 }
3157 }
3158}
3159
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003160template <typename T>
3161static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3162 TypedefNameDecl *TDNDecl = TD->getDecl();
3163 QualType QT = TDNDecl->getUnderlyingType();
3164 if (QT->isPointerType()) {
3165 QT = QT->getPointeeType();
3166 if (const RecordType *RT = QT->getAs<RecordType>())
Fariborz Jahanian9af6a782014-06-11 19:10:46 +00003167 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
Aaron Ballman2084f8f2013-12-19 13:20:36 +00003168 return RD->getAttr<T>();
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003169 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003170 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003171}
3172
3173static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3174 TypedefNameDecl *&TDNDecl) {
3175 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3176 TDNDecl = TD->getDecl();
3177 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3178 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3179 return ObjCBAttr;
3180 T = TDNDecl->getUnderlyingType();
3181 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003182 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003183}
3184
John McCall4124c492011-10-17 18:40:02 +00003185static void
3186diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3187 QualType castType, ARCConversionTypeClass castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003188 Expr *castExpr, Expr *realCast,
3189 ARCConversionTypeClass exprACTC,
John McCall4124c492011-10-17 18:40:02 +00003190 Sema::CheckedConversionKind CCK) {
John McCall31168b02011-06-15 23:02:42 +00003191 SourceLocation loc =
John McCalle4fe2452011-10-01 01:01:08 +00003192 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCall31168b02011-06-15 23:02:42 +00003193
John McCall4124c492011-10-17 18:40:02 +00003194 if (S.makeUnavailableInSystemHeader(loc,
John McCalle4fe2452011-10-01 01:01:08 +00003195 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCall31168b02011-06-15 23:02:42 +00003196 return;
John McCall4124c492011-10-17 18:40:02 +00003197
3198 QualType castExprType = castExpr->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00003199 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003200 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3201 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3202 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
Fariborz Jahanian1ad83a32014-06-18 23:22:38 +00003203 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003204 return;
John McCall31168b02011-06-15 23:02:42 +00003205
John McCall640767f2011-06-17 06:50:50 +00003206 unsigned srcKind = 0;
John McCall31168b02011-06-15 23:02:42 +00003207 switch (exprACTC) {
John McCalle4fe2452011-10-01 01:01:08 +00003208 case ACTC_none:
3209 case ACTC_coreFoundation:
3210 case ACTC_voidPtr:
3211 srcKind = (castExprType->isPointerType() ? 1 : 0);
3212 break;
3213 case ACTC_retainable:
3214 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3215 break;
3216 case ACTC_indirectRetainable:
3217 srcKind = 4;
3218 break;
John McCall31168b02011-06-15 23:02:42 +00003219 }
3220
John McCall4124c492011-10-17 18:40:02 +00003221 // Check whether this could be fixed with a bridge cast.
3222 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
3223 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCall31168b02011-06-15 23:02:42 +00003224
John McCall4124c492011-10-17 18:40:02 +00003225 // Bridge from an ARC type to a CF type.
3226 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003227
John McCall4124c492011-10-17 18:40:02 +00003228 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3229 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3230 << 2 // of C pointer type
3231 << castExprType
3232 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3233 << castType
3234 << castRange
3235 << castExpr->getSourceRange();
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003236 bool br = S.isKnownName("CFBridgingRelease");
Jordan Rose4502b532012-07-31 01:07:43 +00003237 ACCResult CreateRule =
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003238 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003239 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003240 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003241 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003242 DiagnosticBuilder DiagB =
3243 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3244 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Craig Topperc3ec1492014-05-26 06:22:03 +00003245
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003246 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003247 castType, castExpr, realCast, "__bridge ",
3248 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003249 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003250 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003251 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003252 DiagnosticBuilder DiagB =
3253 (CCK == Sema::CCK_OtherCast && !br) ?
3254 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3255 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3256 diag::note_arc_bridge_transfer)
3257 << castExprType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003258
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003259 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003260 castType, castExpr, realCast, "__bridge_transfer ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003261 br ? "CFBridgingRelease" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003262 }
John McCall4124c492011-10-17 18:40:02 +00003263
3264 return;
3265 }
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003266
John McCall4124c492011-10-17 18:40:02 +00003267 // Bridge from a CF type to an ARC type.
3268 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003269 bool br = S.isKnownName("CFBridgingRetain");
John McCall4124c492011-10-17 18:40:02 +00003270 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3271 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3272 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3273 << castExprType
3274 << 2 // to C pointer type
3275 << castType
3276 << castRange
3277 << castExpr->getSourceRange();
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003278 ACCResult CreateRule =
3279 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003280 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003281 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003282 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003283 DiagnosticBuilder DiagB =
3284 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3285 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003286 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003287 castType, castExpr, realCast, "__bridge ",
3288 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003289 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003290 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003291 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003292 DiagnosticBuilder DiagB =
3293 (CCK == Sema::CCK_OtherCast && !br) ?
3294 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3295 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3296 diag::note_arc_bridge_retained)
3297 << castType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003298
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003299 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003300 castType, castExpr, realCast, "__bridge_retained ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003301 br ? "CFBridgingRetain" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003302 }
John McCall4124c492011-10-17 18:40:02 +00003303
3304 return;
John McCall31168b02011-06-15 23:02:42 +00003305 }
3306
John McCall4124c492011-10-17 18:40:02 +00003307 S.Diag(loc, diag::err_arc_mismatched_cast)
3308 << (CCK != Sema::CCK_ImplicitConversion)
3309 << srcKind << castExprType << castType
John McCall31168b02011-06-15 23:02:42 +00003310 << castRange << castExpr->getSourceRange();
3311}
3312
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003313template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003314static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3315 bool &HadTheAttribute, bool warn) {
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003316 QualType T = castExpr->getType();
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003317 HadTheAttribute = false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003318 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3319 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003320 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003321 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003322 HadTheAttribute = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003323 NamedDecl *Target = nullptr;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003324 // Check for an existing type with this name.
3325 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3326 Sema::LookupOrdinaryName);
3327 if (S.LookupName(R, S.TUScope)) {
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003328 Target = R.getFoundDecl();
3329 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3330 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3331 if (const ObjCObjectPointerType *InterfacePointerType =
3332 castType->getAsObjCInterfacePointerType()) {
3333 ObjCInterfaceDecl *CastClass
3334 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003335 if ((CastClass == ExprClass) ||
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003336 (CastClass && ExprClass->isSuperClassOf(CastClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003337 return true;
3338 if (warn)
3339 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3340 << T << Target->getName() << castType->getPointeeType();
3341 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003342 } else if (castType->isObjCIdType() ||
3343 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3344 castType, ExprClass)))
3345 // ok to cast to 'id'.
3346 // casting to id<p-list> is ok if bridge type adopts all of
3347 // p-list protocols.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003348 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003349 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003350 if (warn) {
3351 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3352 << T << Target->getName() << castType;
3353 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3354 S.Diag(Target->getLocStart(), diag::note_declared_at);
3355 }
3356 return false;
Fariborz Jahanian2c312122013-11-16 23:22:37 +00003357 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003358 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003359 }
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003360 S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface)
Aaron Ballmanc0550742014-01-03 02:07:43 +00003361 << castExpr->getType() << Parm;
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003362 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3363 if (Target)
3364 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003365 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003366 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003367 return false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003368 }
3369 T = TDNDecl->getUnderlyingType();
3370 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003371 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003372}
3373
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003374template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003375static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
3376 bool &HadTheAttribute, bool warn) {
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003377 QualType T = castType;
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003378 HadTheAttribute = false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003379 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3380 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003381 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003382 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003383 HadTheAttribute = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003384 NamedDecl *Target = nullptr;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003385 // Check for an existing type with this name.
3386 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3387 Sema::LookupOrdinaryName);
3388 if (S.LookupName(R, S.TUScope)) {
3389 Target = R.getFoundDecl();
3390 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3391 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3392 if (const ObjCObjectPointerType *InterfacePointerType =
3393 castExpr->getType()->getAsObjCInterfacePointerType()) {
3394 ObjCInterfaceDecl *ExprClass
3395 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003396 if ((CastClass == ExprClass) ||
3397 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003398 return true;
3399 if (warn) {
3400 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3401 << castExpr->getType()->getPointeeType() << T;
3402 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3403 }
3404 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003405 } else if (castExpr->getType()->isObjCIdType() ||
3406 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3407 castExpr->getType(), CastClass)))
3408 // ok to cast an 'id' expression to a CFtype.
3409 // ok to cast an 'id<plist>' expression to CFtype provided plist
3410 // adopts all of CFtype's ObjetiveC's class plist.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003411 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003412 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003413 if (warn) {
3414 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3415 << castExpr->getType() << castType;
3416 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3417 S.Diag(Target->getLocStart(), diag::note_declared_at);
3418 }
3419 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003420 }
3421 }
3422 }
3423 S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject)
3424 << castExpr->getType() << castType;
3425 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3426 if (Target)
3427 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003428 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003429 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003430 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003431 }
3432 T = TDNDecl->getUnderlyingType();
3433 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003434 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003435}
3436
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003437void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003438 if (!getLangOpts().ObjC1)
3439 return;
Alp Tokerf6a24ce2013-12-05 16:25:25 +00003440 // warn in presence of __bridge casting to or from a toll free bridge cast.
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003441 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3442 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003443 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003444 bool HasObjCBridgeAttr;
3445 bool ObjCBridgeAttrWillNotWarn =
3446 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3447 false);
3448 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3449 return;
3450 bool HasObjCBridgeMutableAttr;
3451 bool ObjCBridgeMutableAttrWillNotWarn =
3452 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3453 HasObjCBridgeMutableAttr, false);
3454 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3455 return;
3456
3457 if (HasObjCBridgeAttr)
3458 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3459 true);
3460 else if (HasObjCBridgeMutableAttr)
3461 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3462 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003463 }
3464 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003465 bool HasObjCBridgeAttr;
3466 bool ObjCBridgeAttrWillNotWarn =
3467 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3468 false);
3469 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3470 return;
3471 bool HasObjCBridgeMutableAttr;
3472 bool ObjCBridgeMutableAttrWillNotWarn =
3473 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3474 HasObjCBridgeMutableAttr, false);
3475 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3476 return;
3477
3478 if (HasObjCBridgeAttr)
3479 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3480 true);
3481 else if (HasObjCBridgeMutableAttr)
3482 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3483 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003484 }
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003485}
3486
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003487void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
3488 QualType SrcType = castExpr->getType();
3489 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
3490 if (PRE->isExplicitProperty()) {
3491 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
3492 SrcType = PDecl->getType();
3493 }
3494 else if (PRE->isImplicitProperty()) {
3495 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
3496 SrcType = Getter->getReturnType();
3497
3498 }
3499 }
3500
3501 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
3502 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
3503 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
3504 return;
3505 CheckObjCBridgeRelatedConversions(castExpr->getLocStart(),
3506 castType, SrcType, castExpr);
3507 return;
3508}
3509
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00003510bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
3511 CastKind &Kind) {
3512 if (!getLangOpts().ObjC1)
3513 return false;
3514 ARCConversionTypeClass exprACTC =
3515 classifyTypeForARCConversion(castExpr->getType());
3516 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3517 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
3518 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
3519 CheckTollFreeBridgeCast(castType, castExpr);
3520 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
3521 : CK_CPointerToObjCPointerCast;
3522 return true;
3523 }
3524 return false;
3525}
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003526
3527bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
3528 QualType DestType, QualType SrcType,
3529 ObjCInterfaceDecl *&RelatedClass,
3530 ObjCMethodDecl *&ClassMethod,
3531 ObjCMethodDecl *&InstanceMethod,
3532 TypedefNameDecl *&TDNDecl,
3533 bool CfToNs) {
3534 QualType T = CfToNs ? SrcType : DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003535 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
3536 if (!ObjCBAttr)
3537 return false;
3538
3539 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
3540 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
3541 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
3542 if (!RCId)
3543 return false;
Craig Topperc3ec1492014-05-26 06:22:03 +00003544 NamedDecl *Target = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003545 // Check for an existing type with this name.
3546 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
3547 Sema::LookupOrdinaryName);
3548 if (!LookupName(R, TUScope)) {
3549 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003550 << SrcType << DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003551 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3552 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003553 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003554 Target = R.getFoundDecl();
3555 if (Target && isa<ObjCInterfaceDecl>(Target))
3556 RelatedClass = cast<ObjCInterfaceDecl>(Target);
3557 else {
3558 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
3559 << SrcType << DestType;
3560 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3561 if (Target)
3562 Diag(Target->getLocStart(), diag::note_declared_at);
3563 return false;
3564 }
3565
3566 // Check for an existing class method with the given selector name.
3567 if (CfToNs && CMId) {
3568 Selector Sel = Context.Selectors.getUnarySelector(CMId);
3569 ClassMethod = RelatedClass->lookupMethod(Sel, false);
3570 if (!ClassMethod) {
3571 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003572 << SrcType << DestType << Sel << false;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003573 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3574 return false;
3575 }
3576 }
3577
3578 // Check for an existing instance method with the given selector name.
3579 if (!CfToNs && IMId) {
3580 Selector Sel = Context.Selectors.getNullarySelector(IMId);
3581 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
3582 if (!InstanceMethod) {
3583 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003584 << SrcType << DestType << Sel << true;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003585 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3586 return false;
3587 }
3588 }
3589 return true;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003590}
3591
3592bool
3593Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003594 QualType DestType, QualType SrcType,
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003595 Expr *&SrcExpr) {
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003596 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
3597 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
3598 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
3599 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
3600 if (!CfToNs && !NsToCf)
3601 return false;
3602
3603 ObjCInterfaceDecl *RelatedClass;
Craig Topperc3ec1492014-05-26 06:22:03 +00003604 ObjCMethodDecl *ClassMethod = nullptr;
3605 ObjCMethodDecl *InstanceMethod = nullptr;
3606 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003607 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
3608 ClassMethod, InstanceMethod, TDNDecl, CfToNs))
3609 return false;
3610
3611 if (CfToNs) {
3612 // Implicit conversion from CF to ObjC object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003613 if (ClassMethod) {
3614 std::string ExpressionString = "[";
3615 ExpressionString += RelatedClass->getNameAsString();
3616 ExpressionString += " ";
3617 ExpressionString += ClassMethod->getSelector().getAsString();
3618 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
3619 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003620 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003621 << SrcType << DestType << ClassMethod->getSelector() << false
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003622 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString)
3623 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003624 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3625 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3626
3627 QualType receiverType =
3628 Context.getObjCInterfaceType(RelatedClass);
3629 // Argument.
3630 Expr *args[] = { SrcExpr };
3631 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
3632 ClassMethod->getLocation(),
3633 ClassMethod->getSelector(), ClassMethod,
3634 MultiExprArg(args, 1));
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003635 SrcExpr = msg.get();
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003636 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003637 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003638 }
3639 else {
3640 // Implicit conversion from ObjC type to CF object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003641 if (InstanceMethod) {
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003642 std::string ExpressionString;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003643 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003644 if (InstanceMethod->isPropertyAccessor())
3645 if (const ObjCPropertyDecl *PDecl = InstanceMethod->findPropertyDecl()) {
3646 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
3647 ExpressionString = ".";
3648 ExpressionString += PDecl->getNameAsString();
3649 Diag(Loc, diag::err_objc_bridged_related_known_method)
3650 << SrcType << DestType << InstanceMethod->getSelector() << true
3651 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3652 }
3653 if (ExpressionString.empty()) {
3654 // Provide a fixit: [ObjectExpr InstanceMethod]
3655 ExpressionString = " ";
3656 ExpressionString += InstanceMethod->getSelector().getAsString();
3657 ExpressionString += "]";
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003658
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003659 Diag(Loc, diag::err_objc_bridged_related_known_method)
3660 << SrcType << DestType << InstanceMethod->getSelector() << true
3661 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[")
3662 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3663 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003664 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3665 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3666
3667 ExprResult msg =
3668 BuildInstanceMessageImplicit(SrcExpr, SrcType,
3669 InstanceMethod->getLocation(),
3670 InstanceMethod->getSelector(),
3671 InstanceMethod, None);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003672 SrcExpr = msg.get();
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003673 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003674 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003675 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003676 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003677}
3678
John McCall4124c492011-10-17 18:40:02 +00003679Sema::ARCConversionResult
3680Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003681 Expr *&castExpr, CheckedConversionKind CCK,
Fariborz Jahanianc03ef572014-06-18 23:52:49 +00003682 bool DiagnoseCFAudited,
3683 BinaryOperatorKind Opc) {
John McCall4124c492011-10-17 18:40:02 +00003684 QualType castExprType = castExpr->getType();
3685
3686 // For the purposes of the classification, we assume reference types
3687 // will bind to temporaries.
3688 QualType effCastType = castType;
3689 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
3690 effCastType = ref->getPointeeType();
3691
3692 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
3693 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003694 if (exprACTC == castACTC) {
3695 // check for viablity and report error if casting an rvalue to a
3696 // life-time qualifier.
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003697 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003698 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003699 (castType != castExprType)) {
3700 const Type *DT = castType.getTypePtr();
3701 QualType QDT = castType;
3702 // We desugar some types but not others. We ignore those
3703 // that cannot happen in a cast; i.e. auto, and those which
3704 // should not be de-sugared; i.e typedef.
3705 if (const ParenType *PT = dyn_cast<ParenType>(DT))
3706 QDT = PT->desugar();
3707 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
3708 QDT = TP->desugar();
3709 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
3710 QDT = AT->desugar();
3711 if (QDT != castType &&
3712 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
3713 SourceLocation loc =
3714 (castRange.isValid() ? castRange.getBegin()
3715 : castExpr->getExprLoc());
3716 Diag(loc, diag::err_arc_nolifetime_behavior);
3717 }
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003718 }
3719 return ACR_okay;
3720 }
3721
John McCall4124c492011-10-17 18:40:02 +00003722 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
3723
3724 // Allow all of these types to be cast to integer types (but not
3725 // vice-versa).
3726 if (castACTC == ACTC_none && castType->isIntegralType(Context))
3727 return ACR_okay;
3728
3729 // Allow casts between pointers to lifetime types (e.g., __strong id*)
3730 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
3731 // must be explicit.
3732 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
3733 return ACR_okay;
3734 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
3735 CCK != CCK_ImplicitConversion)
3736 return ACR_okay;
3737
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003738 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
John McCall4124c492011-10-17 18:40:02 +00003739 // For invalid casts, fall through.
3740 case ACC_invalid:
3741 break;
3742
3743 // Do nothing for both bottom and +0.
3744 case ACC_bottom:
3745 case ACC_plusZero:
3746 return ACR_okay;
3747
3748 // If the result is +1, consume it here.
3749 case ACC_plusOne:
3750 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
3751 CK_ARCConsumeObject, castExpr,
Craig Topperc3ec1492014-05-26 06:22:03 +00003752 nullptr, VK_RValue);
John McCall4124c492011-10-17 18:40:02 +00003753 ExprNeedsCleanups = true;
3754 return ACR_okay;
3755 }
3756
3757 // If this is a non-implicit cast from id or block type to a
3758 // CoreFoundation type, delay complaining in case the cast is used
3759 // in an acceptable context.
3760 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
3761 CCK != CCK_ImplicitConversion)
3762 return ACR_unbridged;
3763
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00003764 // Do not issue bridge cast" diagnostic when implicit casting a cstring
3765 // to 'NSString *'. Let caller issue a normal mismatched diagnostic with
3766 // suitable fix-it.
Fariborz Jahanian283bf892013-12-18 21:04:43 +00003767 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
3768 ConversionToObjCStringLiteralCheck(castType, castExpr))
3769 return ACR_okay;
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00003770
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003771 // Do not issue "bridge cast" diagnostic when implicit casting
3772 // a retainable object to a CF type parameter belonging to an audited
3773 // CF API function. Let caller issue a normal type mismatched diagnostic
3774 // instead.
3775 if (!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
3776 castACTC != ACTC_coreFoundation)
Fariborz Jahanianc03ef572014-06-18 23:52:49 +00003777 if (!(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
3778 (Opc == BO_NE || Opc == BO_EQ)))
3779 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3780 castExpr, castExpr, exprACTC, CCK);
John McCall4124c492011-10-17 18:40:02 +00003781 return ACR_okay;
3782}
3783
3784/// Given that we saw an expression with the ARCUnbridgedCastTy
3785/// placeholder type, complain bitterly.
3786void Sema::diagnoseARCUnbridgedCast(Expr *e) {
3787 // We expect the spurious ImplicitCastExpr to already have been stripped.
3788 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3789 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
3790
3791 SourceRange castRange;
3792 QualType castType;
3793 CheckedConversionKind CCK;
3794
3795 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
3796 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
3797 castType = cast->getTypeAsWritten();
3798 CCK = CCK_CStyleCast;
3799 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
3800 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
3801 castType = cast->getTypeAsWritten();
3802 CCK = CCK_OtherCast;
3803 } else {
3804 castType = cast->getType();
3805 CCK = CCK_ImplicitConversion;
3806 }
3807
3808 ARCConversionTypeClass castACTC =
3809 classifyTypeForARCConversion(castType.getNonReferenceType());
3810
3811 Expr *castExpr = realCast->getSubExpr();
3812 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
3813
3814 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003815 castExpr, realCast, ACTC_retainable, CCK);
John McCall4124c492011-10-17 18:40:02 +00003816}
3817
3818/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
3819/// type, remove the placeholder cast.
3820Expr *Sema::stripARCUnbridgedCast(Expr *e) {
3821 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3822
3823 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
3824 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
3825 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
3826 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
3827 assert(uo->getOpcode() == UO_Extension);
3828 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
3829 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
3830 sub->getValueKind(), sub->getObjectKind(),
3831 uo->getOperatorLoc());
3832 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
3833 assert(!gse->isResultDependent());
3834
3835 unsigned n = gse->getNumAssocs();
3836 SmallVector<Expr*, 4> subExprs(n);
3837 SmallVector<TypeSourceInfo*, 4> subTypes(n);
3838 for (unsigned i = 0; i != n; ++i) {
3839 subTypes[i] = gse->getAssocTypeSourceInfo(i);
3840 Expr *sub = gse->getAssocExpr(i);
3841 if (i == gse->getResultIndex())
3842 sub = stripARCUnbridgedCast(sub);
3843 subExprs[i] = sub;
3844 }
3845
3846 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
3847 gse->getControllingExpr(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003848 subTypes, subExprs,
3849 gse->getDefaultLoc(),
John McCall4124c492011-10-17 18:40:02 +00003850 gse->getRParenLoc(),
3851 gse->containsUnexpandedParameterPack(),
3852 gse->getResultIndex());
3853 } else {
3854 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
3855 return cast<ImplicitCastExpr>(e)->getSubExpr();
3856 }
3857}
3858
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00003859bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
3860 QualType exprType) {
3861 QualType canCastType =
3862 Context.getCanonicalType(castType).getUnqualifiedType();
3863 QualType canExprType =
3864 Context.getCanonicalType(exprType).getUnqualifiedType();
3865 if (isa<ObjCObjectPointerType>(canCastType) &&
3866 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
3867 canExprType->isObjCObjectPointerType()) {
3868 if (const ObjCObjectPointerType *ObjT =
3869 canExprType->getAs<ObjCObjectPointerType>())
Richard Smith802c4b72012-08-23 06:16:52 +00003870 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
3871 return !ObjI->isArcWeakrefUnavailable();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00003872 }
3873 return true;
3874}
3875
John McCall4db5c3c2011-07-07 06:58:02 +00003876/// Look for an ObjCReclaimReturnedObject cast and destroy it.
3877static Expr *maybeUndoReclaimObject(Expr *e) {
3878 // For now, we just undo operands that are *immediately* reclaim
3879 // expressions, which prevents the vast majority of potential
3880 // problems here. To catch them all, we'd need to rebuild arbitrary
3881 // value-propagating subexpressions --- we can't reliably rebuild
3882 // in-place because of expression sharing.
3883 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall2d637d22011-09-10 06:18:15 +00003884 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall4db5c3c2011-07-07 06:58:02 +00003885 return ice->getSubExpr();
3886
3887 return e;
3888}
3889
John McCall31168b02011-06-15 23:02:42 +00003890ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
3891 ObjCBridgeCastKind Kind,
3892 SourceLocation BridgeKeywordLoc,
3893 TypeSourceInfo *TSInfo,
3894 Expr *SubExpr) {
John McCalleb075542011-08-26 00:48:42 +00003895 ExprResult SubResult = UsualUnaryConversions(SubExpr);
3896 if (SubResult.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003897 SubExpr = SubResult.get();
John McCalleb075542011-08-26 00:48:42 +00003898
John McCall31168b02011-06-15 23:02:42 +00003899 QualType T = TSInfo->getType();
3900 QualType FromType = SubExpr->getType();
3901
John McCall9320b872011-09-09 05:25:32 +00003902 CastKind CK;
3903
John McCall31168b02011-06-15 23:02:42 +00003904 bool MustConsume = false;
3905 if (T->isDependentType() || SubExpr->isTypeDependent()) {
3906 // Okay: we'll build a dependent expression type.
John McCall9320b872011-09-09 05:25:32 +00003907 CK = CK_Dependent;
John McCall31168b02011-06-15 23:02:42 +00003908 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
3909 // Casting CF -> id
John McCall9320b872011-09-09 05:25:32 +00003910 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
3911 : CK_CPointerToObjCPointerCast);
John McCall31168b02011-06-15 23:02:42 +00003912 switch (Kind) {
3913 case OBC_Bridge:
3914 break;
3915
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003916 case OBC_BridgeRetained: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003917 bool br = isKnownName("CFBridgingRelease");
John McCall31168b02011-06-15 23:02:42 +00003918 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3919 << 2
3920 << FromType
3921 << (T->isBlockPointerType()? 1 : 0)
3922 << T
3923 << SubExpr->getSourceRange()
3924 << Kind;
3925 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3926 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
3927 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003928 << FromType << br
John McCall31168b02011-06-15 23:02:42 +00003929 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003930 br ? "CFBridgingRelease "
3931 : "__bridge_transfer ");
John McCall31168b02011-06-15 23:02:42 +00003932
3933 Kind = OBC_Bridge;
3934 break;
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003935 }
John McCall31168b02011-06-15 23:02:42 +00003936
3937 case OBC_BridgeTransfer:
3938 // We must consume the Objective-C object produced by the cast.
3939 MustConsume = true;
3940 break;
3941 }
3942 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
3943 // Okay: id -> CF
John McCall9320b872011-09-09 05:25:32 +00003944 CK = CK_BitCast;
John McCall31168b02011-06-15 23:02:42 +00003945 switch (Kind) {
3946 case OBC_Bridge:
John McCall4db5c3c2011-07-07 06:58:02 +00003947 // Reclaiming a value that's going to be __bridge-casted to CF
3948 // is very dangerous, so we don't do it.
3949 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCall31168b02011-06-15 23:02:42 +00003950 break;
3951
3952 case OBC_BridgeRetained:
3953 // Produce the object before casting it.
3954 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall2d637d22011-09-10 06:18:15 +00003955 CK_ARCProduceObject,
Craig Topperc3ec1492014-05-26 06:22:03 +00003956 SubExpr, nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00003957 break;
3958
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003959 case OBC_BridgeTransfer: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003960 bool br = isKnownName("CFBridgingRetain");
John McCall31168b02011-06-15 23:02:42 +00003961 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3962 << (FromType->isBlockPointerType()? 1 : 0)
3963 << FromType
3964 << 2
3965 << T
3966 << SubExpr->getSourceRange()
3967 << Kind;
3968
3969 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3970 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
3971 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003972 << T << br
3973 << FixItHint::CreateReplacement(BridgeKeywordLoc,
3974 br ? "CFBridgingRetain " : "__bridge_retained");
John McCall31168b02011-06-15 23:02:42 +00003975
3976 Kind = OBC_Bridge;
3977 break;
3978 }
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003979 }
John McCall31168b02011-06-15 23:02:42 +00003980 } else {
3981 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
3982 << FromType << T << Kind
3983 << SubExpr->getSourceRange()
3984 << TSInfo->getTypeLoc().getSourceRange();
3985 return ExprError();
3986 }
3987
John McCall9320b872011-09-09 05:25:32 +00003988 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCall31168b02011-06-15 23:02:42 +00003989 BridgeKeywordLoc,
3990 TSInfo, SubExpr);
3991
3992 if (MustConsume) {
3993 ExprNeedsCleanups = true;
John McCall2d637d22011-09-10 06:18:15 +00003994 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
Craig Topperc3ec1492014-05-26 06:22:03 +00003995 nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00003996 }
3997
3998 return Result;
3999}
4000
4001ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
4002 SourceLocation LParenLoc,
4003 ObjCBridgeCastKind Kind,
4004 SourceLocation BridgeKeywordLoc,
4005 ParsedType Type,
4006 SourceLocation RParenLoc,
4007 Expr *SubExpr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004008 TypeSourceInfo *TSInfo = nullptr;
John McCall31168b02011-06-15 23:02:42 +00004009 QualType T = GetTypeFromParser(Type, &TSInfo);
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00004010 if (Kind == OBC_Bridge)
4011 CheckTollFreeBridgeCast(T, SubExpr);
John McCall31168b02011-06-15 23:02:42 +00004012 if (!TSInfo)
4013 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
4014 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
4015 SubExpr);
4016}