blob: 0e1751a503b7b22bf69b4eb9fa8a862999c5eda1 [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,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000136 nullptr, 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,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000211 nullptr, nullptr,
212 SourceLocation());
Patrick Beard0caa3942012-04-19 00:25:12 +0000213 } else {
214 // Otherwise, require a declaration of NSNumber.
215 S.Diag(Loc, diag::err_undeclared_nsnumber);
Craig Topperc3ec1492014-05-26 06:22:03 +0000216 return nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000217 }
218 } else if (!S.NSNumberDecl->hasDefinition()) {
219 S.Diag(Loc, diag::err_undeclared_nsnumber);
Craig Topperc3ec1492014-05-26 06:22:03 +0000220 return nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000221 }
Alex Denisove36748a2015-02-16 16:17:05 +0000222 }
223
224 if (S.NSNumberPointer.isNull()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000225 // generate the pointer to NSNumber type.
Jordy Roseaca01f92012-05-12 17:32:52 +0000226 QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
227 S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000228 }
229
Ted Kremeneke65b0862012-03-06 20:05:56 +0000230 // Look for the appropriate method within NSNumber.
Jordy Roseaca01f92012-05-12 17:32:52 +0000231 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000232 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000233 // create a stub definition this NSNumber factory method.
Craig Topperc3ec1492014-05-26 06:22:03 +0000234 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000235 Method =
236 ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
237 S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
238 /*isInstance=*/false, /*isVariadic=*/false,
239 /*isPropertyAccessor=*/false,
240 /*isImplicitlyDeclared=*/true,
241 /*isDefined=*/false, ObjCMethodDecl::Required,
242 /*HasRelatedResultType=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000243 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
244 SourceLocation(), SourceLocation(),
Patrick Beard0caa3942012-04-19 00:25:12 +0000245 &CX.Idents.get("value"),
Craig Topperc3ec1492014-05-26 06:22:03 +0000246 NumberType, /*TInfo=*/nullptr,
247 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000248 Method->setMethodParams(S.Context, value, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000249 }
250
Jordy Rose08e500c2012-05-12 17:32:44 +0000251 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
Craig Topperc3ec1492014-05-26 06:22:03 +0000252 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000253
254 // Note: if the parameter type is out-of-line, we'll catch it later in the
255 // implicit conversion.
256
257 S.NSNumberLiteralMethods[*Kind] = Method;
258 return Method;
259}
260
Patrick Beard0caa3942012-04-19 00:25:12 +0000261/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
262/// numeric literal expression. Type of the expression will be "NSNumber *".
Ted Kremeneke65b0862012-03-06 20:05:56 +0000263ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000264 // Determine the type of the literal.
265 QualType NumberType = Number->getType();
266 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
267 // In C, character literals have type 'int'. That's not the type we want
268 // to use to determine the Objective-c literal kind.
269 switch (Char->getKind()) {
270 case CharacterLiteral::Ascii:
271 NumberType = Context.CharTy;
272 break;
273
274 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000275 NumberType = Context.getWideCharType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000276 break;
277
278 case CharacterLiteral::UTF16:
279 NumberType = Context.Char16Ty;
280 break;
281
282 case CharacterLiteral::UTF32:
283 NumberType = Context.Char32Ty;
284 break;
285 }
286 }
287
Ted Kremeneke65b0862012-03-06 20:05:56 +0000288 // Look for the appropriate method within NSNumber.
289 // Construct the literal.
Patrick Beard2565c592012-05-01 21:47:19 +0000290 SourceRange NR(Number->getSourceRange());
Patrick Beard0caa3942012-04-19 00:25:12 +0000291 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
Patrick Beard2565c592012-05-01 21:47:19 +0000292 true, NR);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000293 if (!Method)
294 return ExprError();
295
296 // Convert the number to the type that the parameter expects.
Alp Toker03376dc2014-07-07 09:02:20 +0000297 ParmVarDecl *ParamDecl = Method->parameters()[0];
Patrick Beard2565c592012-05-01 21:47:19 +0000298 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
299 ParamDecl);
300 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
301 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000302 Number);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000303 if (ConvertedNumber.isInvalid())
304 return ExprError();
305 Number = ConvertedNumber.get();
306
Patrick Beard2565c592012-05-01 21:47:19 +0000307 // Use the effective source range of the literal, including the leading '@'.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000308 return MaybeBindToTemporary(
Patrick Beard2565c592012-05-01 21:47:19 +0000309 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
310 SourceRange(AtLoc, NR.getEnd())));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000311}
312
313ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
314 SourceLocation ValueLoc,
315 bool Value) {
316 ExprResult Inner;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000317 if (getLangOpts().CPlusPlus) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000318 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
319 } else {
320 // C doesn't actually have a way to represent literal values of type
321 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
322 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
323 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
324 CK_IntegralToBoolean);
325 }
326
327 return BuildObjCNumericLiteral(AtLoc, Inner.get());
328}
329
330/// \brief Check that the given expression is a valid element of an Objective-C
331/// collection literal.
332static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000333 QualType T,
334 bool ArrayLiteral = false) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000335 // If the expression is type-dependent, there's nothing for us to do.
336 if (Element->isTypeDependent())
337 return Element;
338
339 ExprResult Result = S.CheckPlaceholderExpr(Element);
340 if (Result.isInvalid())
341 return ExprError();
342 Element = Result.get();
343
344 // In C++, check for an implicit conversion to an Objective-C object pointer
345 // type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000346 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000347 InitializedEntity Entity
Jordy Roseaca01f92012-05-12 17:32:52 +0000348 = InitializedEntity::InitializeParameter(S.Context, T,
349 /*Consumed=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000350 InitializationKind Kind
Jordy Roseaca01f92012-05-12 17:32:52 +0000351 = InitializationKind::CreateCopy(Element->getLocStart(),
352 SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000353 InitializationSequence Seq(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000354 if (!Seq.Failed())
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000355 return Seq.Perform(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000356 }
357
358 Expr *OrigElement = Element;
359
360 // Perform lvalue-to-rvalue conversion.
361 Result = S.DefaultLvalueConversion(Element);
362 if (Result.isInvalid())
363 return ExprError();
364 Element = Result.get();
365
366 // Make sure that we have an Objective-C pointer type or block.
367 if (!Element->getType()->isObjCObjectPointerType() &&
368 !Element->getType()->isBlockPointerType()) {
369 bool Recovered = false;
370
371 // If this is potentially an Objective-C numeric literal, add the '@'.
372 if (isa<IntegerLiteral>(OrigElement) ||
373 isa<CharacterLiteral>(OrigElement) ||
374 isa<FloatingLiteral>(OrigElement) ||
375 isa<ObjCBoolLiteralExpr>(OrigElement) ||
376 isa<CXXBoolLiteralExpr>(OrigElement)) {
377 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
378 int Which = isa<CharacterLiteral>(OrigElement) ? 1
379 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
380 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
381 : 3;
382
383 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
384 << Which << OrigElement->getSourceRange()
385 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
386
387 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
388 OrigElement);
389 if (Result.isInvalid())
390 return ExprError();
391
392 Element = Result.get();
393 Recovered = true;
394 }
395 }
396 // If this is potentially an Objective-C string literal, add the '@'.
397 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
398 if (String->isAscii()) {
399 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
400 << 0 << OrigElement->getSourceRange()
401 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
402
403 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
404 if (Result.isInvalid())
405 return ExprError();
406
407 Element = Result.get();
408 Recovered = true;
409 }
410 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000411
Ted Kremeneke65b0862012-03-06 20:05:56 +0000412 if (!Recovered) {
413 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
414 << Element->getType();
415 return ExprError();
416 }
417 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000418 if (ArrayLiteral)
Ted Kremenek197fee42013-10-09 22:34:33 +0000419 if (ObjCStringLiteral *getString =
420 dyn_cast<ObjCStringLiteral>(OrigElement)) {
421 if (StringLiteral *SL = getString->getString()) {
422 unsigned numConcat = SL->getNumConcatenated();
423 if (numConcat > 1) {
424 // Only warn if the concatenated string doesn't come from a macro.
425 bool hasMacro = false;
426 for (unsigned i = 0; i < numConcat ; ++i)
427 if (SL->getStrTokenLoc(i).isMacroID()) {
428 hasMacro = true;
429 break;
430 }
431 if (!hasMacro)
432 S.Diag(Element->getLocStart(),
433 diag::warn_concatenated_nsarray_literal)
434 << Element->getType();
435 }
436 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000437 }
438
Ted Kremeneke65b0862012-03-06 20:05:56 +0000439 // Make sure that the element has the type that the container factory
440 // function expects.
441 return S.PerformCopyInitialization(
442 InitializedEntity::InitializeParameter(S.Context, T,
443 /*Consumed=*/false),
444 Element->getLocStart(), Element);
445}
446
Patrick Beard0caa3942012-04-19 00:25:12 +0000447ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
448 if (ValueExpr->isTypeDependent()) {
449 ObjCBoxedExpr *BoxedExpr =
Craig Topperc3ec1492014-05-26 06:22:03 +0000450 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000451 return BoxedExpr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000452 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000453 ObjCMethodDecl *BoxingMethod = nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000454 QualType BoxedType;
455 // Convert the expression to an RValue, so we can check for pointer types...
456 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
457 if (RValue.isInvalid()) {
458 return ExprError();
459 }
460 ValueExpr = RValue.get();
Patrick Beard2565c592012-05-01 21:47:19 +0000461 QualType ValueType(ValueExpr->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +0000462 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
463 QualType PointeeType = PT->getPointeeType();
464 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
465
466 if (!NSStringDecl) {
467 IdentifierInfo *NSStringId =
468 NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
469 NamedDecl *Decl = LookupSingleName(TUScope, NSStringId,
470 SR.getBegin(), LookupOrdinaryName);
471 NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl);
472 if (!NSStringDecl) {
473 if (getLangOpts().DebuggerObjCLiteral) {
474 // Support boxed expressions in the debugger w/o NSString declaration.
Jordy Roseaca01f92012-05-12 17:32:52 +0000475 DeclContext *TU = Context.getTranslationUnitDecl();
476 NSStringDecl = ObjCInterfaceDecl::Create(Context, TU,
477 SourceLocation(),
478 NSStringId,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000479 nullptr, nullptr,
480 SourceLocation());
Patrick Beard0caa3942012-04-19 00:25:12 +0000481 } else {
482 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
483 return ExprError();
484 }
485 } else if (!NSStringDecl->hasDefinition()) {
486 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
487 return ExprError();
488 }
489 assert(NSStringDecl && "NSStringDecl should not be NULL");
Jordy Roseaca01f92012-05-12 17:32:52 +0000490 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
491 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000492 }
493
494 if (!StringWithUTF8StringMethod) {
495 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
496 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
497
498 // Look for the appropriate method within NSString.
Jordy Rose08e500c2012-05-12 17:32:44 +0000499 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
500 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000501 // Debugger needs to work even if NSString hasn't been defined.
Craig Topperc3ec1492014-05-26 06:22:03 +0000502 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000503 ObjCMethodDecl *M = ObjCMethodDecl::Create(
504 Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
505 NSStringPointer, ReturnTInfo, NSStringDecl,
506 /*isInstance=*/false, /*isVariadic=*/false,
507 /*isPropertyAccessor=*/false,
508 /*isImplicitlyDeclared=*/true,
509 /*isDefined=*/false, ObjCMethodDecl::Required,
510 /*HasRelatedResultType=*/false);
Jordy Roseaca01f92012-05-12 17:32:52 +0000511 QualType ConstCharType = Context.CharTy.withConst();
Patrick Beard0caa3942012-04-19 00:25:12 +0000512 ParmVarDecl *value =
513 ParmVarDecl::Create(Context, M,
514 SourceLocation(), SourceLocation(),
515 &Context.Idents.get("value"),
Jordy Roseaca01f92012-05-12 17:32:52 +0000516 Context.getPointerType(ConstCharType),
Craig Topperc3ec1492014-05-26 06:22:03 +0000517 /*TInfo=*/nullptr,
518 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000519 M->setMethodParams(Context, value, None);
Jordy Rose08e500c2012-05-12 17:32:44 +0000520 BoxingMethod = M;
Patrick Beard0caa3942012-04-19 00:25:12 +0000521 }
Jordy Rose890f4572012-05-12 15:53:41 +0000522
Jordy Rose08e500c2012-05-12 17:32:44 +0000523 if (!validateBoxingMethod(*this, SR.getBegin(), NSStringDecl,
524 stringWithUTF8String, BoxingMethod))
525 return ExprError();
526
527 StringWithUTF8StringMethod = BoxingMethod;
Patrick Beard0caa3942012-04-19 00:25:12 +0000528 }
529
530 BoxingMethod = StringWithUTF8StringMethod;
531 BoxedType = NSStringPointer;
532 }
Patrick Beard2565c592012-05-01 21:47:19 +0000533 } else if (ValueType->isBuiltinType()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000534 // The other types we support are numeric, char and BOOL/bool. We could also
535 // provide limited support for structure types, such as NSRange, NSRect, and
536 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
537 // for more details.
538
539 // Check for a top-level character literal.
540 if (const CharacterLiteral *Char =
541 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
542 // In C, character literals have type 'int'. That's not the type we want
543 // to use to determine the Objective-c literal kind.
544 switch (Char->getKind()) {
545 case CharacterLiteral::Ascii:
546 ValueType = Context.CharTy;
547 break;
548
549 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000550 ValueType = Context.getWideCharType();
Patrick Beard0caa3942012-04-19 00:25:12 +0000551 break;
552
553 case CharacterLiteral::UTF16:
554 ValueType = Context.Char16Ty;
555 break;
556
557 case CharacterLiteral::UTF32:
558 ValueType = Context.Char32Ty;
559 break;
560 }
561 }
Fariborz Jahanian5d64abb2014-06-18 20:49:02 +0000562 CheckForIntOverflow(ValueExpr);
Patrick Beard0caa3942012-04-19 00:25:12 +0000563 // FIXME: Do I need to do anything special with BoolTy expressions?
564
565 // Look for the appropriate method within NSNumber.
566 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType);
567 BoxedType = NSNumberPointer;
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000568 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
569 if (!ET->getDecl()->isComplete()) {
570 Diag(SR.getBegin(), diag::err_objc_incomplete_boxed_expression_type)
571 << ValueType << ValueExpr->getSourceRange();
572 return ExprError();
573 }
574
575 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(),
576 ET->getDecl()->getIntegerType());
577 BoxedType = NSNumberPointer;
Alex Denisovfde64952015-06-26 05:28:36 +0000578 } else if (ValueType->isObjCBoxableRecordType()) {
579 // Support for structure types, that marked as objc_boxable
580 // struct __attribute__((objc_boxable)) s { ... };
581
582 // Look up the NSValue class, if we haven't done so already. It's cached
583 // in the Sema instance.
584 if (!NSValueDecl) {
585 IdentifierInfo *NSValueId =
586 NSAPIObj->getNSClassId(NSAPI::ClassId_NSValue);
587 NamedDecl *IF = LookupSingleName(TUScope, NSValueId,
588 SR.getBegin(), Sema::LookupOrdinaryName);
589 NSValueDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
590 if (!NSValueDecl) {
591 if (getLangOpts().DebuggerObjCLiteral) {
592 // Create a stub definition of NSValue.
593 DeclContext *TU = Context.getTranslationUnitDecl();
594 NSValueDecl = ObjCInterfaceDecl::Create(Context, TU,
595 SourceLocation(), NSValueId,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000596 nullptr, nullptr,
597 SourceLocation());
Alex Denisovfde64952015-06-26 05:28:36 +0000598 } else {
599 // Otherwise, require a declaration of NSValue.
600 Diag(SR.getBegin(), diag::err_undeclared_nsvalue);
601 return ExprError();
602 }
603 } else if (!NSValueDecl->hasDefinition()) {
604 Diag(SR.getBegin(), diag::err_undeclared_nsvalue);
605 return ExprError();
606 }
607
608 // generate the pointer to NSValue type.
609 QualType NSValueObject = Context.getObjCInterfaceType(NSValueDecl);
610 NSValuePointer = Context.getObjCObjectPointerType(NSValueObject);
611 }
612
613 if (!ValueWithBytesObjCTypeMethod) {
614 IdentifierInfo *II[] = {
615 &Context.Idents.get("valueWithBytes"),
616 &Context.Idents.get("objCType")
617 };
618 Selector ValueWithBytesObjCType = Context.Selectors.getSelector(2, II);
619
620 // Look for the appropriate method within NSValue.
621 BoxingMethod = NSValueDecl->lookupClassMethod(ValueWithBytesObjCType);
622 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
623 // Debugger needs to work even if NSValue hasn't been defined.
624 TypeSourceInfo *ReturnTInfo = nullptr;
625 ObjCMethodDecl *M = ObjCMethodDecl::Create(
626 Context,
627 SourceLocation(),
628 SourceLocation(),
629 ValueWithBytesObjCType,
630 NSValuePointer,
631 ReturnTInfo,
632 NSValueDecl,
633 /*isInstance=*/false,
634 /*isVariadic=*/false,
635 /*isPropertyAccessor=*/false,
636 /*isImplicitlyDeclared=*/true,
637 /*isDefined=*/false,
638 ObjCMethodDecl::Required,
639 /*HasRelatedResultType=*/false);
640
641 SmallVector<ParmVarDecl *, 2> Params;
642
643 ParmVarDecl *bytes =
644 ParmVarDecl::Create(Context, M,
645 SourceLocation(), SourceLocation(),
646 &Context.Idents.get("bytes"),
647 Context.VoidPtrTy.withConst(),
648 /*TInfo=*/nullptr,
649 SC_None, nullptr);
650 Params.push_back(bytes);
651
652 QualType ConstCharType = Context.CharTy.withConst();
653 ParmVarDecl *type =
654 ParmVarDecl::Create(Context, M,
655 SourceLocation(), SourceLocation(),
656 &Context.Idents.get("type"),
657 Context.getPointerType(ConstCharType),
658 /*TInfo=*/nullptr,
659 SC_None, nullptr);
660 Params.push_back(type);
661
662 M->setMethodParams(Context, Params, None);
663 BoxingMethod = M;
664 }
665
666 if (!validateBoxingMethod(*this, SR.getBegin(), NSValueDecl,
667 ValueWithBytesObjCType, BoxingMethod))
668 return ExprError();
669
670 ValueWithBytesObjCTypeMethod = BoxingMethod;
671 }
672
673 if (!ValueType.isTriviallyCopyableType(Context)) {
674 Diag(SR.getBegin(),
675 diag::err_objc_non_trivially_copyable_boxed_expression_type)
676 << ValueType << ValueExpr->getSourceRange();
677 return ExprError();
678 }
679
680 BoxingMethod = ValueWithBytesObjCTypeMethod;
681 BoxedType = NSValuePointer;
Patrick Beard0caa3942012-04-19 00:25:12 +0000682 }
683
684 if (!BoxingMethod) {
685 Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type)
686 << ValueType << ValueExpr->getSourceRange();
687 return ExprError();
688 }
689
Alex Denisovfde64952015-06-26 05:28:36 +0000690 DiagnoseUseOfDecl(BoxingMethod, SR.getBegin());
691
692 ExprResult ConvertedValueExpr;
693 if (ValueType->isObjCBoxableRecordType()) {
694 InitializedEntity IE = InitializedEntity::InitializeTemporary(ValueType);
695 ConvertedValueExpr = PerformCopyInitialization(IE, ValueExpr->getExprLoc(),
696 ValueExpr);
697 } else {
698 // Convert the expression to the type that the parameter requires.
699 ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
700 InitializedEntity IE = InitializedEntity::InitializeParameter(Context,
701 ParamDecl);
702 ConvertedValueExpr = PerformCopyInitialization(IE, SourceLocation(),
703 ValueExpr);
704 }
705
Patrick Beard0caa3942012-04-19 00:25:12 +0000706 if (ConvertedValueExpr.isInvalid())
707 return ExprError();
708 ValueExpr = ConvertedValueExpr.get();
709
710 ObjCBoxedExpr *BoxedExpr =
711 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
712 BoxingMethod, SR);
713 return MaybeBindToTemporary(BoxedExpr);
714}
715
John McCallf2538342012-07-31 05:14:30 +0000716/// Build an ObjC subscript pseudo-object expression, given that
717/// that's supported by the runtime.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000718ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
719 Expr *IndexExpr,
720 ObjCMethodDecl *getterMethod,
721 ObjCMethodDecl *setterMethod) {
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +0000722 assert(!LangOpts.isSubscriptPointerArithmetic());
John McCall5fb5df92012-06-20 06:18:46 +0000723
John McCallf2538342012-07-31 05:14:30 +0000724 // We can't get dependent types here; our callers should have
725 // filtered them out.
726 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
727 "base or index cannot have dependent type here");
728
729 // Filter out placeholders in the index. In theory, overloads could
730 // be preserved here, although that might not actually work correctly.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000731 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
732 if (Result.isInvalid())
733 return ExprError();
734 IndexExpr = Result.get();
735
John McCallf2538342012-07-31 05:14:30 +0000736 // Perform lvalue-to-rvalue conversion on the base.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000737 Result = DefaultLvalueConversion(BaseExpr);
738 if (Result.isInvalid())
739 return ExprError();
740 BaseExpr = Result.get();
John McCallf2538342012-07-31 05:14:30 +0000741
742 // Build the pseudo-object expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000743 return ObjCSubscriptRefExpr::Create(Context, BaseExpr, IndexExpr,
744 Context.PseudoObjectTy, getterMethod,
745 setterMethod, RB);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000746}
747
748ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
749 // Look up the NSArray class, if we haven't done so already.
750 if (!NSArrayDecl) {
751 NamedDecl *IF = LookupSingleName(TUScope,
752 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
753 SR.getBegin(),
754 LookupOrdinaryName);
755 NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000756 if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000757 NSArrayDecl = ObjCInterfaceDecl::Create (Context,
758 Context.getTranslationUnitDecl(),
759 SourceLocation(),
760 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
Douglas Gregor85f3f952015-07-07 03:57:15 +0000761 nullptr, nullptr, SourceLocation());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000762
763 if (!NSArrayDecl) {
764 Diag(SR.getBegin(), diag::err_undeclared_nsarray);
765 return ExprError();
766 }
767 }
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000768
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000769 // Find the arrayWithObjects:count: method, if we haven't done so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000770 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000771 if (!ArrayWithObjectsMethod) {
772 Selector
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000773 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
774 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000775 if (!Method && getLangOpts().DebuggerObjCLiteral) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000776 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000777 Method = ObjCMethodDecl::Create(
778 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000779 Context.getTranslationUnitDecl(), false /*Instance*/,
Alp Toker314cc812014-01-25 16:55:45 +0000780 false /*isVariadic*/,
781 /*isPropertyAccessor=*/false,
782 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
783 ObjCMethodDecl::Required, false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000784 SmallVector<ParmVarDecl *, 2> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000785 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000786 SourceLocation(),
787 SourceLocation(),
788 &Context.Idents.get("objects"),
789 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000790 /*TInfo=*/nullptr,
791 SC_None, nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000792 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000793 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000794 SourceLocation(),
795 SourceLocation(),
796 &Context.Idents.get("cnt"),
797 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000798 /*TInfo=*/nullptr, SC_None,
799 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000800 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000801 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000802 }
803
Jordy Rose08e500c2012-05-12 17:32:44 +0000804 if (!validateBoxingMethod(*this, SR.getBegin(), NSArrayDecl, Sel, Method))
Ted Kremeneke65b0862012-03-06 20:05:56 +0000805 return ExprError();
Jordy Rose08e500c2012-05-12 17:32:44 +0000806
Jordy Rose4af44872012-05-12 17:32:56 +0000807 // Dig out the type that all elements should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000808 QualType T = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000809 const PointerType *PtrT = T->getAs<PointerType>();
810 if (!PtrT ||
811 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
812 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
813 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000814 Diag(Method->parameters()[0]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000815 diag::note_objc_literal_method_param)
816 << 0 << T
817 << Context.getPointerType(IdT.withConst());
818 return ExprError();
819 }
820
821 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000822 if (!Method->parameters()[1]->getType()->isIntegerType()) {
Jordy Rose4af44872012-05-12 17:32:56 +0000823 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
824 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000825 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000826 diag::note_objc_literal_method_param)
827 << 1
Alp Toker03376dc2014-07-07 09:02:20 +0000828 << Method->parameters()[1]->getType()
Jordy Rose4af44872012-05-12 17:32:56 +0000829 << "integral";
830 return ExprError();
831 }
832
833 // We've found a good +arrayWithObjects:count: method. Save it!
Jordy Rose08e500c2012-05-12 17:32:44 +0000834 ArrayWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000835 }
836
Alp Toker03376dc2014-07-07 09:02:20 +0000837 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000838 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000839
840 // Check that each of the elements provided is valid in a collection literal,
841 // performing conversions as necessary.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000842 Expr **ElementsBuffer = Elements.data();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000843 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
844 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
845 ElementsBuffer[I],
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000846 RequiredType, true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000847 if (Converted.isInvalid())
848 return ExprError();
849
850 ElementsBuffer[I] = Converted.get();
851 }
852
853 QualType Ty
854 = Context.getObjCObjectPointerType(
855 Context.getObjCInterfaceType(NSArrayDecl));
856
857 return MaybeBindToTemporary(
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000858 ObjCArrayLiteral::Create(Context, Elements, Ty,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000859 ArrayWithObjectsMethod, SR));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000860}
861
862ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
863 ObjCDictionaryElement *Elements,
864 unsigned NumElements) {
865 // Look up the NSDictionary class, if we haven't done so already.
866 if (!NSDictionaryDecl) {
867 NamedDecl *IF = LookupSingleName(TUScope,
868 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
869 SR.getBegin(), LookupOrdinaryName);
870 NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000871 if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000872 NSDictionaryDecl = ObjCInterfaceDecl::Create (Context,
873 Context.getTranslationUnitDecl(),
874 SourceLocation(),
875 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
Douglas Gregor85f3f952015-07-07 03:57:15 +0000876 nullptr, nullptr, SourceLocation());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000877
878 if (!NSDictionaryDecl) {
879 Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
880 return ExprError();
881 }
882 }
883
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000884 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
885 // so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000886 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000887 if (!DictionaryWithObjectsMethod) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000888 Selector Sel = NSAPIObj->getNSDictionarySelector(
889 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
890 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000891 if (!Method && getLangOpts().DebuggerObjCLiteral) {
892 Method = ObjCMethodDecl::Create(Context,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000893 SourceLocation(), SourceLocation(), Sel,
894 IdT,
Craig Topperc3ec1492014-05-26 06:22:03 +0000895 nullptr /*TypeSourceInfo */,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000896 Context.getTranslationUnitDecl(),
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000897 false /*Instance*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000898 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000899 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
900 ObjCMethodDecl::Required,
901 false);
902 SmallVector<ParmVarDecl *, 3> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000903 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000904 SourceLocation(),
905 SourceLocation(),
906 &Context.Idents.get("objects"),
907 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000908 /*TInfo=*/nullptr, SC_None,
909 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000910 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000911 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000912 SourceLocation(),
913 SourceLocation(),
914 &Context.Idents.get("keys"),
915 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000916 /*TInfo=*/nullptr, SC_None,
917 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000918 Params.push_back(keys);
Jordy Rose08e500c2012-05-12 17:32:44 +0000919 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000920 SourceLocation(),
921 SourceLocation(),
922 &Context.Idents.get("cnt"),
923 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000924 /*TInfo=*/nullptr, SC_None,
925 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000926 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000927 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000928 }
929
Jordy Rose08e500c2012-05-12 17:32:44 +0000930 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
931 Method))
932 return ExprError();
933
Jordy Rose4af44872012-05-12 17:32:56 +0000934 // Dig out the type that all values should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000935 QualType ValueT = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000936 const PointerType *PtrValue = ValueT->getAs<PointerType>();
937 if (!PtrValue ||
938 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000939 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
Jordy Rose4af44872012-05-12 17:32:56 +0000940 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000941 Diag(Method->parameters()[0]->getLocation(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000942 diag::note_objc_literal_method_param)
Jordy Rose4af44872012-05-12 17:32:56 +0000943 << 0 << ValueT
Ted Kremeneke65b0862012-03-06 20:05:56 +0000944 << Context.getPointerType(IdT.withConst());
945 return ExprError();
946 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000947
Jordy Rose4af44872012-05-12 17:32:56 +0000948 // Dig out the type that all keys should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000949 QualType KeyT = Method->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000950 const PointerType *PtrKey = KeyT->getAs<PointerType>();
951 if (!PtrKey ||
952 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
953 IdT)) {
954 bool err = true;
955 if (PtrKey) {
956 if (QIDNSCopying.isNull()) {
957 // key argument of selector is id<NSCopying>?
958 if (ObjCProtocolDecl *NSCopyingPDecl =
959 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
960 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
961 QIDNSCopying =
962 Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
963 (ObjCProtocolDecl**) PQ,1);
964 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
965 }
966 }
967 if (!QIDNSCopying.isNull())
968 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
969 QIDNSCopying);
970 }
971
972 if (err) {
973 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
974 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000975 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000976 diag::note_objc_literal_method_param)
977 << 1 << KeyT
978 << Context.getPointerType(IdT.withConst());
979 return ExprError();
980 }
981 }
982
983 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000984 QualType CountType = Method->parameters()[2]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000985 if (!CountType->isIntegerType()) {
986 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
987 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000988 Diag(Method->parameters()[2]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000989 diag::note_objc_literal_method_param)
990 << 2 << CountType
991 << "integral";
992 return ExprError();
993 }
994
995 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
996 DictionaryWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000997 }
998
Alp Toker03376dc2014-07-07 09:02:20 +0000999 QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +00001000 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
Alp Toker03376dc2014-07-07 09:02:20 +00001001 QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +00001002 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
1003
Ted Kremeneke65b0862012-03-06 20:05:56 +00001004 // Check that each of the keys and values provided is valid in a collection
1005 // literal, performing conversions as necessary.
1006 bool HasPackExpansions = false;
1007 for (unsigned I = 0, N = NumElements; I != N; ++I) {
1008 // Check the key.
1009 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
1010 KeyT);
1011 if (Key.isInvalid())
1012 return ExprError();
1013
1014 // Check the value.
1015 ExprResult Value
1016 = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
1017 if (Value.isInvalid())
1018 return ExprError();
1019
1020 Elements[I].Key = Key.get();
1021 Elements[I].Value = Value.get();
1022
1023 if (Elements[I].EllipsisLoc.isInvalid())
1024 continue;
1025
1026 if (!Elements[I].Key->containsUnexpandedParameterPack() &&
1027 !Elements[I].Value->containsUnexpandedParameterPack()) {
1028 Diag(Elements[I].EllipsisLoc,
1029 diag::err_pack_expansion_without_parameter_packs)
1030 << SourceRange(Elements[I].Key->getLocStart(),
1031 Elements[I].Value->getLocEnd());
1032 return ExprError();
1033 }
1034
1035 HasPackExpansions = true;
1036 }
1037
1038
1039 QualType Ty
1040 = Context.getObjCObjectPointerType(
Robert Wilhelm88e02492013-08-19 07:57:02 +00001041 Context.getObjCInterfaceType(NSDictionaryDecl));
1042 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
1043 Context, makeArrayRef(Elements, NumElements), HasPackExpansions, Ty,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +00001044 DictionaryWithObjectsMethod, SR));
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001045}
1046
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +00001047ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregorabd9e962010-04-20 15:39:42 +00001048 TypeSourceInfo *EncodedTypeInfo,
Anders Carlsson315d2292009-06-07 18:45:35 +00001049 SourceLocation RParenLoc) {
Douglas Gregorabd9e962010-04-20 15:39:42 +00001050 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlsson315d2292009-06-07 18:45:35 +00001051 QualType StrTy;
Mike Stump11289f42009-09-09 15:08:12 +00001052 if (EncodedType->isDependentType())
Anders Carlsson315d2292009-06-07 18:45:35 +00001053 StrTy = Context.DependentTy;
1054 else {
Fariborz Jahaniand9bc6c32011-06-16 22:34:44 +00001055 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
1056 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +00001057 if (RequireCompleteType(AtLoc, EncodedType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001058 diag::err_incomplete_type_objc_at_encode,
1059 EncodedTypeInfo->getTypeLoc()))
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +00001060 return ExprError();
1061
Anders Carlsson315d2292009-06-07 18:45:35 +00001062 std::string Str;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00001063 QualType NotEncodedT;
1064 Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT);
1065 if (!NotEncodedT.isNull())
1066 Diag(AtLoc, diag::warn_incomplete_encoded_type)
1067 << EncodedType << NotEncodedT;
Anders Carlsson315d2292009-06-07 18:45:35 +00001068
1069 // The type of @encode is the same as the type of the corresponding string,
1070 // which is an array type.
1071 StrTy = Context.CharTy;
1072 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001073 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Anders Carlsson315d2292009-06-07 18:45:35 +00001074 StrTy.addConst();
1075 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
1076 ArrayType::Normal, 0);
1077 }
Mike Stump11289f42009-09-09 15:08:12 +00001078
Douglas Gregorabd9e962010-04-20 15:39:42 +00001079 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlsson315d2292009-06-07 18:45:35 +00001080}
1081
John McCallfaf5fb42010-08-26 23:41:50 +00001082ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1083 SourceLocation EncodeLoc,
1084 SourceLocation LParenLoc,
1085 ParsedType ty,
1086 SourceLocation RParenLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001087 // FIXME: Preserve type source info ?
Douglas Gregorabd9e962010-04-20 15:39:42 +00001088 TypeSourceInfo *TInfo;
1089 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
1090 if (!TInfo)
1091 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
1092 PP.getLocForEndOfToken(LParenLoc));
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001093
Douglas Gregorabd9e962010-04-20 15:39:42 +00001094 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001095}
1096
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001097static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
1098 SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001099 SourceLocation LParenLoc,
1100 SourceLocation RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001101 ObjCMethodDecl *Method,
1102 ObjCMethodList &MethList) {
1103 ObjCMethodList *M = &MethList;
1104 bool Warned = false;
1105 for (M = M->getNext(); M; M=M->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00001106 ObjCMethodDecl *MatchingMethodDecl = M->getMethod();
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001107 if (MatchingMethodDecl == Method ||
1108 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
1109 MatchingMethodDecl->getSelector() != Method->getSelector())
1110 continue;
1111 if (!S.MatchTwoMethodDeclarations(Method,
1112 MatchingMethodDecl, Sema::MMS_loose)) {
1113 if (!Warned) {
1114 Warned = true;
1115 S.Diag(AtLoc, diag::warning_multiple_selectors)
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001116 << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
1117 << FixItHint::CreateInsertion(RParenLoc, ")");
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001118 S.Diag(Method->getLocation(), diag::note_method_declared_at)
1119 << Method->getDeclName();
1120 }
1121 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
1122 << MatchingMethodDecl->getDeclName();
1123 }
1124 }
1125 return Warned;
1126}
1127
1128static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001129 ObjCMethodDecl *Method,
1130 SourceLocation LParenLoc,
1131 SourceLocation RParenLoc,
1132 bool WarnMultipleSelectors) {
1133 if (!WarnMultipleSelectors ||
1134 S.Diags.isIgnored(diag::warning_multiple_selectors, SourceLocation()))
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001135 return;
1136 bool Warned = false;
1137 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1138 e = S.MethodPool.end(); b != e; b++) {
1139 // first, instance methods
1140 ObjCMethodList &InstMethList = b->second.first;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001141 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001142 Method, InstMethList))
1143 Warned = true;
1144
1145 // second, class methods
1146 ObjCMethodList &ClsMethList = b->second.second;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001147 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1148 Method, ClsMethList) || Warned)
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001149 return;
1150 }
1151}
1152
John McCallfaf5fb42010-08-26 23:41:50 +00001153ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1154 SourceLocation AtLoc,
1155 SourceLocation SelLoc,
1156 SourceLocation LParenLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001157 SourceLocation RParenLoc,
1158 bool WarnMultipleSelectors) {
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001159 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian890803f2015-04-15 17:26:21 +00001160 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001161 if (!Method)
1162 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian0571d9b2009-06-16 16:25:00 +00001163 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00001164 if (!Method) {
1165 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1166 Selector MatchedSel = OM->getSelector();
1167 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1168 RParenLoc.getLocWithOffset(-1));
1169 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1170 << Sel << MatchedSel
1171 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1172
1173 } else
1174 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001175 } else
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001176 DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
1177 WarnMultipleSelectors);
Chandler Carruth12c8f652015-03-27 00:55:05 +00001178
Fariborz Jahanian65a78b52014-05-09 19:51:39 +00001179 if (Method &&
1180 Method->getImplementationControl() != ObjCMethodDecl::Optional &&
Chandler Carruth12c8f652015-03-27 00:55:05 +00001181 !getSourceManager().isInSystemHeader(Method->getLocation()))
1182 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00001183
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001184 // In ARC, forbid the user from using @selector for
John McCall31168b02011-06-15 23:02:42 +00001185 // retain/release/autorelease/dealloc/retainCount.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001186 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001187 switch (Sel.getMethodFamily()) {
1188 case OMF_retain:
1189 case OMF_release:
1190 case OMF_autorelease:
1191 case OMF_retainCount:
1192 case OMF_dealloc:
1193 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1194 Sel << SourceRange(LParenLoc, RParenLoc);
1195 break;
1196
1197 case OMF_None:
1198 case OMF_alloc:
1199 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00001200 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00001201 case OMF_init:
1202 case OMF_mutableCopy:
1203 case OMF_new:
1204 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00001205 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00001206 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00001207 break;
1208 }
1209 }
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001210 QualType Ty = Context.getObjCSelType();
Daniel Dunbar45858d22010-02-03 20:11:42 +00001211 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001212}
1213
John McCallfaf5fb42010-08-26 23:41:50 +00001214ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1215 SourceLocation AtLoc,
1216 SourceLocation ProtoLoc,
1217 SourceLocation LParenLoc,
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001218 SourceLocation ProtoIdLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00001219 SourceLocation RParenLoc) {
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001220 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001221 if (!PDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001222 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001223 return true;
1224 }
Fariborz Jahaniana57d91c22014-07-25 19:45:01 +00001225 if (PDecl->hasDefinition())
1226 PDecl = PDecl->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00001227
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001228 QualType Ty = Context.getObjCProtoType();
1229 if (Ty.isNull())
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001230 return true;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001231 Ty = Context.getObjCObjectPointerType(Ty);
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001232 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001233}
1234
John McCall5f2d5562011-02-03 09:00:02 +00001235/// Try to capture an implicit reference to 'self'.
Eli Friedman24af8502012-02-03 22:47:37 +00001236ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1237 DeclContext *DC = getFunctionLevelDeclContext();
John McCall5f2d5562011-02-03 09:00:02 +00001238
1239 // If we're not in an ObjC method, error out. Note that, unlike the
1240 // C++ case, we don't require an instance method --- class methods
1241 // still have a 'self', and we really do still need to capture it!
1242 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1243 if (!method)
Craig Topperc3ec1492014-05-26 06:22:03 +00001244 return nullptr;
John McCall5f2d5562011-02-03 09:00:02 +00001245
Douglas Gregorfdf598e2012-02-18 09:37:24 +00001246 tryCaptureVariable(method->getSelfDecl(), Loc);
John McCall5f2d5562011-02-03 09:00:02 +00001247
1248 return method;
1249}
1250
Douglas Gregor64910ca2011-09-09 20:05:21 +00001251static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
Douglas Gregor813a0662015-06-19 18:14:38 +00001252 QualType origType = T;
1253 if (auto nullability = AttributedType::stripOuterNullability(T)) {
1254 if (T == Context.getObjCInstanceType()) {
1255 return Context.getAttributedType(
1256 AttributedType::getNullabilityAttrKind(*nullability),
1257 Context.getObjCIdType(),
1258 Context.getObjCIdType());
1259 }
1260
1261 return origType;
1262 }
1263
Douglas Gregor64910ca2011-09-09 20:05:21 +00001264 if (T == Context.getObjCInstanceType())
1265 return Context.getObjCIdType();
1266
Douglas Gregor813a0662015-06-19 18:14:38 +00001267 return origType;
Douglas Gregor64910ca2011-09-09 20:05:21 +00001268}
1269
Douglas Gregor813a0662015-06-19 18:14:38 +00001270/// Determine the result type of a message send based on the receiver type,
1271/// method, and the kind of message send.
1272///
1273/// This is the "base" result type, which will still need to be adjusted
1274/// to account for nullability.
1275static QualType getBaseMessageSendResultType(Sema &S,
1276 QualType ReceiverType,
1277 ObjCMethodDecl *Method,
1278 bool isClassMessage,
1279 bool isSuperMessage) {
Douglas Gregor33823722011-06-11 01:09:30 +00001280 assert(Method && "Must have a method");
1281 if (!Method->hasRelatedResultType())
1282 return Method->getSendResultType();
Douglas Gregor813a0662015-06-19 18:14:38 +00001283
1284 ASTContext &Context = S.Context;
1285
1286 // Local function that transfers the nullability of the method's
1287 // result type to the returned result.
1288 auto transferNullability = [&](QualType type) -> QualType {
1289 // If the method's result type has nullability, extract it.
1290 if (auto nullability = Method->getSendResultType()->getNullability(Context)){
1291 // Strip off any outer nullability sugar from the provided type.
1292 (void)AttributedType::stripOuterNullability(type);
1293
1294 // Form a new attributed type using the method result type's nullability.
1295 return Context.getAttributedType(
1296 AttributedType::getNullabilityAttrKind(*nullability),
1297 type,
1298 type);
1299 }
1300
1301 return type;
1302 };
1303
Douglas Gregor33823722011-06-11 01:09:30 +00001304 // If a method has a related return type:
1305 // - if the method found is an instance method, but the message send
1306 // was a class message send, T is the declared return type of the method
1307 // found
1308 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregor64910ca2011-09-09 20:05:21 +00001309 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor813a0662015-06-19 18:14:38 +00001310
1311 // - if the receiver is super, T is a pointer to the class of the
Douglas Gregor33823722011-06-11 01:09:30 +00001312 // enclosing method definition
1313 if (isSuperMessage) {
Douglas Gregor813a0662015-06-19 18:14:38 +00001314 if (ObjCMethodDecl *CurMethod = S.getCurMethodDecl())
1315 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) {
1316 return transferNullability(
1317 Context.getObjCObjectPointerType(
1318 Context.getObjCInterfaceType(Class)));
1319 }
Douglas Gregor33823722011-06-11 01:09:30 +00001320 }
Douglas Gregor813a0662015-06-19 18:14:38 +00001321
Douglas Gregor33823722011-06-11 01:09:30 +00001322 // - if the receiver is the name of a class U, T is a pointer to U
1323 if (ReceiverType->getAs<ObjCInterfaceType>() ||
1324 ReceiverType->isObjCQualifiedInterfaceType())
Douglas Gregor813a0662015-06-19 18:14:38 +00001325 return transferNullability(Context.getObjCObjectPointerType(ReceiverType));
1326 // - if the receiver is of type Class or qualified Class type,
Douglas Gregor33823722011-06-11 01:09:30 +00001327 // T is the declared return type of the method.
1328 if (ReceiverType->isObjCClassType() ||
1329 ReceiverType->isObjCQualifiedClassType())
Douglas Gregor64910ca2011-09-09 20:05:21 +00001330 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor813a0662015-06-19 18:14:38 +00001331
Douglas Gregor33823722011-06-11 01:09:30 +00001332 // - if the receiver is id, qualified id, Class, or qualified Class, T
1333 // is the receiver type, otherwise
1334 // - T is the type of the receiver expression.
Douglas Gregor813a0662015-06-19 18:14:38 +00001335 return transferNullability(ReceiverType);
1336}
1337
1338QualType Sema::getMessageSendResultType(QualType ReceiverType,
1339 ObjCMethodDecl *Method,
1340 bool isClassMessage,
1341 bool isSuperMessage) {
1342 // Produce the result type.
1343 QualType resultType = getBaseMessageSendResultType(*this, ReceiverType,
1344 Method,
1345 isClassMessage,
1346 isSuperMessage);
1347
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001348 // If this is a class message, ignore the nullability of the receiver.
1349 if (isClassMessage)
1350 return resultType;
1351
Douglas Gregor813a0662015-06-19 18:14:38 +00001352 // Map the nullability of the result into a table index.
1353 unsigned receiverNullabilityIdx = 0;
1354 if (auto nullability = ReceiverType->getNullability(Context))
1355 receiverNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1356
1357 unsigned resultNullabilityIdx = 0;
1358 if (auto nullability = resultType->getNullability(Context))
1359 resultNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1360
1361 // The table of nullability mappings, indexed by the receiver's nullability
1362 // and then the result type's nullability.
1363 static const uint8_t None = 0;
1364 static const uint8_t NonNull = 1;
1365 static const uint8_t Nullable = 2;
1366 static const uint8_t Unspecified = 3;
1367 static const uint8_t nullabilityMap[4][4] = {
1368 // None NonNull Nullable Unspecified
1369 /* None */ { None, None, Nullable, None },
1370 /* NonNull */ { None, NonNull, Nullable, Unspecified },
1371 /* Nullable */ { Nullable, Nullable, Nullable, Nullable },
1372 /* Unspecified */ { None, Unspecified, Nullable, Unspecified }
1373 };
1374
1375 unsigned newResultNullabilityIdx
1376 = nullabilityMap[receiverNullabilityIdx][resultNullabilityIdx];
1377 if (newResultNullabilityIdx == resultNullabilityIdx)
1378 return resultType;
1379
1380 // Strip off the existing nullability. This removes as little type sugar as
1381 // possible.
1382 do {
1383 if (auto attributed = dyn_cast<AttributedType>(resultType.getTypePtr())) {
1384 resultType = attributed->getModifiedType();
1385 } else {
1386 resultType = resultType.getDesugaredType(Context);
1387 }
1388 } while (resultType->getNullability(Context));
1389
1390 // Add nullability back if needed.
1391 if (newResultNullabilityIdx > 0) {
1392 auto newNullability
1393 = static_cast<NullabilityKind>(newResultNullabilityIdx-1);
1394 return Context.getAttributedType(
1395 AttributedType::getNullabilityAttrKind(newNullability),
1396 resultType, resultType);
1397 }
1398
1399 return resultType;
Douglas Gregor33823722011-06-11 01:09:30 +00001400}
John McCall5f2d5562011-02-03 09:00:02 +00001401
John McCall5ec7e7d2013-03-19 07:04:25 +00001402/// Look for an ObjC method whose result type exactly matches the given type.
1403static const ObjCMethodDecl *
1404findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1405 QualType instancetype) {
Alp Toker314cc812014-01-25 16:55:45 +00001406 if (MD->getReturnType() == instancetype)
1407 return MD;
John McCall5ec7e7d2013-03-19 07:04:25 +00001408
1409 // For these purposes, a method in an @implementation overrides a
1410 // declaration in the @interface.
1411 if (const ObjCImplDecl *impl =
1412 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1413 const ObjCContainerDecl *iface;
1414 if (const ObjCCategoryImplDecl *catImpl =
1415 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1416 iface = catImpl->getCategoryDecl();
1417 } else {
1418 iface = impl->getClassInterface();
1419 }
1420
1421 const ObjCMethodDecl *ifaceMD =
1422 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1423 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1424 }
1425
1426 SmallVector<const ObjCMethodDecl *, 4> overrides;
1427 MD->getOverriddenMethods(overrides);
1428 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1429 if (const ObjCMethodDecl *result =
1430 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1431 return result;
1432 }
1433
Craig Topperc3ec1492014-05-26 06:22:03 +00001434 return nullptr;
John McCall5ec7e7d2013-03-19 07:04:25 +00001435}
1436
1437void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1438 // Only complain if we're in an ObjC method and the required return
1439 // type doesn't match the method's declared return type.
1440 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1441 if (!MD || !MD->hasRelatedResultType() ||
Alp Toker314cc812014-01-25 16:55:45 +00001442 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
John McCall5ec7e7d2013-03-19 07:04:25 +00001443 return;
1444
1445 // Look for a method overridden by this method which explicitly uses
1446 // 'instancetype'.
1447 if (const ObjCMethodDecl *overridden =
1448 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
Aaron Ballman41b10ac2014-08-01 13:20:09 +00001449 SourceRange range = overridden->getReturnTypeSourceRange();
1450 SourceLocation loc = range.getBegin();
John McCall5ec7e7d2013-03-19 07:04:25 +00001451 if (loc.isInvalid())
1452 loc = overridden->getLocation();
1453 Diag(loc, diag::note_related_result_type_explicit)
1454 << /*current method*/ 1 << range;
1455 return;
1456 }
1457
1458 // Otherwise, if we have an interesting method family, note that.
1459 // This should always trigger if the above didn't.
1460 if (ObjCMethodFamily family = MD->getMethodFamily())
1461 Diag(MD->getLocation(), diag::note_related_result_type_family)
1462 << /*current method*/ 1
1463 << family;
1464}
1465
Douglas Gregor33823722011-06-11 01:09:30 +00001466void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1467 E = E->IgnoreParenImpCasts();
1468 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1469 if (!MsgSend)
1470 return;
1471
1472 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1473 if (!Method)
1474 return;
1475
1476 if (!Method->hasRelatedResultType())
1477 return;
Alp Toker314cc812014-01-25 16:55:45 +00001478
1479 if (Context.hasSameUnqualifiedType(
1480 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
Douglas Gregor33823722011-06-11 01:09:30 +00001481 return;
Alp Toker314cc812014-01-25 16:55:45 +00001482
1483 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
Douglas Gregorbab8a962011-09-08 01:46:34 +00001484 Context.getObjCInstanceType()))
1485 return;
1486
Douglas Gregor33823722011-06-11 01:09:30 +00001487 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1488 << Method->isInstanceMethod() << Method->getSelector()
1489 << MsgSend->getType();
1490}
1491
1492bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001493 MultiExprArg Args,
1494 Selector Sel,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001495 ArrayRef<SourceLocation> SelectorLocs,
1496 ObjCMethodDecl *Method,
Douglas Gregor33823722011-06-11 01:09:30 +00001497 bool isClassMessage, bool isSuperMessage,
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001498 SourceLocation lbrac, SourceLocation rbrac,
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00001499 SourceRange RecRange,
John McCall7decc9e2010-11-18 06:31:45 +00001500 QualType &ReturnType, ExprValueKind &VK) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001501 SourceLocation SelLoc;
1502 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1503 SelLoc = SelectorLocs.front();
1504 else
1505 SelLoc = lbrac;
1506
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001507 if (!Method) {
Daniel Dunbar83876b42008-09-11 00:04:36 +00001508 // Apply default argument promotion as for (C99 6.5.2.2p6).
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001509 for (unsigned i = 0, e = Args.size(); i != e; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001510 if (Args[i]->isTypeDependent())
1511 continue;
1512
John McCallcc5788c2013-03-04 07:34:02 +00001513 ExprResult result;
1514 if (getLangOpts().DebuggerSupport) {
1515 QualType paramTy; // ignored
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001516 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
John McCallcc5788c2013-03-04 07:34:02 +00001517 } else {
1518 result = DefaultArgumentPromotion(Args[i]);
1519 }
1520 if (result.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001521 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001522 Args[i] = result.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001523 }
Daniel Dunbar83876b42008-09-11 00:04:36 +00001524
John McCall31168b02011-06-15 23:02:42 +00001525 unsigned DiagID;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001526 if (getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00001527 DiagID = diag::err_arc_method_not_found;
1528 else
1529 DiagID = isClassMessage ? diag::warn_class_method_not_found
1530 : diag::warn_inst_method_not_found;
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001531 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001532 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
Fariborz Jahanian06499232013-06-18 17:10:58 +00001533 if (OMD && !OMD->isInvalidDecl()) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001534 if (getLangOpts().ObjCAutoRefCount)
1535 DiagID = diag::error_method_not_found_with_typo;
1536 else
1537 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1538 : diag::warn_instance_method_not_found_with_typo;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001539 Selector MatchedSel = OMD->getSelector();
1540 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
Fariborz Jahanian5ab87502014-08-12 22:16:41 +00001541 if (MatchedSel.isUnarySelector())
1542 Diag(SelLoc, DiagID)
1543 << Sel<< isClassMessage << MatchedSel
1544 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1545 else
1546 Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001547 }
1548 else
1549 Diag(SelLoc, DiagID)
1550 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001551 SelectorLocs.back());
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001552 // Find the class to which we are sending this message.
1553 if (ReceiverType->isObjCObjectPointerType()) {
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00001554 if (ObjCInterfaceDecl *ThisClass =
1555 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()) {
1556 Diag(ThisClass->getLocation(), diag::note_receiver_class_declared);
1557 if (!RecRange.isInvalid())
1558 if (ThisClass->lookupClassMethod(Sel))
1559 Diag(RecRange.getBegin(),diag::note_receiver_expr_here)
1560 << FixItHint::CreateReplacement(RecRange,
1561 ThisClass->getNameAsString());
1562 }
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001563 }
1564 }
John McCall3f4138c2011-07-13 17:56:40 +00001565
1566 // In debuggers, we want to use __unknown_anytype for these
1567 // results so that clients can cast them.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001568 if (getLangOpts().DebuggerSupport) {
John McCall3f4138c2011-07-13 17:56:40 +00001569 ReturnType = Context.UnknownAnyTy;
1570 } else {
1571 ReturnType = Context.getObjCIdType();
1572 }
John McCall7decc9e2010-11-18 06:31:45 +00001573 VK = VK_RValue;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001574 return false;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001575 }
Mike Stump11289f42009-09-09 15:08:12 +00001576
Douglas Gregor33823722011-06-11 01:09:30 +00001577 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1578 isSuperMessage);
Alp Toker314cc812014-01-25 16:55:45 +00001579 VK = Expr::getValueKindForType(Method->getReturnType());
Mike Stump11289f42009-09-09 15:08:12 +00001580
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001581 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian60462092010-04-08 00:30:06 +00001582 // Method might have more arguments than selector indicates. This is due
1583 // to addition of c-style arguments in method.
1584 if (Method->param_size() > Sel.getNumArgs())
1585 NumNamedArgs = Method->param_size();
1586 // FIXME. This need be cleaned up.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001587 if (Args.size() < NumNamedArgs) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001588 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001589 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
Fariborz Jahanian60462092010-04-08 00:30:06 +00001590 return false;
1591 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001592
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001593 bool IsError = false;
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001594 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001595 // We can't do any type-checking on a type-dependent argument.
1596 if (Args[i]->isTypeDependent())
1597 continue;
1598
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001599 Expr *argExpr = Args[i];
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001600
Alp Toker03376dc2014-07-07 09:02:20 +00001601 ParmVarDecl *param = Method->parameters()[i];
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001602 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump11289f42009-09-09 15:08:12 +00001603
John McCall4124c492011-10-17 18:40:02 +00001604 // Strip the unbridged-cast placeholder expression off unless it's
1605 // a consumed argument.
1606 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1607 !param->hasAttr<CFConsumedAttr>())
1608 argExpr = stripARCUnbridgedCast(argExpr);
1609
John McCallea0a39e2012-11-14 00:49:39 +00001610 // If the parameter is __unknown_anytype, infer its type
1611 // from the argument.
1612 if (param->getType() == Context.UnknownAnyTy) {
John McCallcc5788c2013-03-04 07:34:02 +00001613 QualType paramType;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001614 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
John McCallcc5788c2013-03-04 07:34:02 +00001615 if (argE.isInvalid()) {
John McCallea0a39e2012-11-14 00:49:39 +00001616 IsError = true;
John McCallcc5788c2013-03-04 07:34:02 +00001617 } else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001618 Args[i] = argE.get();
John McCallea0a39e2012-11-14 00:49:39 +00001619
John McCallcc5788c2013-03-04 07:34:02 +00001620 // Update the parameter type in-place.
1621 param->setType(paramType);
1622 }
1623 continue;
John McCallea0a39e2012-11-14 00:49:39 +00001624 }
1625
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001626 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
John McCall4124c492011-10-17 18:40:02 +00001627 param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001628 diag::err_call_incomplete_argument, argExpr))
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001629 return true;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001630
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001631 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
John McCall4124c492011-10-17 18:40:02 +00001632 param);
Fariborz Jahaniana1db7df2014-07-31 17:39:50 +00001633 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001634 if (ArgE.isInvalid())
1635 IsError = true;
1636 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001637 Args[i] = ArgE.getAs<Expr>();
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001638 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001639
1640 // Promote additional arguments to variadic methods.
1641 if (Method->isVariadic()) {
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001642 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001643 if (Args[i]->isTypeDependent())
1644 continue;
1645
Jordy Roseaca01f92012-05-12 17:32:52 +00001646 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
Craig Topperc3ec1492014-05-26 06:22:03 +00001647 nullptr);
John Wiegley01296292011-04-08 18:41:53 +00001648 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001649 Args[i] = Arg.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001650 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001651 } else {
1652 // Check for extra arguments to non-variadic methods.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001653 if (Args.size() != NumNamedArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00001654 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001655 diag::err_typecheck_call_too_many_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001656 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001657 << Method->getSourceRange()
Chris Lattner3b054132008-11-19 05:08:23 +00001658 << SourceRange(Args[NumNamedArgs]->getLocStart(),
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001659 Args.back()->getLocEnd());
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001660 }
1661 }
1662
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001663 DiagnoseSentinelCalls(Method, SelLoc, Args);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001664
1665 // Do additional checkings on method.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001666 IsError |= CheckObjCMethodCall(
Craig Topper8c2a2a02014-08-30 16:55:39 +00001667 Method, SelLoc, makeArrayRef(Args.data(), Args.size()));
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001668
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001669 return IsError;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001670}
1671
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001672bool Sema::isSelfExpr(Expr *RExpr) {
Fariborz Jahanianb3b1e172011-03-27 19:53:47 +00001673 // 'self' is objc 'self' in an objc method only.
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001674 ObjCMethodDecl *Method =
1675 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1676 return isSelfExpr(RExpr, Method);
1677}
1678
1679bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
John McCallfe96e0b2011-11-06 09:01:30 +00001680 if (!method) return false;
1681
John McCall31168b02011-06-15 23:02:42 +00001682 receiver = receiver->IgnoreParenLValueCasts();
1683 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCallfe96e0b2011-11-06 09:01:30 +00001684 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregor486b74e2011-09-27 16:10:05 +00001685 return true;
1686 return false;
Steve Naroff3f49fee2009-03-04 15:11:40 +00001687}
1688
John McCall526ab472011-10-25 17:37:35 +00001689/// LookupMethodInType - Look up a method in an ObjCObjectType.
1690ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1691 bool isInstance) {
1692 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1693 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1694 // Look it up in the main interface (and categories, etc.)
1695 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1696 return method;
1697
1698 // Okay, look for "private" methods declared in any
1699 // @implementations we've seen.
Anna Zaksc77a3b12012-07-27 19:07:44 +00001700 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1701 return method;
John McCall526ab472011-10-25 17:37:35 +00001702 }
1703
1704 // Check qualifiers.
Aaron Ballman1683f7b2014-03-17 15:55:30 +00001705 for (const auto *I : objType->quals())
1706 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
John McCall526ab472011-10-25 17:37:35 +00001707 return method;
1708
Craig Topperc3ec1492014-05-26 06:22:03 +00001709 return nullptr;
John McCall526ab472011-10-25 17:37:35 +00001710}
1711
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001712/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1713/// list of a qualified objective pointer type.
1714ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1715 const ObjCObjectPointerType *OPT,
1716 bool Instance)
1717{
Craig Topperc3ec1492014-05-26 06:22:03 +00001718 ObjCMethodDecl *MD = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +00001719 for (const auto *PROTO : OPT->quals()) {
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001720 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1721 return MD;
1722 }
1723 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001724 return nullptr;
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001725}
1726
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001727/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1728/// objective C interface. This is a property reference expression.
John McCalldadc5752010-08-24 06:29:42 +00001729ExprResult Sema::
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001730HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001731 Expr *BaseExpr, SourceLocation OpLoc,
1732 DeclarationName MemberName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001733 SourceLocation MemberLoc,
1734 SourceLocation SuperLoc, QualType SuperType,
1735 bool Super) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001736 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1737 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00001738
Benjamin Kramer365082d2012-05-19 16:34:46 +00001739 if (!MemberName.isIdentifier()) {
Douglas Gregord6459312011-04-20 18:19:55 +00001740 Diag(MemberLoc, diag::err_invalid_property_name)
1741 << MemberName << QualType(OPT, 0);
1742 return ExprError();
1743 }
Benjamin Kramer365082d2012-05-19 16:34:46 +00001744
1745 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregord6459312011-04-20 18:19:55 +00001746
Douglas Gregor4123a862011-11-14 22:10:01 +00001747 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1748 : BaseExpr->getSourceRange();
1749 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001750 diag::err_property_not_found_forward_class,
1751 MemberName, BaseRange))
Fariborz Jahanian7cabbe02010-12-16 00:56:28 +00001752 return ExprError();
Douglas Gregor4123a862011-11-14 22:10:01 +00001753
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001754 // Search for a declared property first.
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001755 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001756 // Check whether we can reference this property.
1757 if (DiagnoseUseOfDecl(PD, MemberLoc))
1758 return ExprError();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001759 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001760 return new (Context)
1761 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1762 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001763 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001764 return new (Context)
1765 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1766 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001767 }
1768 // Check protocols on qualified interfaces.
Aaron Ballman83731462014-03-17 16:14:00 +00001769 for (const auto *I : OPT->quals())
1770 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001771 // Check whether we can reference this property.
1772 if (DiagnoseUseOfDecl(PD, MemberLoc))
1773 return ExprError();
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001774
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001775 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001776 return new (Context) ObjCPropertyRefExpr(
1777 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
1778 SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001779 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001780 return new (Context)
1781 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1782 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001783 }
1784 // If that failed, look for an "implicit" property by seeing if the nullary
1785 // selector is implemented.
1786
1787 // FIXME: The logic for looking up nullary and unary selectors should be
1788 // shared with the code in ActOnInstanceMessage.
1789
1790 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1791 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001792
1793 // May be founf in property's qualified list.
1794 if (!Getter)
1795 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001796
1797 // If this reference is in an @implementation, check for 'private' methods.
1798 if (!Getter)
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001799 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001800
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001801 if (Getter) {
1802 // Check if we can reference this property.
1803 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1804 return ExprError();
1805 }
1806 // If we found a getter then this may be a valid dot-reference, we
1807 // will look for the matching setter, in case it is needed.
1808 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001809 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1810 PP.getSelectorTable(), Member);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001811 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001812
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001813 // May be founf in property's qualified list.
1814 if (!Setter)
1815 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1816
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001817 if (!Setter) {
1818 // If this reference is in an @implementation, also check for 'private'
1819 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001820 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001821 }
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001822
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001823 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1824 return ExprError();
1825
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001826 // Special warning if member name used in a property-dot for a setter accessor
1827 // does not use a property with same name; e.g. obj.X = ... for a property with
1828 // name 'x'.
1829 if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor()
1830 && !IFace->FindPropertyDeclaration(Member)) {
Fariborz Jahanian4eda2c02014-08-15 17:39:00 +00001831 if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) {
1832 // Do not warn if user is using property-dot syntax to make call to
1833 // user named setter.
1834 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter))
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001835 Diag(MemberLoc,
1836 diag::warn_property_access_suggest)
1837 << MemberName << QualType(OPT, 0) << PDecl->getName()
1838 << FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
Fariborz Jahanian4eda2c02014-08-15 17:39:00 +00001839 }
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001840 }
1841
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001842 if (Getter || Setter) {
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001843 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001844 return new (Context)
1845 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1846 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001847 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001848 return new (Context)
1849 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1850 OK_ObjCProperty, MemberLoc, BaseExpr);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001851
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001852 }
1853
1854 // Attempt to correct for typos in property names.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001855 if (TypoCorrection Corrected =
1856 CorrectTypo(DeclarationNameInfo(MemberName, MemberLoc),
1857 LookupOrdinaryName, nullptr, nullptr,
1858 llvm::make_unique<DeclFilterCCC<ObjCPropertyDecl>>(),
1859 CTK_ErrorRecovery, IFace, false, OPT)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001860 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1861 << MemberName << QualType(OPT, 0));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001862 DeclarationName TypoResult = Corrected.getCorrection();
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001863 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1864 TypoResult, MemberLoc,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001865 SuperLoc, SuperType, Super);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001866 }
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001867 ObjCInterfaceDecl *ClassDeclared;
1868 if (ObjCIvarDecl *Ivar =
1869 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1870 QualType T = Ivar->getType();
1871 if (const ObjCObjectPointerType * OBJPT =
1872 T->getAsObjCInterfacePointerType()) {
Douglas Gregor4123a862011-11-14 22:10:01 +00001873 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001874 diag::err_property_not_as_forward_class,
1875 MemberName, BaseExpr))
Douglas Gregor4123a862011-11-14 22:10:01 +00001876 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001877 }
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001878 Diag(MemberLoc,
1879 diag::err_ivar_access_using_property_syntax_suggest)
1880 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1881 << FixItHint::CreateReplacement(OpLoc, "->");
1882 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001883 }
Chris Lattner90c58fa2010-04-11 07:51:10 +00001884
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001885 Diag(MemberLoc, diag::err_property_not_found)
1886 << MemberName << QualType(OPT, 0);
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001887 if (Setter)
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001888 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001889 << MemberName << BaseExpr->getSourceRange();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001890 return ExprError();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001891}
1892
1893
1894
John McCalldadc5752010-08-24 06:29:42 +00001895ExprResult Sema::
Chris Lattnera36ec422010-04-11 08:28:14 +00001896ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1897 IdentifierInfo &propertyName,
1898 SourceLocation receiverNameLoc,
1899 SourceLocation propertyNameLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00001900
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001901 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001902 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1903 receiverNameLoc);
Douglas Gregor33823722011-06-11 01:09:30 +00001904
1905 bool IsSuper = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00001906 if (!IFace) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001907 // If the "receiver" is 'super' in a method, handle it as an expression-like
1908 // property reference.
John McCall5f2d5562011-02-03 09:00:02 +00001909 if (receiverNamePtr->isStr("super")) {
Douglas Gregor33823722011-06-11 01:09:30 +00001910 IsSuper = true;
1911
Eli Friedman24af8502012-02-03 22:47:37 +00001912 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001913 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) {
1914 if (CurMethod->isInstanceMethod()) {
1915 ObjCInterfaceDecl *Super = Class->getSuperClass();
1916 if (!Super) {
1917 // The current class does not have a superclass.
1918 Diag(receiverNameLoc, diag::error_root_class_cannot_use_super)
1919 << Class->getIdentifier();
1920 return ExprError();
1921 }
1922 QualType T = Context.getObjCInterfaceType(Super);
1923 T = Context.getObjCObjectPointerType(T);
1924
1925 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
1926 /*BaseExpr*/nullptr,
1927 SourceLocation()/*OpLoc*/,
1928 &propertyName,
1929 propertyNameLoc,
1930 receiverNameLoc, T, true);
Fariborz Jahanian05e2aaa2013-03-11 22:26:33 +00001931 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001932
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001933 // Otherwise, if this is a class method, try dispatching to our
1934 // superclass.
1935 IFace = Class->getSuperClass();
Chris Lattnera36ec422010-04-11 08:28:14 +00001936 }
Chris Lattnera36ec422010-04-11 08:28:14 +00001937 }
John McCall5f2d5562011-02-03 09:00:02 +00001938 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001939
1940 if (!IFace) {
Alp Tokerec543272013-12-24 09:48:30 +00001941 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
1942 << tok::l_paren;
Chris Lattnera36ec422010-04-11 08:28:14 +00001943 return ExprError();
1944 }
1945 }
1946
1947 // Search for a declared property first.
Steve Naroff9527bbf2009-03-09 21:12:44 +00001948 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001949 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001950
1951 // If this reference is in an @implementation, check for 'private' methods.
1952 if (!Getter)
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001953 Getter = IFace->lookupPrivateClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001954
1955 if (Getter) {
1956 // FIXME: refactor/share with ActOnMemberReference().
1957 // Check if we can reference this property.
1958 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1959 return ExprError();
1960 }
Mike Stump11289f42009-09-09 15:08:12 +00001961
Steve Naroff9527bbf2009-03-09 21:12:44 +00001962 // Look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00001963 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001964 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1965 PP.getSelectorTable(),
1966 &propertyName);
Mike Stump11289f42009-09-09 15:08:12 +00001967
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001968 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001969 if (!Setter) {
1970 // If this reference is in an @implementation, also check for 'private'
1971 // methods.
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001972 Setter = IFace->lookupPrivateClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001973 }
1974 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00001975 if (!Setter)
1976 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001977
1978 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1979 return ExprError();
1980
1981 if (Getter || Setter) {
Douglas Gregor33823722011-06-11 01:09:30 +00001982 if (IsSuper)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001983 return new (Context)
1984 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1985 OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
1986 Context.getObjCInterfaceType(IFace));
Douglas Gregor33823722011-06-11 01:09:30 +00001987
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001988 return new (Context) ObjCPropertyRefExpr(
1989 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
1990 propertyNameLoc, receiverNameLoc, IFace);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001991 }
1992 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1993 << &propertyName << Context.getObjCInterfaceType(IFace));
1994}
1995
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001996namespace {
1997
1998class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1999 public:
2000 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
2001 // Determine whether "super" is acceptable in the current context.
2002 if (Method && Method->getClassInterface())
2003 WantObjCSuper = Method->getClassInterface()->getSuperClass();
2004 }
2005
Craig Toppere14c0f82014-03-12 04:55:44 +00002006 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002007 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
2008 candidate.isKeyword("super");
2009 }
2010};
2011
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002012}
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002013
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002014Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregore5798dc2010-04-21 20:38:13 +00002015 IdentifierInfo *Name,
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002016 SourceLocation NameLoc,
2017 bool IsSuper,
Douglas Gregore5798dc2010-04-21 20:38:13 +00002018 bool HasTrailingDot,
John McCallba7bf592010-08-24 05:47:05 +00002019 ParsedType &ReceiverType) {
2020 ReceiverType = ParsedType();
Douglas Gregore5798dc2010-04-21 20:38:13 +00002021
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002022 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor57756ea2010-10-14 22:11:03 +00002023 // messaging super. If the identifier is "super" and there is a
2024 // trailing dot, it's an instance message.
2025 if (IsSuper && S->isInObjcMethodScope())
2026 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002027
2028 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
2029 LookupName(Result, S);
2030
2031 switch (Result.getResultKind()) {
2032 case LookupResult::NotFound:
Douglas Gregorca7136b2010-04-19 20:09:36 +00002033 // Normal name lookup didn't find anything. If we're in an
2034 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor57756ea2010-10-14 22:11:03 +00002035 // FIXME: This is a hack. Ivar lookup should be part of normal
2036 // lookup.
Douglas Gregorca7136b2010-04-19 20:09:36 +00002037 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidis3a8de5b2011-11-09 00:22:48 +00002038 if (!Method->getClassInterface()) {
2039 // Fall back: let the parser try to parse it as an instance message.
2040 return ObjCInstanceMessage;
2041 }
2042
Douglas Gregorca7136b2010-04-19 20:09:36 +00002043 ObjCInterfaceDecl *ClassDeclared;
2044 if (Method->getClassInterface()->lookupInstanceVariable(Name,
2045 ClassDeclared))
2046 return ObjCInstanceMessage;
2047 }
Douglas Gregor57756ea2010-10-14 22:11:03 +00002048
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002049 // Break out; we'll perform typo correction below.
2050 break;
2051
2052 case LookupResult::NotFoundInCurrentInstantiation:
2053 case LookupResult::FoundOverloaded:
2054 case LookupResult::FoundUnresolvedValue:
2055 case LookupResult::Ambiguous:
2056 Result.suppressDiagnostics();
2057 return ObjCInstanceMessage;
2058
2059 case LookupResult::Found: {
Fariborz Jahanian14889fc2011-02-08 00:23:07 +00002060 // If the identifier is a class or not, and there is a trailing dot,
2061 // it's an instance message.
2062 if (HasTrailingDot)
2063 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002064 // We found something. If it's a type, then we have a class
2065 // message. Otherwise, it's an instance message.
2066 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregore5798dc2010-04-21 20:38:13 +00002067 QualType T;
2068 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
2069 T = Context.getObjCInterfaceType(Class);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00002070 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
Douglas Gregore5798dc2010-04-21 20:38:13 +00002071 T = Context.getTypeDeclType(Type);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00002072 DiagnoseUseOfDecl(Type, NameLoc);
2073 }
2074 else
Douglas Gregore5798dc2010-04-21 20:38:13 +00002075 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002076
Douglas Gregore5798dc2010-04-21 20:38:13 +00002077 // We have a class message, and T is the type we're
2078 // messaging. Build source-location information for it.
2079 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +00002080 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregore5798dc2010-04-21 20:38:13 +00002081 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002082 }
2083 }
2084
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002085 if (TypoCorrection Corrected = CorrectTypo(
2086 Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr,
2087 llvm::make_unique<ObjCInterfaceOrSuperCCC>(getCurMethodDecl()),
2088 CTK_ErrorRecovery, nullptr, false, nullptr, false)) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002089 if (Corrected.isKeyword()) {
2090 // If we've found the keyword "super" (the only keyword that would be
2091 // returned by CorrectTypo), this is a send to super.
Richard Smithf9b15102013-08-17 00:46:16 +00002092 diagnoseTypo(Corrected,
2093 PDiag(diag::err_unknown_receiver_suggest) << Name);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002094 return ObjCSuperMessage;
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002095 } else if (ObjCInterfaceDecl *Class =
Richard Smithf9b15102013-08-17 00:46:16 +00002096 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002097 // If we found a declaration, correct when it refers to an Objective-C
2098 // class.
Richard Smithf9b15102013-08-17 00:46:16 +00002099 diagnoseTypo(Corrected,
2100 PDiag(diag::err_unknown_receiver_suggest) << Name);
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002101 QualType T = Context.getObjCInterfaceType(Class);
2102 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2103 ReceiverType = CreateParsedType(T, TSInfo);
2104 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002105 }
2106 }
Richard Smithf9b15102013-08-17 00:46:16 +00002107
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002108 // Fall back: let the parser try to parse it as an instance message.
2109 return ObjCInstanceMessage;
2110}
Steve Naroff9527bbf2009-03-09 21:12:44 +00002111
John McCalldadc5752010-08-24 06:29:42 +00002112ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002113 SourceLocation SuperLoc,
2114 Selector Sel,
2115 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002116 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002117 SourceLocation RBracLoc,
2118 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002119 // Determine whether we are inside a method or not.
Eli Friedman24af8502012-02-03 22:47:37 +00002120 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregor4fdba132010-04-21 20:01:04 +00002121 if (!Method) {
2122 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
2123 return ExprError();
2124 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002125
Douglas Gregor4fdba132010-04-21 20:01:04 +00002126 ObjCInterfaceDecl *Class = Method->getClassInterface();
2127 if (!Class) {
2128 Diag(SuperLoc, diag::error_no_super_class_message)
2129 << Method->getDeclName();
2130 return ExprError();
2131 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002132
Douglas Gregor4fdba132010-04-21 20:01:04 +00002133 ObjCInterfaceDecl *Super = Class->getSuperClass();
2134 if (!Super) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002135 // The current class does not have a superclass.
Ted Kremenek499897b2011-01-23 17:21:34 +00002136 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
2137 << Class->getIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002138 return ExprError();
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002139 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002140
Douglas Gregor4fdba132010-04-21 20:01:04 +00002141 // We are in a method whose class has a superclass, so 'super'
2142 // is acting as a keyword.
Jordan Rose2afd6612012-10-19 16:05:26 +00002143 if (Method->getSelector() == Sel)
2144 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber715abaf2011-08-22 17:25:57 +00002145
Jordan Rose2afd6612012-10-19 16:05:26 +00002146 if (Method->isInstanceMethod()) {
Douglas Gregor4fdba132010-04-21 20:01:04 +00002147 // Since we are in an instance method, this is an instance
2148 // message to the superclass instance.
2149 QualType SuperTy = Context.getObjCInterfaceType(Super);
2150 SuperTy = Context.getObjCObjectPointerType(SuperTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00002151 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
2152 Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002153 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002154 }
Douglas Gregor4fdba132010-04-21 20:01:04 +00002155
2156 // Since we are in a class method, this is a class message to
2157 // the superclass.
Craig Topperc3ec1492014-05-26 06:22:03 +00002158 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
Douglas Gregor4fdba132010-04-21 20:01:04 +00002159 Context.getObjCInterfaceType(Super),
Craig Topperc3ec1492014-05-26 06:22:03 +00002160 SuperLoc, Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002161 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002162}
2163
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002164
2165ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
2166 bool isSuperReceiver,
2167 SourceLocation Loc,
2168 Selector Sel,
2169 ObjCMethodDecl *Method,
2170 MultiExprArg Args) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002171 TypeSourceInfo *receiverTypeInfo = nullptr;
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002172 if (!ReceiverType.isNull())
2173 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
2174
2175 return BuildClassMessage(receiverTypeInfo, ReceiverType,
2176 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
2177 Sel, Method, Loc, Loc, Loc, Args,
2178 /*isImplicit=*/true);
2179
2180}
2181
Ted Kremeneke65b0862012-03-06 20:05:56 +00002182static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2183 unsigned DiagID,
2184 bool (*refactor)(const ObjCMessageExpr *,
2185 const NSAPI &, edit::Commit &)) {
2186 SourceLocation MsgLoc = Msg->getExprLoc();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002187 if (S.Diags.isIgnored(DiagID, MsgLoc))
Ted Kremeneke65b0862012-03-06 20:05:56 +00002188 return;
2189
2190 SourceManager &SM = S.SourceMgr;
2191 edit::Commit ECommit(SM, S.LangOpts);
2192 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2193 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2194 << Msg->getSelector() << Msg->getSourceRange();
2195 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2196 if (!ECommit.isCommitable())
2197 return;
2198 for (edit::Commit::edit_iterator
2199 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2200 const edit::Commit::Edit &Edit = *I;
2201 switch (Edit.Kind) {
2202 case edit::Commit::Act_Insert:
2203 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2204 Edit.Text,
2205 Edit.BeforePrev));
2206 break;
2207 case edit::Commit::Act_InsertFromRange:
2208 Builder.AddFixItHint(
2209 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2210 Edit.getInsertFromRange(SM),
2211 Edit.BeforePrev));
2212 break;
2213 case edit::Commit::Act_Remove:
2214 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2215 break;
2216 }
2217 }
2218 }
2219}
2220
2221static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2222 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2223 edit::rewriteObjCRedundantCallWithLiteral);
2224}
2225
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002226/// \brief Diagnose use of %s directive in an NSString which is being passed
2227/// as formatting string to formatting method.
2228static void
2229DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S,
2230 ObjCMethodDecl *Method,
2231 Selector Sel,
2232 Expr **Args, unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002233 unsigned Idx = 0;
2234 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002235 ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily();
2236 if (SFFamily == ObjCStringFormatFamily::SFF_NSString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002237 Idx = 0;
2238 Format = true;
2239 }
2240 else if (Method) {
2241 for (const auto *I : Method->specific_attrs<FormatAttr>()) {
2242 if (S.GetFormatNSStringIdx(I, Idx)) {
2243 Format = true;
2244 break;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002245 }
2246 }
2247 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002248 if (!Format || NumArgs <= Idx)
2249 return;
2250
2251 Expr *FormatExpr = Args[Idx];
2252 if (ObjCStringLiteral *OSL =
2253 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) {
2254 StringLiteral *FormatString = OSL->getString();
2255 if (S.FormatStringHasSArg(FormatString)) {
2256 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2257 << "%s" << 0 << 0;
2258 if (Method)
2259 S.Diag(Method->getLocation(), diag::note_method_declared_at)
2260 << Method->getDeclName();
2261 }
2262 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002263}
2264
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002265/// \brief Build an Objective-C class message expression.
2266///
2267/// This routine takes care of both normal class messages and
2268/// class messages to the superclass.
2269///
2270/// \param ReceiverTypeInfo Type source information that describes the
2271/// receiver of this message. This may be NULL, in which case we are
2272/// sending to the superclass and \p SuperLoc must be a valid source
2273/// location.
2274
2275/// \param ReceiverType The type of the object receiving the
2276/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2277/// type as that refers to. For a superclass send, this is the type of
2278/// the superclass.
2279///
2280/// \param SuperLoc The location of the "super" keyword in a
2281/// superclass message.
2282///
2283/// \param Sel The selector to which the message is being sent.
2284///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002285/// \param Method The method that this class message is invoking, if
2286/// already known.
2287///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002288/// \param LBracLoc The location of the opening square bracket ']'.
2289///
James Dennettffad8b72012-06-22 08:10:18 +00002290/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002291///
James Dennettffad8b72012-06-22 08:10:18 +00002292/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002293ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002294 QualType ReceiverType,
2295 SourceLocation SuperLoc,
2296 Selector Sel,
2297 ObjCMethodDecl *Method,
2298 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002299 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002300 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002301 MultiExprArg ArgsIn,
2302 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002303 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00002304 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002305 if (LBracLoc.isInvalid()) {
2306 Diag(Loc, diag::err_missing_open_square_message_send)
2307 << FixItHint::CreateInsertion(Loc, "[");
2308 LBracLoc = Loc;
2309 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002310 SourceLocation SelLoc;
2311 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2312 SelLoc = SelectorLocs.front();
2313 else
2314 SelLoc = Loc;
2315
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002316 if (ReceiverType->isDependentType()) {
2317 // If the receiver type is dependent, we can't type-check anything
2318 // at this point. Build a dependent expression.
2319 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002320 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002321 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002322 return ObjCMessageExpr::Create(
2323 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
2324 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2325 isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002326 }
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002327
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002328 // Find the class to which we are sending this message.
Craig Topperc3ec1492014-05-26 06:22:03 +00002329 ObjCInterfaceDecl *Class = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00002330 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2331 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002332 Diag(Loc, diag::err_invalid_receiver_class_message)
2333 << ReceiverType;
2334 return ExprError();
Steve Naroffe2177fb2008-07-25 19:39:00 +00002335 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002336 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanianc27cd1b2011-10-15 19:18:36 +00002337 // objc++ diagnoses during typename annotation.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002338 if (!getLangOpts().CPlusPlus)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002339 (void)DiagnoseUseOfDecl(Class, SelLoc);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002340 // Find the method we are messaging.
Douglas Gregorb5186b12010-04-22 17:01:48 +00002341 if (!Method) {
Douglas Gregor4123a862011-11-14 22:10:01 +00002342 SourceRange TypeRange
2343 = SuperLoc.isValid()? SourceRange(SuperLoc)
2344 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002345 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002346 (getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002347 ? diag::err_arc_receiver_forward_class
2348 : diag::warn_receiver_forward_class),
2349 TypeRange)) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002350 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorb5186b12010-04-22 17:01:48 +00002351 Method = LookupFactoryMethodInGlobalPool(Sel,
2352 SourceRange(LBracLoc, RBracLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00002353 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002354 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2355 << Method->getDeclName();
2356 }
2357 if (!Method)
2358 Method = Class->lookupClassMethod(Sel);
2359
2360 // If we have an implementation in scope, check "private" methods.
2361 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002362 Method = Class->lookupPrivateClassMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002363
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002364 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002365 return ExprError();
Fariborz Jahanian1bd844d2009-05-08 23:02:36 +00002366 }
Mike Stump11289f42009-09-09 15:08:12 +00002367
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002368 // Check the argument types and determine the result type.
2369 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002370 ExprValueKind VK = VK_RValue;
2371
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002372 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002373 Expr **Args = ArgsIn.data();
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002374 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2375 Sel, SelectorLocs,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00002376 Method, true,
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00002377 SuperLoc.isValid(), LBracLoc, RBracLoc,
2378 SourceRange(),
Douglas Gregor33823722011-06-11 01:09:30 +00002379 ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002380 return ExprError();
Ted Kremeneka3a37ae2008-06-24 15:50:53 +00002381
Alp Toker314cc812014-01-25 16:55:45 +00002382 if (Method && !Method->getReturnType()->isVoidType() &&
2383 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002384 diag::err_illegal_message_expr_incomplete_type))
2385 return ExprError();
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002386
Fariborz Jahaniane8b45502014-08-22 19:52:49 +00002387 // Warn about explicit call of +initialize on its own class. But not on 'super'.
Fariborz Jahanian42292282014-08-25 21:27:38 +00002388 if (Method && Method->getMethodFamily() == OMF_initialize) {
2389 if (!SuperLoc.isValid()) {
2390 const ObjCInterfaceDecl *ID =
2391 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext());
2392 if (ID == Class) {
2393 Diag(Loc, diag::warn_direct_initialize_call);
2394 Diag(Method->getLocation(), diag::note_method_declared_at)
2395 << Method->getDeclName();
2396 }
2397 }
2398 else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2399 // [super initialize] is allowed only within an +initialize implementation
2400 if (CurMeth->getMethodFamily() != OMF_initialize) {
2401 Diag(Loc, diag::warn_direct_super_initialize_call);
2402 Diag(Method->getLocation(), diag::note_method_declared_at)
2403 << Method->getDeclName();
2404 Diag(CurMeth->getLocation(), diag::note_method_declared_at)
2405 << CurMeth->getDeclName();
2406 }
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002407 }
2408 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002409
2410 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2411
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002412 // Construct the appropriate ObjCMessageExpr.
Ted Kremeneke65b0862012-03-06 20:05:56 +00002413 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002414 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002415 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002416 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002417 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002418 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002419 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002420 else {
John McCall7decc9e2010-11-18 06:31:45 +00002421 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002422 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002423 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002424 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002425 if (!isImplicit)
2426 checkCocoaAPI(*this, Result);
2427 }
Douglas Gregoraae38d62010-05-22 05:17:18 +00002428 return MaybeBindToTemporary(Result);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002429}
2430
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002431// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002432// ArgExprs is optional - if it is present, the number of expressions
2433// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002434ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor3e972002010-09-15 23:19:31 +00002435 ParsedType Receiver,
2436 Selector Sel,
2437 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002438 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor3e972002010-09-15 23:19:31 +00002439 SourceLocation RBracLoc,
2440 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002441 TypeSourceInfo *ReceiverTypeInfo;
2442 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2443 if (ReceiverType.isNull())
2444 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002445
Mike Stump11289f42009-09-09 15:08:12 +00002446
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002447 if (!ReceiverTypeInfo)
2448 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2449
2450 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002451 /*SuperLoc=*/SourceLocation(), Sel,
2452 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2453 Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002454}
2455
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002456ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2457 QualType ReceiverType,
2458 SourceLocation Loc,
2459 Selector Sel,
2460 ObjCMethodDecl *Method,
2461 MultiExprArg Args) {
2462 return BuildInstanceMessage(Receiver, ReceiverType,
2463 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2464 Sel, Method, Loc, Loc, Loc, Args,
2465 /*isImplicit=*/true);
2466}
2467
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002468/// \brief Build an Objective-C instance message expression.
2469///
2470/// This routine takes care of both normal instance messages and
2471/// instance messages to the superclass instance.
2472///
2473/// \param Receiver The expression that computes the object that will
2474/// receive this message. This may be empty, in which case we are
2475/// sending to the superclass instance and \p SuperLoc must be a valid
2476/// source location.
2477///
2478/// \param ReceiverType The (static) type of the object receiving the
2479/// message. When a \p Receiver expression is provided, this is the
2480/// same type as that expression. For a superclass instance send, this
2481/// is a pointer to the type of the superclass.
2482///
2483/// \param SuperLoc The location of the "super" keyword in a
2484/// superclass instance message.
2485///
2486/// \param Sel The selector to which the message is being sent.
2487///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002488/// \param Method The method that this instance message is invoking, if
2489/// already known.
2490///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002491/// \param LBracLoc The location of the opening square bracket ']'.
2492///
James Dennettffad8b72012-06-22 08:10:18 +00002493/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002494///
James Dennettffad8b72012-06-22 08:10:18 +00002495/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002496ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002497 QualType ReceiverType,
2498 SourceLocation SuperLoc,
2499 Selector Sel,
2500 ObjCMethodDecl *Method,
2501 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002502 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002503 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002504 MultiExprArg ArgsIn,
2505 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002506 // The location of the receiver.
2507 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002508 SourceRange RecRange =
2509 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2510 SourceLocation SelLoc;
2511 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2512 SelLoc = SelectorLocs.front();
2513 else
2514 SelLoc = Loc;
2515
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002516 if (LBracLoc.isInvalid()) {
2517 Diag(Loc, diag::err_missing_open_square_message_send)
2518 << FixItHint::CreateInsertion(Loc, "[");
2519 LBracLoc = Loc;
2520 }
2521
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002522 // If we have a receiver expression, perform appropriate promotions
2523 // and determine receiver type.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002524 if (Receiver) {
John McCall4124c492011-10-17 18:40:02 +00002525 if (Receiver->hasPlaceholderType()) {
Douglas Gregord8fb1e32011-12-01 01:37:36 +00002526 ExprResult Result;
2527 if (Receiver->getType() == Context.UnknownAnyTy)
2528 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2529 else
2530 Result = CheckPlaceholderExpr(Receiver);
2531 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002532 Receiver = Result.get();
John McCall4124c492011-10-17 18:40:02 +00002533 }
2534
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002535 if (Receiver->isTypeDependent()) {
2536 // If the receiver is type-dependent, we can't type-check anything
2537 // at this point. Build a dependent expression.
2538 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002539 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002540 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002541 return ObjCMessageExpr::Create(
2542 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
2543 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2544 RBracLoc, isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002545 }
2546
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002547 // If necessary, apply function/array conversion to the receiver.
2548 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00002549 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2550 if (Result.isInvalid())
2551 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002552 Receiver = Result.get();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002553 ReceiverType = Receiver->getType();
John McCall80c93a02013-03-01 09:20:14 +00002554
2555 // If the receiver is an ObjC pointer, a block pointer, or an
2556 // __attribute__((NSObject)) pointer, we don't need to do any
2557 // special conversion in order to look up a receiver.
2558 if (ReceiverType->isObjCRetainableType()) {
2559 // do nothing
2560 } else if (!getLangOpts().ObjCAutoRefCount &&
2561 !Context.getObjCIdType().isNull() &&
2562 (ReceiverType->isPointerType() ||
2563 ReceiverType->isIntegerType())) {
2564 // Implicitly convert integers and pointers to 'id' but emit a warning.
2565 // But not in ARC.
2566 Diag(Loc, diag::warn_bad_receiver_type)
2567 << ReceiverType
2568 << Receiver->getSourceRange();
2569 if (ReceiverType->isPointerType()) {
2570 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002571 CK_CPointerToObjCPointerCast).get();
John McCall80c93a02013-03-01 09:20:14 +00002572 } else {
2573 // TODO: specialized warning on null receivers?
2574 bool IsNull = Receiver->isNullPointerConstant(Context,
2575 Expr::NPC_ValueDependentIsNull);
2576 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2577 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002578 Kind).get();
John McCall80c93a02013-03-01 09:20:14 +00002579 }
2580 ReceiverType = Receiver->getType();
2581 } else if (getLangOpts().CPlusPlus) {
Douglas Gregor4b60a152013-11-07 22:34:54 +00002582 // The receiver must be a complete type.
2583 if (RequireCompleteType(Loc, Receiver->getType(),
2584 diag::err_incomplete_receiver_type))
2585 return ExprError();
2586
John McCall80c93a02013-03-01 09:20:14 +00002587 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2588 if (result.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002589 Receiver = result.get();
John McCall80c93a02013-03-01 09:20:14 +00002590 ReceiverType = Receiver->getType();
2591 }
2592 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002593 }
2594
John McCall80c93a02013-03-01 09:20:14 +00002595 // There's a somewhat weird interaction here where we assume that we
2596 // won't actually have a method unless we also don't need to do some
2597 // of the more detailed type-checking on the receiver.
2598
Douglas Gregorb5186b12010-04-22 17:01:48 +00002599 if (!Method) {
2600 // Handle messages to id.
Fariborz Jahanian32e59ba2010-08-10 18:10:50 +00002601 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002602 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002603 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2604 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002605 SourceRange(LBracLoc, RBracLoc),
2606 receiverIsId);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002607 if (!Method)
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002608 Method = LookupFactoryMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002609 SourceRange(LBracLoc,RBracLoc),
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002610 receiverIsId);
Fariborz Jahanian05e77f82014-11-07 23:51:15 +00002611 if (Method) {
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00002612 if (ObjCMethodDecl *BestMethod =
Fariborz Jahaniand288fad2014-08-13 23:38:04 +00002613 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00002614 Method = BestMethod;
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002615 if (!AreMultipleMethodsInGlobalPool(Sel, Method,
2616 SourceRange(LBracLoc, RBracLoc),
2617 receiverIsId)) {
Sylvestre Ledru30f17082014-11-17 18:26:39 +00002618 DiagnoseUseOfDecl(Method, SelLoc);
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002619 }
Fariborz Jahanian05e77f82014-11-07 23:51:15 +00002620 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002621 } else if (ReceiverType->isObjCClassType() ||
2622 ReceiverType->isObjCQualifiedClassType()) {
2623 // Handle messages to Class.
Nico Weber2e0c8f72014-12-27 03:58:08 +00002624 // We allow sending a message to a qualified Class ("Class<foo>"), which
2625 // is ok as long as one of the protocols implements the selector (if not,
2626 // warn).
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002627 if (const ObjCObjectPointerType *QClassTy
2628 = ReceiverType->getAsObjCQualifiedClassType()) {
2629 // Search protocols for class methods.
2630 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2631 if (!Method) {
2632 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2633 // warn if instance method found for a Class message.
2634 if (Method) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002635 Diag(SelLoc, diag::warn_instance_method_on_class_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002636 << Method->getSelector() << Sel;
Ted Kremenek59b10db2012-02-27 22:55:11 +00002637 Diag(Method->getLocation(), diag::note_method_declared_at)
2638 << Method->getDeclName();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002639 }
Steve Naroff3f49fee2009-03-04 15:11:40 +00002640 }
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002641 } else {
2642 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2643 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2644 // First check the public methods in the class interface.
2645 Method = ClassDecl->lookupClassMethod(Sel);
2646
2647 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002648 Method = ClassDecl->lookupPrivateClassMethod(Sel);
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002649 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002650 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002651 return ExprError();
2652 }
2653 if (!Method) {
2654 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregor486b74e2011-09-27 16:10:05 +00002655 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002656 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002657 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002658 if (!Method) {
2659 // If no class (factory) method was found, check if an _instance_
2660 // method of the same name exists in the root class only.
2661 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002662 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002663 if (Method)
2664 if (const ObjCInterfaceDecl *ID =
2665 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2666 if (ID->getSuperClass())
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002667 Diag(SelLoc, diag::warn_root_inst_method_not_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002668 << Sel << SourceRange(LBracLoc, RBracLoc);
2669 }
2670 }
Fariborz Jahaniand288fad2014-08-13 23:38:04 +00002671 if (Method)
2672 if (ObjCMethodDecl *BestMethod =
2673 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
2674 Method = BestMethod;
Douglas Gregor9a129192010-04-21 00:45:42 +00002675 }
2676 }
2677 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002678 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00002679 ObjCInterfaceDecl *ClassDecl = nullptr;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002680
2681 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2682 // long as one of the protocols implements the selector (if not, warn).
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002683 // And as long as message is not deprecated/unavailable (warn if it is).
Douglas Gregorb5186b12010-04-22 17:01:48 +00002684 if (const ObjCObjectPointerType *QIdTy
2685 = ReceiverType->getAsObjCQualifiedIdType()) {
2686 // Search protocols for instance methods.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002687 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2688 if (!Method)
2689 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002690 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002691 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002692 } else if (const ObjCObjectPointerType *OCIType
2693 = ReceiverType->getAsObjCInterfacePointerType()) {
2694 // We allow sending a message to a pointer to an interface (an object).
2695 ClassDecl = OCIType->getInterfaceDecl();
John McCall31168b02011-06-15 23:02:42 +00002696
Douglas Gregor4123a862011-11-14 22:10:01 +00002697 // Try to complete the type. Under ARC, this is a hard error from which
2698 // we don't try to recover.
Craig Topperc3ec1492014-05-26 06:22:03 +00002699 const ObjCInterfaceDecl *forwardClass = nullptr;
Douglas Gregor4123a862011-11-14 22:10:01 +00002700 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002701 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002702 ? diag::err_arc_receiver_forward_instance
2703 : diag::warn_receiver_forward_instance,
2704 Receiver? Receiver->getSourceRange()
2705 : SourceRange(SuperLoc))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002706 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregor4123a862011-11-14 22:10:01 +00002707 return ExprError();
2708
2709 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanianc934de62012-02-03 01:02:44 +00002710 Diag(Receiver ? Receiver->getLocStart()
2711 : SuperLoc, diag::note_receiver_is_id);
Craig Topperc3ec1492014-05-26 06:22:03 +00002712 Method = nullptr;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002713 } else {
2714 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCall31168b02011-06-15 23:02:42 +00002715 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002716
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002717 if (!Method)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002718 // Search protocol qualifiers.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002719 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2720
Douglas Gregorb5186b12010-04-22 17:01:48 +00002721 if (!Method) {
2722 // If we have implementations in scope, check "private" methods.
Anna Zaksc77a3b12012-07-27 19:07:44 +00002723 Method = ClassDecl->lookupPrivateMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002724
David Blaikiebbafb8a2012-03-11 07:00:24 +00002725 if (!Method && getLangOpts().ObjCAutoRefCount) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002726 Diag(SelLoc, diag::err_arc_may_not_respond)
2727 << OCIType->getPointeeType() << Sel << RecRange
Fariborz Jahanian32c13502012-11-28 01:27:44 +00002728 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
John McCall31168b02011-06-15 23:02:42 +00002729 return ExprError();
2730 }
2731
Douglas Gregor486b74e2011-09-27 16:10:05 +00002732 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002733 // If we still haven't found a method, look in the global pool. This
2734 // behavior isn't very desirable, however we need it for GCC
2735 // compatibility. FIXME: should we deviate??
2736 if (OCIType->qual_empty()) {
2737 Method = LookupInstanceMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002738 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002739 if (Method) {
2740 if (auto BestMethod =
2741 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
2742 Method = BestMethod;
2743 AreMultipleMethodsInGlobalPool(Sel, Method,
2744 SourceRange(LBracLoc, RBracLoc),
2745 true);
2746 }
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +00002747 if (Method && !forwardClass)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002748 Diag(SelLoc, diag::warn_maynot_respond)
2749 << OCIType->getInterfaceDecl()->getIdentifier()
2750 << Sel << RecRange;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002751 }
2752 }
2753 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002754 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002755 return ExprError();
John McCallfec112d2011-09-09 06:11:02 +00002756 } else {
John McCall80c93a02013-03-01 09:20:14 +00002757 // Reject other random receiver types (e.g. structs).
2758 Diag(Loc, diag::err_bad_receiver_type)
2759 << ReceiverType << Receiver->getSourceRange();
2760 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002761 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002762 }
Chris Lattner6b946cc2008-07-21 05:57:44 +00002763 }
Mike Stump11289f42009-09-09 15:08:12 +00002764
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002765 FunctionScopeInfo *DIFunctionScopeInfo =
2766 (Method && Method->getMethodFamily() == OMF_init)
Craig Topperc3ec1492014-05-26 06:22:03 +00002767 ? getEnclosingFunction() : nullptr;
2768
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002769 if (DIFunctionScopeInfo &&
2770 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002771 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2772 bool isDesignatedInitChain = false;
2773 if (SuperLoc.isValid()) {
2774 if (const ObjCObjectPointerType *
2775 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2776 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
Argyrios Kyrtzidisd664a342013-12-13 03:48:17 +00002777 // Either we know this is a designated initializer or we
2778 // conservatively assume it because we don't know for sure.
2779 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2780 ID->isDesignatedInitializer(Sel)) {
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002781 isDesignatedInitChain = true;
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002782 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002783 }
2784 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002785 }
2786 }
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002787 if (!isDesignatedInitChain) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002788 const ObjCMethodDecl *InitMethod = nullptr;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002789 bool isDesignated =
2790 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2791 assert(isDesignated && InitMethod);
2792 (void)isDesignated;
2793 Diag(SelLoc, SuperLoc.isValid() ?
2794 diag::warn_objc_designated_init_non_designated_init_call :
2795 diag::warn_objc_designated_init_non_super_designated_init_call);
2796 Diag(InitMethod->getLocation(),
2797 diag::note_objc_designated_init_marked_here);
2798 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002799 }
2800
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002801 if (DIFunctionScopeInfo &&
2802 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002803 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2804 if (SuperLoc.isValid()) {
2805 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2806 } else {
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002807 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002808 }
2809 }
2810
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002811 // Check the message arguments.
2812 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002813 Expr **Args = ArgsIn.data();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002814 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002815 ExprValueKind VK = VK_RValue;
Fariborz Jahanian68500912010-12-01 01:07:24 +00002816 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2817 ReceiverType->isObjCQualifiedClassType());
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002818 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2819 Sel, SelectorLocs, Method,
Douglas Gregor33823722011-06-11 01:09:30 +00002820 ClassMessage, SuperLoc.isValid(),
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00002821 LBracLoc, RBracLoc, RecRange, ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002822 return ExprError();
Alp Toker314cc812014-01-25 16:55:45 +00002823
2824 if (Method && !Method->getReturnType()->isVoidType() &&
2825 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002826 diag::err_illegal_message_expr_incomplete_type))
2827 return ExprError();
Douglas Gregor9a129192010-04-21 00:45:42 +00002828
John McCall31168b02011-06-15 23:02:42 +00002829 // In ARC, forbid the user from sending messages to
2830 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002831 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002832 ObjCMethodFamily family =
2833 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2834 switch (family) {
2835 case OMF_init:
2836 if (Method)
2837 checkInitMethod(Method, ReceiverType);
2838
2839 case OMF_None:
2840 case OMF_alloc:
2841 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00002842 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002843 case OMF_mutableCopy:
2844 case OMF_new:
2845 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002846 case OMF_initialize:
John McCall31168b02011-06-15 23:02:42 +00002847 break;
2848
2849 case OMF_dealloc:
2850 case OMF_retain:
2851 case OMF_release:
2852 case OMF_autorelease:
2853 case OMF_retainCount:
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002854 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
2855 << Sel << RecRange;
John McCall31168b02011-06-15 23:02:42 +00002856 break;
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002857
2858 case OMF_performSelector:
2859 if (Method && NumArgs >= 1) {
2860 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2861 Selector ArgSel = SelExp->getSelector();
2862 ObjCMethodDecl *SelMethod =
2863 LookupInstanceMethodInGlobalPool(ArgSel,
2864 SelExp->getSourceRange());
2865 if (!SelMethod)
2866 SelMethod =
2867 LookupFactoryMethodInGlobalPool(ArgSel,
2868 SelExp->getSourceRange());
2869 if (SelMethod) {
2870 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2871 switch (SelFamily) {
2872 case OMF_alloc:
2873 case OMF_copy:
2874 case OMF_mutableCopy:
2875 case OMF_new:
2876 case OMF_self:
2877 case OMF_init:
2878 // Issue error, unless ns_returns_not_retained.
2879 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2880 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002881 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002882 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002883 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2884 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002885 }
2886 break;
2887 default:
2888 // +0 call. OK. unless ns_returns_retained.
2889 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2890 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002891 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002892 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002893 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2894 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002895 }
2896 break;
2897 }
2898 }
2899 } else {
2900 // error (may leak).
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002901 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002902 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2903 }
2904 }
2905 break;
John McCall31168b02011-06-15 23:02:42 +00002906 }
2907 }
2908
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002909 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2910
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002911 // Construct the appropriate ObjCMessageExpr instance.
John McCall31168b02011-06-15 23:02:42 +00002912 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002913 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002914 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002915 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002916 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002917 makeArrayRef(Args, NumArgs), RBracLoc,
2918 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002919 else {
John McCall7decc9e2010-11-18 06:31:45 +00002920 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002921 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002922 makeArrayRef(Args, NumArgs), RBracLoc,
2923 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002924 if (!isImplicit)
2925 checkCocoaAPI(*this, Result);
2926 }
John McCall31168b02011-06-15 23:02:42 +00002927
David Blaikiebbafb8a2012-03-11 07:00:24 +00002928 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002929 // In ARC, annotate delegate init calls.
2930 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregor486b74e2011-09-27 16:10:05 +00002931 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCall31168b02011-06-15 23:02:42 +00002932 // Only consider init calls *directly* in init implementations,
2933 // not within blocks.
2934 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2935 if (method && method->getMethodFamily() == OMF_init) {
2936 // The implicit assignment to self means we also don't want to
2937 // consume the result.
2938 Result->setDelegateInitCall(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002939 return Result;
John McCall31168b02011-06-15 23:02:42 +00002940 }
2941 }
2942
2943 // In ARC, check for message sends which are likely to introduce
2944 // retain cycles.
2945 checkRetainCycles(Result);
Jordan Rose22487652012-10-11 16:06:21 +00002946
2947 if (!isImplicit && Method) {
2948 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
2949 bool IsWeak =
2950 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
2951 if (!IsWeak && Sel.isUnarySelector())
2952 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002953 if (IsWeak &&
2954 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
2955 getCurFunction()->recordUseOfWeak(Result, Prop);
Jordan Rose22487652012-10-11 16:06:21 +00002956 }
2957 }
John McCall31168b02011-06-15 23:02:42 +00002958 }
Alex Denisove1d882c2015-03-04 17:55:52 +00002959
2960 CheckObjCCircularContainer(Result);
2961
Douglas Gregoraae38d62010-05-22 05:17:18 +00002962 return MaybeBindToTemporary(Result);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002963}
2964
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002965static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
2966 if (ObjCSelectorExpr *OSE =
2967 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
2968 Selector Sel = OSE->getSelector();
2969 SourceLocation Loc = OSE->getAtLoc();
Chandler Carruth12c8f652015-03-27 00:55:05 +00002970 auto Pos = S.ReferencedSelectors.find(Sel);
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002971 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
2972 S.ReferencedSelectors.erase(Pos);
2973 }
2974}
2975
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002976// ActOnInstanceMessage - used for both unary and keyword messages.
2977// ArgExprs is optional - if it is present, the number of expressions
2978// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002979ExprResult Sema::ActOnInstanceMessage(Scope *S,
2980 Expr *Receiver,
2981 Selector Sel,
2982 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002983 ArrayRef<SourceLocation> SelectorLocs,
John McCalldadc5752010-08-24 06:29:42 +00002984 SourceLocation RBracLoc,
2985 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002986 if (!Receiver)
2987 return ExprError();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00002988
2989 // A ParenListExpr can show up while doing error recovery with invalid code.
2990 if (isa<ParenListExpr>(Receiver)) {
2991 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
2992 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002993 Receiver = Result.get();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00002994 }
Fariborz Jahanian17748062013-01-22 19:05:17 +00002995
2996 if (RespondsToSelectorSel.isNull()) {
2997 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
2998 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
2999 }
3000 if (Sel == RespondsToSelectorSel)
Fariborz Jahanian02447d82013-01-22 18:35:43 +00003001 RemoveSelectorFromWarningCache(*this, Args[0]);
Craig Topperc3ec1492014-05-26 06:22:03 +00003002
John McCallb268a282010-08-23 23:25:46 +00003003 return BuildInstanceMessage(Receiver, Receiver->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003004 /*SuperLoc=*/SourceLocation(), Sel,
3005 /*Method=*/nullptr, LBracLoc, SelectorLocs,
3006 RBracLoc, Args);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00003007}
Chris Lattner2a3569b2008-04-07 05:30:13 +00003008
John McCall31168b02011-06-15 23:02:42 +00003009enum ARCConversionTypeClass {
John McCalle4fe2452011-10-01 01:01:08 +00003010 /// int, void, struct A
John McCall31168b02011-06-15 23:02:42 +00003011 ACTC_none,
John McCalle4fe2452011-10-01 01:01:08 +00003012
3013 /// id, void (^)()
John McCall31168b02011-06-15 23:02:42 +00003014 ACTC_retainable,
John McCalle4fe2452011-10-01 01:01:08 +00003015
3016 /// id*, id***, void (^*)(),
3017 ACTC_indirectRetainable,
3018
3019 /// void* might be a normal C type, or it might a CF type.
3020 ACTC_voidPtr,
3021
3022 /// struct A*
3023 ACTC_coreFoundation
John McCall31168b02011-06-15 23:02:42 +00003024};
John McCalle4fe2452011-10-01 01:01:08 +00003025static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
3026 return (ACTC == ACTC_retainable ||
3027 ACTC == ACTC_coreFoundation ||
3028 ACTC == ACTC_voidPtr);
3029}
3030static bool isAnyCLike(ARCConversionTypeClass ACTC) {
3031 return ACTC == ACTC_none ||
3032 ACTC == ACTC_voidPtr ||
3033 ACTC == ACTC_coreFoundation;
3034}
3035
John McCall31168b02011-06-15 23:02:42 +00003036static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCalle4fe2452011-10-01 01:01:08 +00003037 bool isIndirect = false;
John McCall31168b02011-06-15 23:02:42 +00003038
3039 // Ignore an outermost reference type.
John McCalle4fe2452011-10-01 01:01:08 +00003040 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall31168b02011-06-15 23:02:42 +00003041 type = ref->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00003042 isIndirect = true;
3043 }
John McCall31168b02011-06-15 23:02:42 +00003044
3045 // Drill through pointers and arrays recursively.
3046 while (true) {
3047 if (const PointerType *ptr = type->getAs<PointerType>()) {
3048 type = ptr->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00003049
3050 // The first level of pointer may be the innermost pointer on a CF type.
3051 if (!isIndirect) {
3052 if (type->isVoidType()) return ACTC_voidPtr;
3053 if (type->isRecordType()) return ACTC_coreFoundation;
3054 }
John McCall31168b02011-06-15 23:02:42 +00003055 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
3056 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
3057 } else {
3058 break;
3059 }
John McCalle4fe2452011-10-01 01:01:08 +00003060 isIndirect = true;
John McCall31168b02011-06-15 23:02:42 +00003061 }
3062
John McCalle4fe2452011-10-01 01:01:08 +00003063 if (isIndirect) {
3064 if (type->isObjCARCBridgableType())
3065 return ACTC_indirectRetainable;
3066 return ACTC_none;
3067 }
3068
3069 if (type->isObjCARCBridgableType())
3070 return ACTC_retainable;
3071
3072 return ACTC_none;
John McCall31168b02011-06-15 23:02:42 +00003073}
3074
3075namespace {
John McCalle4fe2452011-10-01 01:01:08 +00003076 /// A result from the cast checker.
3077 enum ACCResult {
3078 /// Cannot be casted.
3079 ACC_invalid,
3080
3081 /// Can be safely retained or not retained.
3082 ACC_bottom,
3083
3084 /// Can be casted at +0.
3085 ACC_plusZero,
3086
3087 /// Can be casted at +1.
3088 ACC_plusOne
3089 };
3090 ACCResult merge(ACCResult left, ACCResult right) {
3091 if (left == right) return left;
3092 if (left == ACC_bottom) return right;
3093 if (right == ACC_bottom) return left;
3094 return ACC_invalid;
3095 }
3096
3097 /// A checker which white-lists certain expressions whose conversion
3098 /// to or from retainable type would otherwise be forbidden in ARC.
3099 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
3100 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
3101
John McCall31168b02011-06-15 23:02:42 +00003102 ASTContext &Context;
John McCalle4fe2452011-10-01 01:01:08 +00003103 ARCConversionTypeClass SourceClass;
3104 ARCConversionTypeClass TargetClass;
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003105 bool Diagnose;
John McCalle4fe2452011-10-01 01:01:08 +00003106
3107 static bool isCFType(QualType type) {
3108 // Someday this can use ns_bridged. For now, it has to do this.
3109 return type->isCARCBridgableType();
John McCall31168b02011-06-15 23:02:42 +00003110 }
John McCalle4fe2452011-10-01 01:01:08 +00003111
3112 public:
3113 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003114 ARCConversionTypeClass target, bool diagnose)
3115 : Context(Context), SourceClass(source), TargetClass(target),
3116 Diagnose(diagnose) {}
John McCalle4fe2452011-10-01 01:01:08 +00003117
3118 using super::Visit;
3119 ACCResult Visit(Expr *e) {
3120 return super::Visit(e->IgnoreParens());
3121 }
3122
3123 ACCResult VisitStmt(Stmt *s) {
3124 return ACC_invalid;
3125 }
3126
3127 /// Null pointer constants can be casted however you please.
3128 ACCResult VisitExpr(Expr *e) {
3129 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
3130 return ACC_bottom;
3131 return ACC_invalid;
3132 }
3133
3134 /// Objective-C string literals can be safely casted.
3135 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
3136 // If we're casting to any retainable type, go ahead. Global
3137 // strings are immune to retains, so this is bottom.
3138 if (isAnyRetainable(TargetClass)) return ACC_bottom;
3139
3140 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00003141 }
3142
John McCalle4fe2452011-10-01 01:01:08 +00003143 /// Look through certain implicit and explicit casts.
3144 ACCResult VisitCastExpr(CastExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00003145 switch (e->getCastKind()) {
3146 case CK_NullToPointer:
John McCalle4fe2452011-10-01 01:01:08 +00003147 return ACC_bottom;
3148
John McCall31168b02011-06-15 23:02:42 +00003149 case CK_NoOp:
3150 case CK_LValueToRValue:
3151 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00003152 case CK_CPointerToObjCPointerCast:
3153 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00003154 case CK_AnyPointerToBlockPointerCast:
3155 return Visit(e->getSubExpr());
John McCalle4fe2452011-10-01 01:01:08 +00003156
John McCall31168b02011-06-15 23:02:42 +00003157 default:
John McCalle4fe2452011-10-01 01:01:08 +00003158 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00003159 }
3160 }
John McCalle4fe2452011-10-01 01:01:08 +00003161
3162 /// Look through unary extension.
3163 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00003164 return Visit(e->getSubExpr());
3165 }
John McCalle4fe2452011-10-01 01:01:08 +00003166
3167 /// Ignore the LHS of a comma operator.
3168 ACCResult VisitBinComma(BinaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00003169 return Visit(e->getRHS());
3170 }
John McCalle4fe2452011-10-01 01:01:08 +00003171
3172 /// Conditional operators are okay if both sides are okay.
3173 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
3174 ACCResult left = Visit(e->getTrueExpr());
3175 if (left == ACC_invalid) return ACC_invalid;
3176 return merge(left, Visit(e->getFalseExpr()));
John McCall31168b02011-06-15 23:02:42 +00003177 }
John McCalle4fe2452011-10-01 01:01:08 +00003178
John McCallfe96e0b2011-11-06 09:01:30 +00003179 /// Look through pseudo-objects.
3180 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
3181 // If we're getting here, we should always have a result.
3182 return Visit(e->getResultExpr());
3183 }
3184
John McCalle4fe2452011-10-01 01:01:08 +00003185 /// Statement expressions are okay if their result expression is okay.
3186 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00003187 return Visit(e->getSubStmt()->body_back());
3188 }
John McCall31168b02011-06-15 23:02:42 +00003189
John McCalle4fe2452011-10-01 01:01:08 +00003190 /// Some declaration references are okay.
3191 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
John McCalle4fe2452011-10-01 01:01:08 +00003192 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
Ben Langmuir443aa4b2015-02-25 20:09:06 +00003193 // References to global constants are okay.
John McCalle4fe2452011-10-01 01:01:08 +00003194 if (isAnyRetainable(TargetClass) &&
3195 isAnyRetainable(SourceClass) &&
3196 var &&
3197 var->getStorageClass() == SC_Extern &&
Ben Langmuir443aa4b2015-02-25 20:09:06 +00003198 var->getType().isConstQualified()) {
3199
3200 // In system headers, they can also be assumed to be immune to retains.
3201 // These are things like 'kCFStringTransformToLatin'.
3202 if (Context.getSourceManager().isInSystemHeader(var->getLocation()))
3203 return ACC_bottom;
3204
3205 return ACC_plusZero;
John McCalle4fe2452011-10-01 01:01:08 +00003206 }
3207
3208 // Nothing else.
3209 return ACC_invalid;
Fariborz Jahanian78876372011-06-21 17:38:29 +00003210 }
John McCalle4fe2452011-10-01 01:01:08 +00003211
3212 /// Some calls are okay.
3213 ACCResult VisitCallExpr(CallExpr *e) {
3214 if (FunctionDecl *fn = e->getDirectCallee())
3215 if (ACCResult result = checkCallToFunction(fn))
3216 return result;
3217
3218 return super::VisitCallExpr(e);
3219 }
3220
3221 ACCResult checkCallToFunction(FunctionDecl *fn) {
3222 // Require a CF*Ref return type.
Alp Toker314cc812014-01-25 16:55:45 +00003223 if (!isCFType(fn->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003224 return ACC_invalid;
3225
3226 if (!isAnyRetainable(TargetClass))
3227 return ACC_invalid;
3228
3229 // Honor an explicit 'not retained' attribute.
3230 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3231 return ACC_plusZero;
3232
3233 // Honor an explicit 'retained' attribute, except that for
3234 // now we're not going to permit implicit handling of +1 results,
3235 // because it's a bit frightening.
3236 if (fn->hasAttr<CFReturnsRetainedAttr>())
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003237 return Diagnose ? ACC_plusOne
3238 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003239
3240 // Recognize this specific builtin function, which is used by CFSTR.
3241 unsigned builtinID = fn->getBuiltinID();
3242 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3243 return ACC_bottom;
3244
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003245 // Otherwise, don't do anything implicit with an unaudited function.
3246 if (!fn->hasAttr<CFAuditedTransferAttr>())
3247 return ACC_invalid;
3248
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003249 // Otherwise, it's +0 unless it follows the create convention.
3250 if (ento::coreFoundation::followsCreateRule(fn))
3251 return Diagnose ? ACC_plusOne
3252 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003253
John McCalle4fe2452011-10-01 01:01:08 +00003254 return ACC_plusZero;
3255 }
3256
3257 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3258 return checkCallToMethod(e->getMethodDecl());
3259 }
3260
3261 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3262 ObjCMethodDecl *method;
3263 if (e->isExplicitProperty())
3264 method = e->getExplicitProperty()->getGetterMethodDecl();
3265 else
3266 method = e->getImplicitPropertyGetter();
3267 return checkCallToMethod(method);
3268 }
3269
3270 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3271 if (!method) return ACC_invalid;
3272
3273 // Check for message sends to functions returning CF types. We
3274 // just obey the Cocoa conventions with these, even though the
3275 // return type is CF.
Alp Toker314cc812014-01-25 16:55:45 +00003276 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003277 return ACC_invalid;
3278
3279 // If the method is explicitly marked not-retained, it's +0.
3280 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3281 return ACC_plusZero;
3282
3283 // If the method is explicitly marked as returning retained, or its
3284 // selector follows a +1 Cocoa convention, treat it as +1.
3285 if (method->hasAttr<CFReturnsRetainedAttr>())
3286 return ACC_plusOne;
3287
3288 switch (method->getSelector().getMethodFamily()) {
3289 case OMF_alloc:
3290 case OMF_copy:
3291 case OMF_mutableCopy:
3292 case OMF_new:
3293 return ACC_plusOne;
3294
3295 default:
3296 // Otherwise, treat it as +0.
3297 return ACC_plusZero;
Fariborz Jahanian9b83be82011-06-21 19:42:38 +00003298 }
3299 }
John McCalle4fe2452011-10-01 01:01:08 +00003300 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003301}
Fariborz Jahanian4ad56862011-06-20 20:54:42 +00003302
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003303bool Sema::isKnownName(StringRef name) {
3304 if (name.empty())
3305 return false;
3306 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003307 Sema::LookupOrdinaryName);
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003308 return LookupName(R, TUScope, false);
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003309}
3310
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003311static void addFixitForObjCARCConversion(Sema &S,
3312 DiagnosticBuilder &DiagB,
3313 Sema::CheckedConversionKind CCK,
3314 SourceLocation afterLParen,
3315 QualType castType,
3316 Expr *castExpr,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003317 Expr *realCast,
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003318 const char *bridgeKeyword,
3319 const char *CFBridgeName) {
3320 // We handle C-style and implicit casts here.
3321 switch (CCK) {
3322 case Sema::CCK_ImplicitConversion:
3323 case Sema::CCK_CStyleCast:
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003324 case Sema::CCK_OtherCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003325 break;
3326 case Sema::CCK_FunctionalCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003327 return;
3328 }
3329
3330 if (CFBridgeName) {
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003331 if (CCK == Sema::CCK_OtherCast) {
3332 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3333 SourceRange range(NCE->getOperatorLoc(),
3334 NCE->getAngleBrackets().getEnd());
3335 SmallString<32> BridgeCall;
3336
3337 SourceManager &SM = S.getSourceManager();
3338 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3339 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3340 BridgeCall += ' ';
3341
3342 BridgeCall += CFBridgeName;
3343 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3344 }
3345 return;
3346 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003347 Expr *castedE = castExpr;
3348 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3349 castedE = CCE->getSubExpr();
3350 castedE = castedE->IgnoreImpCasts();
3351 SourceRange range = castedE->getSourceRange();
Jordan Rose288c4212012-06-07 01:10:31 +00003352
3353 SmallString<32> BridgeCall;
3354
3355 SourceManager &SM = S.getSourceManager();
3356 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3357 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3358 BridgeCall += ' ';
3359
3360 BridgeCall += CFBridgeName;
3361
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003362 if (isa<ParenExpr>(castedE)) {
3363 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003364 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003365 } else {
Jordan Rose288c4212012-06-07 01:10:31 +00003366 BridgeCall += '(';
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003367 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003368 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003369 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3370 S.PP.getLocForEndOfToken(range.getEnd()),
3371 ")"));
3372 }
3373 return;
3374 }
3375
3376 if (CCK == Sema::CCK_CStyleCast) {
3377 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003378 } else if (CCK == Sema::CCK_OtherCast) {
3379 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3380 std::string castCode = "(";
3381 castCode += bridgeKeyword;
3382 castCode += castType.getAsString();
3383 castCode += ")";
3384 SourceRange Range(NCE->getOperatorLoc(),
3385 NCE->getAngleBrackets().getEnd());
3386 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3387 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003388 } else {
3389 std::string castCode = "(";
3390 castCode += bridgeKeyword;
3391 castCode += castType.getAsString();
3392 castCode += ")";
3393 Expr *castedE = castExpr->IgnoreImpCasts();
3394 SourceRange range = castedE->getSourceRange();
3395 if (isa<ParenExpr>(castedE)) {
3396 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3397 castCode));
3398 } else {
3399 castCode += "(";
3400 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3401 castCode));
3402 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3403 S.PP.getLocForEndOfToken(range.getEnd()),
3404 ")"));
3405 }
3406 }
3407}
3408
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003409template <typename T>
3410static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3411 TypedefNameDecl *TDNDecl = TD->getDecl();
3412 QualType QT = TDNDecl->getUnderlyingType();
3413 if (QT->isPointerType()) {
3414 QT = QT->getPointeeType();
3415 if (const RecordType *RT = QT->getAs<RecordType>())
Fariborz Jahanian9af6a782014-06-11 19:10:46 +00003416 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
Aaron Ballman2084f8f2013-12-19 13:20:36 +00003417 return RD->getAttr<T>();
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003418 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003419 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003420}
3421
3422static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3423 TypedefNameDecl *&TDNDecl) {
3424 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3425 TDNDecl = TD->getDecl();
3426 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3427 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3428 return ObjCBAttr;
3429 T = TDNDecl->getUnderlyingType();
3430 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003431 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003432}
3433
John McCall4124c492011-10-17 18:40:02 +00003434static void
3435diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3436 QualType castType, ARCConversionTypeClass castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003437 Expr *castExpr, Expr *realCast,
3438 ARCConversionTypeClass exprACTC,
John McCall4124c492011-10-17 18:40:02 +00003439 Sema::CheckedConversionKind CCK) {
John McCall31168b02011-06-15 23:02:42 +00003440 SourceLocation loc =
John McCalle4fe2452011-10-01 01:01:08 +00003441 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCall31168b02011-06-15 23:02:42 +00003442
John McCall4124c492011-10-17 18:40:02 +00003443 if (S.makeUnavailableInSystemHeader(loc,
John McCalle4fe2452011-10-01 01:01:08 +00003444 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCall31168b02011-06-15 23:02:42 +00003445 return;
John McCall4124c492011-10-17 18:40:02 +00003446
3447 QualType castExprType = castExpr->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00003448 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003449 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3450 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3451 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
Fariborz Jahanian1ad83a32014-06-18 23:22:38 +00003452 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003453 return;
John McCall31168b02011-06-15 23:02:42 +00003454
John McCall640767f2011-06-17 06:50:50 +00003455 unsigned srcKind = 0;
John McCall31168b02011-06-15 23:02:42 +00003456 switch (exprACTC) {
John McCalle4fe2452011-10-01 01:01:08 +00003457 case ACTC_none:
3458 case ACTC_coreFoundation:
3459 case ACTC_voidPtr:
3460 srcKind = (castExprType->isPointerType() ? 1 : 0);
3461 break;
3462 case ACTC_retainable:
3463 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3464 break;
3465 case ACTC_indirectRetainable:
3466 srcKind = 4;
3467 break;
John McCall31168b02011-06-15 23:02:42 +00003468 }
3469
John McCall4124c492011-10-17 18:40:02 +00003470 // Check whether this could be fixed with a bridge cast.
3471 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
3472 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCall31168b02011-06-15 23:02:42 +00003473
John McCall4124c492011-10-17 18:40:02 +00003474 // Bridge from an ARC type to a CF type.
3475 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003476
John McCall4124c492011-10-17 18:40:02 +00003477 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3478 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3479 << 2 // of C pointer type
3480 << castExprType
3481 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3482 << castType
3483 << castRange
3484 << castExpr->getSourceRange();
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003485 bool br = S.isKnownName("CFBridgingRelease");
Jordan Rose4502b532012-07-31 01:07:43 +00003486 ACCResult CreateRule =
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003487 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003488 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003489 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003490 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003491 DiagnosticBuilder DiagB =
3492 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3493 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Craig Topperc3ec1492014-05-26 06:22:03 +00003494
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003495 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003496 castType, castExpr, realCast, "__bridge ",
3497 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003498 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003499 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003500 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003501 DiagnosticBuilder DiagB =
3502 (CCK == Sema::CCK_OtherCast && !br) ?
3503 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3504 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3505 diag::note_arc_bridge_transfer)
3506 << castExprType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003507
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003508 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003509 castType, castExpr, realCast, "__bridge_transfer ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003510 br ? "CFBridgingRelease" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003511 }
John McCall4124c492011-10-17 18:40:02 +00003512
3513 return;
3514 }
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003515
John McCall4124c492011-10-17 18:40:02 +00003516 // Bridge from a CF type to an ARC type.
3517 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003518 bool br = S.isKnownName("CFBridgingRetain");
John McCall4124c492011-10-17 18:40:02 +00003519 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3520 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3521 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3522 << castExprType
3523 << 2 // to C pointer type
3524 << castType
3525 << castRange
3526 << castExpr->getSourceRange();
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003527 ACCResult CreateRule =
3528 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003529 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003530 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003531 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003532 DiagnosticBuilder DiagB =
3533 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3534 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003535 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003536 castType, castExpr, realCast, "__bridge ",
3537 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003538 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003539 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003540 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003541 DiagnosticBuilder DiagB =
3542 (CCK == Sema::CCK_OtherCast && !br) ?
3543 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3544 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3545 diag::note_arc_bridge_retained)
3546 << castType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003547
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003548 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003549 castType, castExpr, realCast, "__bridge_retained ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003550 br ? "CFBridgingRetain" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003551 }
John McCall4124c492011-10-17 18:40:02 +00003552
3553 return;
John McCall31168b02011-06-15 23:02:42 +00003554 }
3555
John McCall4124c492011-10-17 18:40:02 +00003556 S.Diag(loc, diag::err_arc_mismatched_cast)
3557 << (CCK != Sema::CCK_ImplicitConversion)
3558 << srcKind << castExprType << castType
John McCall31168b02011-06-15 23:02:42 +00003559 << castRange << castExpr->getSourceRange();
3560}
3561
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003562template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003563static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3564 bool &HadTheAttribute, bool warn) {
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003565 QualType T = castExpr->getType();
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003566 HadTheAttribute = false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003567 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3568 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003569 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003570 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003571 HadTheAttribute = true;
Fariborz Jahanianc9e266b2014-12-11 22:56:26 +00003572 if (Parm->isStr("id"))
3573 return true;
3574
Craig Topperc3ec1492014-05-26 06:22:03 +00003575 NamedDecl *Target = nullptr;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003576 // Check for an existing type with this name.
3577 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3578 Sema::LookupOrdinaryName);
3579 if (S.LookupName(R, S.TUScope)) {
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003580 Target = R.getFoundDecl();
3581 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3582 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3583 if (const ObjCObjectPointerType *InterfacePointerType =
3584 castType->getAsObjCInterfacePointerType()) {
3585 ObjCInterfaceDecl *CastClass
3586 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003587 if ((CastClass == ExprClass) ||
Fariborz Jahanian27aa9b42015-04-10 22:07:47 +00003588 (CastClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003589 return true;
3590 if (warn)
3591 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3592 << T << Target->getName() << castType->getPointeeType();
3593 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003594 } else if (castType->isObjCIdType() ||
3595 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3596 castType, ExprClass)))
3597 // ok to cast to 'id'.
3598 // casting to id<p-list> is ok if bridge type adopts all of
3599 // p-list protocols.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003600 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003601 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003602 if (warn) {
3603 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3604 << T << Target->getName() << castType;
3605 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3606 S.Diag(Target->getLocStart(), diag::note_declared_at);
3607 }
3608 return false;
Fariborz Jahanian2c312122013-11-16 23:22:37 +00003609 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003610 }
Fariborz Jahanian696c8872015-04-09 23:39:53 +00003611 } else if (!castType->isObjCIdType()) {
3612 S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface)
3613 << castExpr->getType() << Parm;
3614 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3615 if (Target)
3616 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003617 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003618 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003619 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003620 return false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003621 }
3622 T = TDNDecl->getUnderlyingType();
3623 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003624 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003625}
3626
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003627template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003628static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
3629 bool &HadTheAttribute, bool warn) {
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003630 QualType T = castType;
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003631 HadTheAttribute = false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003632 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3633 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003634 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003635 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003636 HadTheAttribute = true;
John McCallaf6b3f82015-03-10 18:41:23 +00003637 if (Parm->isStr("id"))
3638 return true;
3639
Craig Topperc3ec1492014-05-26 06:22:03 +00003640 NamedDecl *Target = nullptr;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003641 // Check for an existing type with this name.
3642 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3643 Sema::LookupOrdinaryName);
3644 if (S.LookupName(R, S.TUScope)) {
3645 Target = R.getFoundDecl();
3646 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3647 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3648 if (const ObjCObjectPointerType *InterfacePointerType =
3649 castExpr->getType()->getAsObjCInterfacePointerType()) {
3650 ObjCInterfaceDecl *ExprClass
3651 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003652 if ((CastClass == ExprClass) ||
3653 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003654 return true;
3655 if (warn) {
3656 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3657 << castExpr->getType()->getPointeeType() << T;
3658 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3659 }
3660 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003661 } else if (castExpr->getType()->isObjCIdType() ||
3662 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3663 castExpr->getType(), CastClass)))
3664 // ok to cast an 'id' expression to a CFtype.
3665 // ok to cast an 'id<plist>' expression to CFtype provided plist
3666 // adopts all of CFtype's ObjetiveC's class plist.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003667 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003668 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003669 if (warn) {
3670 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3671 << castExpr->getType() << castType;
3672 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3673 S.Diag(Target->getLocStart(), diag::note_declared_at);
3674 }
3675 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003676 }
3677 }
3678 }
3679 S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject)
3680 << castExpr->getType() << castType;
3681 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3682 if (Target)
3683 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003684 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003685 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003686 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003687 }
3688 T = TDNDecl->getUnderlyingType();
3689 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003690 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003691}
3692
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003693void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003694 if (!getLangOpts().ObjC1)
3695 return;
Alp Tokerf6a24ce2013-12-05 16:25:25 +00003696 // warn in presence of __bridge casting to or from a toll free bridge cast.
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003697 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3698 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003699 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003700 bool HasObjCBridgeAttr;
3701 bool ObjCBridgeAttrWillNotWarn =
3702 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3703 false);
3704 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3705 return;
3706 bool HasObjCBridgeMutableAttr;
3707 bool ObjCBridgeMutableAttrWillNotWarn =
3708 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3709 HasObjCBridgeMutableAttr, false);
3710 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3711 return;
3712
3713 if (HasObjCBridgeAttr)
3714 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3715 true);
3716 else if (HasObjCBridgeMutableAttr)
3717 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3718 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003719 }
3720 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003721 bool HasObjCBridgeAttr;
3722 bool ObjCBridgeAttrWillNotWarn =
3723 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3724 false);
3725 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3726 return;
3727 bool HasObjCBridgeMutableAttr;
3728 bool ObjCBridgeMutableAttrWillNotWarn =
3729 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3730 HasObjCBridgeMutableAttr, false);
3731 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3732 return;
3733
3734 if (HasObjCBridgeAttr)
3735 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3736 true);
3737 else if (HasObjCBridgeMutableAttr)
3738 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3739 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003740 }
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003741}
3742
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003743void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
3744 QualType SrcType = castExpr->getType();
3745 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
3746 if (PRE->isExplicitProperty()) {
3747 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
3748 SrcType = PDecl->getType();
3749 }
3750 else if (PRE->isImplicitProperty()) {
3751 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
3752 SrcType = Getter->getReturnType();
3753
3754 }
3755 }
3756
3757 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
3758 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
3759 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
3760 return;
3761 CheckObjCBridgeRelatedConversions(castExpr->getLocStart(),
3762 castType, SrcType, castExpr);
3763 return;
3764}
3765
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00003766bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
3767 CastKind &Kind) {
3768 if (!getLangOpts().ObjC1)
3769 return false;
3770 ARCConversionTypeClass exprACTC =
3771 classifyTypeForARCConversion(castExpr->getType());
3772 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3773 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
3774 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
3775 CheckTollFreeBridgeCast(castType, castExpr);
3776 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
3777 : CK_CPointerToObjCPointerCast;
3778 return true;
3779 }
3780 return false;
3781}
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003782
3783bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
3784 QualType DestType, QualType SrcType,
3785 ObjCInterfaceDecl *&RelatedClass,
3786 ObjCMethodDecl *&ClassMethod,
3787 ObjCMethodDecl *&InstanceMethod,
3788 TypedefNameDecl *&TDNDecl,
3789 bool CfToNs) {
3790 QualType T = CfToNs ? SrcType : DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003791 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
3792 if (!ObjCBAttr)
3793 return false;
3794
3795 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
3796 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
3797 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
3798 if (!RCId)
3799 return false;
Craig Topperc3ec1492014-05-26 06:22:03 +00003800 NamedDecl *Target = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003801 // Check for an existing type with this name.
3802 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
3803 Sema::LookupOrdinaryName);
3804 if (!LookupName(R, TUScope)) {
3805 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003806 << SrcType << DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003807 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3808 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003809 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003810 Target = R.getFoundDecl();
3811 if (Target && isa<ObjCInterfaceDecl>(Target))
3812 RelatedClass = cast<ObjCInterfaceDecl>(Target);
3813 else {
3814 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
3815 << SrcType << DestType;
3816 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3817 if (Target)
3818 Diag(Target->getLocStart(), diag::note_declared_at);
3819 return false;
3820 }
3821
3822 // Check for an existing class method with the given selector name.
3823 if (CfToNs && CMId) {
3824 Selector Sel = Context.Selectors.getUnarySelector(CMId);
3825 ClassMethod = RelatedClass->lookupMethod(Sel, false);
3826 if (!ClassMethod) {
3827 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003828 << SrcType << DestType << Sel << false;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003829 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3830 return false;
3831 }
3832 }
3833
3834 // Check for an existing instance method with the given selector name.
3835 if (!CfToNs && IMId) {
3836 Selector Sel = Context.Selectors.getNullarySelector(IMId);
3837 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
3838 if (!InstanceMethod) {
3839 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003840 << SrcType << DestType << Sel << true;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003841 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3842 return false;
3843 }
3844 }
3845 return true;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003846}
3847
3848bool
3849Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003850 QualType DestType, QualType SrcType,
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003851 Expr *&SrcExpr) {
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003852 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
3853 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
3854 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
3855 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
3856 if (!CfToNs && !NsToCf)
3857 return false;
3858
3859 ObjCInterfaceDecl *RelatedClass;
Craig Topperc3ec1492014-05-26 06:22:03 +00003860 ObjCMethodDecl *ClassMethod = nullptr;
3861 ObjCMethodDecl *InstanceMethod = nullptr;
3862 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003863 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
3864 ClassMethod, InstanceMethod, TDNDecl, CfToNs))
3865 return false;
3866
3867 if (CfToNs) {
3868 // Implicit conversion from CF to ObjC object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003869 if (ClassMethod) {
3870 std::string ExpressionString = "[";
3871 ExpressionString += RelatedClass->getNameAsString();
3872 ExpressionString += " ";
3873 ExpressionString += ClassMethod->getSelector().getAsString();
3874 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
3875 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003876 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003877 << SrcType << DestType << ClassMethod->getSelector() << false
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003878 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString)
3879 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003880 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3881 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3882
3883 QualType receiverType =
3884 Context.getObjCInterfaceType(RelatedClass);
3885 // Argument.
3886 Expr *args[] = { SrcExpr };
3887 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
3888 ClassMethod->getLocation(),
3889 ClassMethod->getSelector(), ClassMethod,
3890 MultiExprArg(args, 1));
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003891 SrcExpr = msg.get();
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003892 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003893 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003894 }
3895 else {
3896 // Implicit conversion from ObjC type to CF object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003897 if (InstanceMethod) {
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003898 std::string ExpressionString;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003899 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003900 if (InstanceMethod->isPropertyAccessor())
3901 if (const ObjCPropertyDecl *PDecl = InstanceMethod->findPropertyDecl()) {
3902 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
3903 ExpressionString = ".";
3904 ExpressionString += PDecl->getNameAsString();
3905 Diag(Loc, diag::err_objc_bridged_related_known_method)
3906 << SrcType << DestType << InstanceMethod->getSelector() << true
3907 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3908 }
3909 if (ExpressionString.empty()) {
3910 // Provide a fixit: [ObjectExpr InstanceMethod]
3911 ExpressionString = " ";
3912 ExpressionString += InstanceMethod->getSelector().getAsString();
3913 ExpressionString += "]";
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003914
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003915 Diag(Loc, diag::err_objc_bridged_related_known_method)
3916 << SrcType << DestType << InstanceMethod->getSelector() << true
3917 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[")
3918 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3919 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003920 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3921 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3922
3923 ExprResult msg =
3924 BuildInstanceMessageImplicit(SrcExpr, SrcType,
3925 InstanceMethod->getLocation(),
3926 InstanceMethod->getSelector(),
3927 InstanceMethod, None);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003928 SrcExpr = msg.get();
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003929 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003930 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003931 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003932 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003933}
3934
John McCall4124c492011-10-17 18:40:02 +00003935Sema::ARCConversionResult
3936Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003937 Expr *&castExpr, CheckedConversionKind CCK,
Fariborz Jahanianc03ef572014-06-18 23:52:49 +00003938 bool DiagnoseCFAudited,
3939 BinaryOperatorKind Opc) {
John McCall4124c492011-10-17 18:40:02 +00003940 QualType castExprType = castExpr->getType();
3941
3942 // For the purposes of the classification, we assume reference types
3943 // will bind to temporaries.
3944 QualType effCastType = castType;
3945 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
3946 effCastType = ref->getPointeeType();
3947
3948 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
3949 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003950 if (exprACTC == castACTC) {
3951 // check for viablity and report error if casting an rvalue to a
3952 // life-time qualifier.
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003953 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003954 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003955 (castType != castExprType)) {
3956 const Type *DT = castType.getTypePtr();
3957 QualType QDT = castType;
3958 // We desugar some types but not others. We ignore those
3959 // that cannot happen in a cast; i.e. auto, and those which
3960 // should not be de-sugared; i.e typedef.
3961 if (const ParenType *PT = dyn_cast<ParenType>(DT))
3962 QDT = PT->desugar();
3963 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
3964 QDT = TP->desugar();
3965 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
3966 QDT = AT->desugar();
3967 if (QDT != castType &&
3968 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
3969 SourceLocation loc =
3970 (castRange.isValid() ? castRange.getBegin()
3971 : castExpr->getExprLoc());
3972 Diag(loc, diag::err_arc_nolifetime_behavior);
3973 }
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003974 }
3975 return ACR_okay;
3976 }
3977
John McCall4124c492011-10-17 18:40:02 +00003978 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
3979
3980 // Allow all of these types to be cast to integer types (but not
3981 // vice-versa).
3982 if (castACTC == ACTC_none && castType->isIntegralType(Context))
3983 return ACR_okay;
3984
3985 // Allow casts between pointers to lifetime types (e.g., __strong id*)
3986 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
3987 // must be explicit.
3988 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
3989 return ACR_okay;
3990 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
3991 CCK != CCK_ImplicitConversion)
3992 return ACR_okay;
3993
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003994 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
John McCall4124c492011-10-17 18:40:02 +00003995 // For invalid casts, fall through.
3996 case ACC_invalid:
3997 break;
3998
3999 // Do nothing for both bottom and +0.
4000 case ACC_bottom:
4001 case ACC_plusZero:
4002 return ACR_okay;
4003
4004 // If the result is +1, consume it here.
4005 case ACC_plusOne:
4006 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
4007 CK_ARCConsumeObject, castExpr,
Craig Topperc3ec1492014-05-26 06:22:03 +00004008 nullptr, VK_RValue);
John McCall4124c492011-10-17 18:40:02 +00004009 ExprNeedsCleanups = true;
4010 return ACR_okay;
4011 }
4012
4013 // If this is a non-implicit cast from id or block type to a
4014 // CoreFoundation type, delay complaining in case the cast is used
4015 // in an acceptable context.
4016 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
4017 CCK != CCK_ImplicitConversion)
4018 return ACR_unbridged;
4019
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00004020 // Do not issue bridge cast" diagnostic when implicit casting a cstring
4021 // to 'NSString *'. Let caller issue a normal mismatched diagnostic with
4022 // suitable fix-it.
Fariborz Jahanian283bf892013-12-18 21:04:43 +00004023 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
4024 ConversionToObjCStringLiteralCheck(castType, castExpr))
4025 return ACR_okay;
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00004026
Fariborz Jahanian25eef192013-07-31 21:40:51 +00004027 // Do not issue "bridge cast" diagnostic when implicit casting
4028 // a retainable object to a CF type parameter belonging to an audited
4029 // CF API function. Let caller issue a normal type mismatched diagnostic
4030 // instead.
4031 if (!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
4032 castACTC != ACTC_coreFoundation)
Fariborz Jahanianc03ef572014-06-18 23:52:49 +00004033 if (!(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
4034 (Opc == BO_NE || Opc == BO_EQ)))
4035 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
4036 castExpr, castExpr, exprACTC, CCK);
John McCall4124c492011-10-17 18:40:02 +00004037 return ACR_okay;
4038}
4039
4040/// Given that we saw an expression with the ARCUnbridgedCastTy
4041/// placeholder type, complain bitterly.
4042void Sema::diagnoseARCUnbridgedCast(Expr *e) {
4043 // We expect the spurious ImplicitCastExpr to already have been stripped.
4044 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4045 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
4046
4047 SourceRange castRange;
4048 QualType castType;
4049 CheckedConversionKind CCK;
4050
4051 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
4052 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
4053 castType = cast->getTypeAsWritten();
4054 CCK = CCK_CStyleCast;
4055 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
4056 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
4057 castType = cast->getTypeAsWritten();
4058 CCK = CCK_OtherCast;
4059 } else {
4060 castType = cast->getType();
4061 CCK = CCK_ImplicitConversion;
4062 }
4063
4064 ARCConversionTypeClass castACTC =
4065 classifyTypeForARCConversion(castType.getNonReferenceType());
4066
4067 Expr *castExpr = realCast->getSubExpr();
4068 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
4069
4070 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00004071 castExpr, realCast, ACTC_retainable, CCK);
John McCall4124c492011-10-17 18:40:02 +00004072}
4073
4074/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
4075/// type, remove the placeholder cast.
4076Expr *Sema::stripARCUnbridgedCast(Expr *e) {
4077 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4078
4079 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
4080 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
4081 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
4082 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
4083 assert(uo->getOpcode() == UO_Extension);
4084 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
4085 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
4086 sub->getValueKind(), sub->getObjectKind(),
4087 uo->getOperatorLoc());
4088 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
4089 assert(!gse->isResultDependent());
4090
4091 unsigned n = gse->getNumAssocs();
4092 SmallVector<Expr*, 4> subExprs(n);
4093 SmallVector<TypeSourceInfo*, 4> subTypes(n);
4094 for (unsigned i = 0; i != n; ++i) {
4095 subTypes[i] = gse->getAssocTypeSourceInfo(i);
4096 Expr *sub = gse->getAssocExpr(i);
4097 if (i == gse->getResultIndex())
4098 sub = stripARCUnbridgedCast(sub);
4099 subExprs[i] = sub;
4100 }
4101
4102 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
4103 gse->getControllingExpr(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00004104 subTypes, subExprs,
4105 gse->getDefaultLoc(),
John McCall4124c492011-10-17 18:40:02 +00004106 gse->getRParenLoc(),
4107 gse->containsUnexpandedParameterPack(),
4108 gse->getResultIndex());
4109 } else {
4110 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
4111 return cast<ImplicitCastExpr>(e)->getSubExpr();
4112 }
4113}
4114
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004115bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
4116 QualType exprType) {
4117 QualType canCastType =
4118 Context.getCanonicalType(castType).getUnqualifiedType();
4119 QualType canExprType =
4120 Context.getCanonicalType(exprType).getUnqualifiedType();
4121 if (isa<ObjCObjectPointerType>(canCastType) &&
4122 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
4123 canExprType->isObjCObjectPointerType()) {
4124 if (const ObjCObjectPointerType *ObjT =
4125 canExprType->getAs<ObjCObjectPointerType>())
Richard Smith802c4b72012-08-23 06:16:52 +00004126 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
4127 return !ObjI->isArcWeakrefUnavailable();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004128 }
4129 return true;
4130}
4131
John McCall4db5c3c2011-07-07 06:58:02 +00004132/// Look for an ObjCReclaimReturnedObject cast and destroy it.
4133static Expr *maybeUndoReclaimObject(Expr *e) {
4134 // For now, we just undo operands that are *immediately* reclaim
4135 // expressions, which prevents the vast majority of potential
4136 // problems here. To catch them all, we'd need to rebuild arbitrary
4137 // value-propagating subexpressions --- we can't reliably rebuild
4138 // in-place because of expression sharing.
4139 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall2d637d22011-09-10 06:18:15 +00004140 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall4db5c3c2011-07-07 06:58:02 +00004141 return ice->getSubExpr();
4142
4143 return e;
4144}
4145
John McCall31168b02011-06-15 23:02:42 +00004146ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
4147 ObjCBridgeCastKind Kind,
4148 SourceLocation BridgeKeywordLoc,
4149 TypeSourceInfo *TSInfo,
4150 Expr *SubExpr) {
John McCalleb075542011-08-26 00:48:42 +00004151 ExprResult SubResult = UsualUnaryConversions(SubExpr);
4152 if (SubResult.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004153 SubExpr = SubResult.get();
John McCalleb075542011-08-26 00:48:42 +00004154
John McCall31168b02011-06-15 23:02:42 +00004155 QualType T = TSInfo->getType();
4156 QualType FromType = SubExpr->getType();
4157
John McCall9320b872011-09-09 05:25:32 +00004158 CastKind CK;
4159
John McCall31168b02011-06-15 23:02:42 +00004160 bool MustConsume = false;
4161 if (T->isDependentType() || SubExpr->isTypeDependent()) {
4162 // Okay: we'll build a dependent expression type.
John McCall9320b872011-09-09 05:25:32 +00004163 CK = CK_Dependent;
John McCall31168b02011-06-15 23:02:42 +00004164 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
4165 // Casting CF -> id
John McCall9320b872011-09-09 05:25:32 +00004166 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
4167 : CK_CPointerToObjCPointerCast);
John McCall31168b02011-06-15 23:02:42 +00004168 switch (Kind) {
4169 case OBC_Bridge:
4170 break;
4171
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004172 case OBC_BridgeRetained: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00004173 bool br = isKnownName("CFBridgingRelease");
John McCall31168b02011-06-15 23:02:42 +00004174 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4175 << 2
4176 << FromType
4177 << (T->isBlockPointerType()? 1 : 0)
4178 << T
4179 << SubExpr->getSourceRange()
4180 << Kind;
4181 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4182 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
4183 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004184 << FromType << br
John McCall31168b02011-06-15 23:02:42 +00004185 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004186 br ? "CFBridgingRelease "
4187 : "__bridge_transfer ");
John McCall31168b02011-06-15 23:02:42 +00004188
4189 Kind = OBC_Bridge;
4190 break;
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004191 }
John McCall31168b02011-06-15 23:02:42 +00004192
4193 case OBC_BridgeTransfer:
4194 // We must consume the Objective-C object produced by the cast.
4195 MustConsume = true;
4196 break;
4197 }
4198 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
4199 // Okay: id -> CF
John McCall9320b872011-09-09 05:25:32 +00004200 CK = CK_BitCast;
John McCall31168b02011-06-15 23:02:42 +00004201 switch (Kind) {
Fariborz Jahanian214567c2014-10-28 17:26:21 +00004202 case OBC_Bridge:
4203 // Reclaiming a value that's going to be __bridge-casted to CF
4204 // is very dangerous, so we don't do it.
4205 SubExpr = maybeUndoReclaimObject(SubExpr);
4206 break;
John McCall31168b02011-06-15 23:02:42 +00004207
4208 case OBC_BridgeRetained:
4209 // Produce the object before casting it.
4210 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall2d637d22011-09-10 06:18:15 +00004211 CK_ARCProduceObject,
Craig Topperc3ec1492014-05-26 06:22:03 +00004212 SubExpr, nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004213 break;
4214
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004215 case OBC_BridgeTransfer: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00004216 bool br = isKnownName("CFBridgingRetain");
John McCall31168b02011-06-15 23:02:42 +00004217 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4218 << (FromType->isBlockPointerType()? 1 : 0)
4219 << FromType
4220 << 2
4221 << T
4222 << SubExpr->getSourceRange()
4223 << Kind;
4224
4225 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4226 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
4227 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004228 << T << br
4229 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4230 br ? "CFBridgingRetain " : "__bridge_retained");
John McCall31168b02011-06-15 23:02:42 +00004231
4232 Kind = OBC_Bridge;
4233 break;
4234 }
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004235 }
John McCall31168b02011-06-15 23:02:42 +00004236 } else {
4237 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
4238 << FromType << T << Kind
4239 << SubExpr->getSourceRange()
4240 << TSInfo->getTypeLoc().getSourceRange();
4241 return ExprError();
4242 }
4243
John McCall9320b872011-09-09 05:25:32 +00004244 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCall31168b02011-06-15 23:02:42 +00004245 BridgeKeywordLoc,
4246 TSInfo, SubExpr);
4247
4248 if (MustConsume) {
4249 ExprNeedsCleanups = true;
John McCall2d637d22011-09-10 06:18:15 +00004250 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
Craig Topperc3ec1492014-05-26 06:22:03 +00004251 nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004252 }
4253
4254 return Result;
4255}
4256
4257ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
4258 SourceLocation LParenLoc,
4259 ObjCBridgeCastKind Kind,
4260 SourceLocation BridgeKeywordLoc,
4261 ParsedType Type,
4262 SourceLocation RParenLoc,
4263 Expr *SubExpr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004264 TypeSourceInfo *TSInfo = nullptr;
John McCall31168b02011-06-15 23:02:42 +00004265 QualType T = GetTypeFromParser(Type, &TSInfo);
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00004266 if (Kind == OBC_Bridge)
4267 CheckTollFreeBridgeCast(T, SubExpr);
John McCall31168b02011-06-15 23:02:42 +00004268 if (!TSInfo)
4269 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
4270 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
4271 SubExpr);
4272}