blob: 7dbd660f53ec697abf725774d6757af3c7287104 [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,
Craig Topper883dd332015-12-24 23:58:11 +000035 ArrayRef<Expr *> Strings) {
Chris Lattnerd7670d92009-02-18 06:13:04 +000036 // Most ObjC strings are formed out of a single piece. However, we *can*
37 // have strings formed out of multiple @ strings with multiple pptokens in
38 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
39 // StringLiteral for ObjCStringLiteral to hold onto.
Craig Topper883dd332015-12-24 23:58:11 +000040 StringLiteral *S = cast<StringLiteral>(Strings[0]);
Mike Stump11289f42009-09-09 15:08:12 +000041
Chris Lattnerd7670d92009-02-18 06:13:04 +000042 // If we have a multi-part string, merge it all together.
Craig Topper883dd332015-12-24 23:58:11 +000043 if (Strings.size() != 1) {
Chris Lattnera3fc41d2008-01-04 22:32:30 +000044 // Concatenate objc strings.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000045 SmallString<128> StrBuf;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000046 SmallVector<SourceLocation, 8> StrLocs;
Mike Stump11289f42009-09-09 15:08:12 +000047
Craig Topper883dd332015-12-24 23:58:11 +000048 for (Expr *E : Strings) {
49 S = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +000050
Douglas Gregorfb65e592011-07-27 05:40:30 +000051 // ObjC strings can't be wide or UTF.
52 if (!S->isAscii()) {
Chris Lattnerd7670d92009-02-18 06:13:04 +000053 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
54 << S->getSourceRange();
55 return true;
56 }
Mike Stump11289f42009-09-09 15:08:12 +000057
Benjamin Kramer35b077e2010-08-17 12:54:38 +000058 // Append the string.
59 StrBuf += S->getString();
Mike Stump11289f42009-09-09 15:08:12 +000060
Chris Lattner163ffd22009-02-18 06:48:40 +000061 // Get the locations of the string tokens.
62 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Chris Lattnera3fc41d2008-01-04 22:32:30 +000063 }
Mike Stump11289f42009-09-09 15:08:12 +000064
Chris Lattner163ffd22009-02-18 06:48:40 +000065 // Create the aggregate string with the appropriate content and location
66 // information.
Benjamin Kramercdac7612014-02-25 12:26:20 +000067 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
68 assert(CAT && "String literal not of constant array type!");
69 QualType StrTy = Context.getConstantArrayType(
70 CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1),
71 CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers());
72 S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii,
73 /*Pascal=*/false, StrTy, &StrLocs[0],
74 StrLocs.size());
Chris Lattnera3fc41d2008-01-04 22:32:30 +000075 }
Ted Kremeneke65b0862012-03-06 20:05:56 +000076
77 return BuildObjCStringLiteral(AtLocs[0], S);
78}
Mike Stump11289f42009-09-09 15:08:12 +000079
Ted Kremeneke65b0862012-03-06 20:05:56 +000080ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
Chris Lattner6436fb62009-02-18 06:01:06 +000081 // Verify that this composite string is acceptable for ObjC strings.
82 if (CheckObjCString(S))
Chris Lattnera3fc41d2008-01-04 22:32:30 +000083 return true;
Chris Lattnerfffd6a72009-02-18 06:06:56 +000084
85 // Initialize the constant string interface lazily. This assumes
Steve Naroff54e59452009-04-07 14:18:33 +000086 // the NSString interface is seen in this translation unit. Note: We
87 // don't use NSConstantString, since the runtime team considers this
88 // interface private (even though it appears in the header files).
Chris Lattnerfffd6a72009-02-18 06:06:56 +000089 QualType Ty = Context.getObjCConstantStringInterface();
90 if (!Ty.isNull()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +000091 Ty = Context.getObjCObjectPointerType(Ty);
David Blaikiebbafb8a2012-03-11 07:00:24 +000092 } else if (getLangOpts().NoConstantCFStrings) {
Craig Topperc3ec1492014-05-26 06:22:03 +000093 IdentifierInfo *NSIdent=nullptr;
David Blaikiebbafb8a2012-03-11 07:00:24 +000094 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Fariborz Jahanian50c925f2010-10-19 17:19:29 +000095
96 if (StringClass.empty())
97 NSIdent = &Context.Idents.get("NSConstantString");
98 else
99 NSIdent = &Context.Idents.get(StringClass);
100
Ted Kremeneke65b0862012-03-06 20:05:56 +0000101 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Fariborz Jahanian07317632010-04-23 23:19:04 +0000102 LookupOrdinaryName);
103 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
104 Context.setObjCConstantStringInterface(StrIF);
105 Ty = Context.getObjCConstantStringInterface();
106 Ty = Context.getObjCObjectPointerType(Ty);
107 } else {
108 // If there is no NSConstantString interface defined then treat this
109 // as error and recover from it.
110 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
111 << S->getSourceRange();
112 Ty = Context.getObjCIdType();
113 }
Chris Lattner091f6982008-06-21 21:44:18 +0000114 } else {
Patrick Beard0caa3942012-04-19 00:25:12 +0000115 IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000116 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000117 LookupOrdinaryName);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000118 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
119 Context.setObjCConstantStringInterface(StrIF);
120 Ty = Context.getObjCConstantStringInterface();
Steve Naroff7cae42b2009-07-10 23:34:53 +0000121 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000122 } else {
Fariborz Jahanian86f82662012-02-23 22:51:36 +0000123 // If there is no NSString interface defined, implicitly declare
124 // a @class NSString; and use that instead. This is to make sure
125 // type of an NSString literal is represented correctly, instead of
126 // being an 'id' type.
127 Ty = Context.getObjCNSStringType();
128 if (Ty.isNull()) {
129 ObjCInterfaceDecl *NSStringIDecl =
130 ObjCInterfaceDecl::Create (Context,
131 Context.getTranslationUnitDecl(),
132 SourceLocation(), NSIdent,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000133 nullptr, nullptr, SourceLocation());
Fariborz Jahanian86f82662012-02-23 22:51:36 +0000134 Ty = Context.getObjCInterfaceType(NSStringIDecl);
135 Context.setObjCNSStringType(Ty);
136 }
137 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000138 }
Chris Lattner091f6982008-06-21 21:44:18 +0000139 }
Mike Stump11289f42009-09-09 15:08:12 +0000140
Ted Kremeneke65b0862012-03-06 20:05:56 +0000141 return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
142}
143
Jordy Rose08e500c2012-05-12 17:32:44 +0000144/// \brief Emits an error if the given method does not exist, or if the return
145/// type is not an Objective-C object.
146static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
147 const ObjCInterfaceDecl *Class,
148 Selector Sel, const ObjCMethodDecl *Method) {
149 if (!Method) {
150 // FIXME: Is there a better way to avoid quotes than using getName()?
151 S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
152 return false;
153 }
154
155 // Make sure the return type is reasonable.
Alp Toker314cc812014-01-25 16:55:45 +0000156 QualType ReturnType = Method->getReturnType();
Jordy Rose08e500c2012-05-12 17:32:44 +0000157 if (!ReturnType->isObjCObjectPointerType()) {
158 S.Diag(Loc, diag::err_objc_literal_method_sig)
159 << Sel;
160 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
161 << ReturnType;
162 return false;
163 }
164
165 return true;
166}
167
Alex Denisovb7d85632015-07-24 05:09:40 +0000168/// \brief Maps ObjCLiteralKind to NSClassIdKindKind
169static NSAPI::NSClassIdKindKind ClassKindFromLiteralKind(
170 Sema::ObjCLiteralKind LiteralKind) {
171 switch (LiteralKind) {
172 case Sema::LK_Array:
173 return NSAPI::ClassId_NSArray;
174 case Sema::LK_Dictionary:
175 return NSAPI::ClassId_NSDictionary;
176 case Sema::LK_Numeric:
177 return NSAPI::ClassId_NSNumber;
178 case Sema::LK_String:
179 return NSAPI::ClassId_NSString;
180 case Sema::LK_Boxed:
181 return NSAPI::ClassId_NSValue;
182
183 // there is no corresponding matching
184 // between LK_None/LK_Block and NSClassIdKindKind
185 case Sema::LK_Block:
186 case Sema::LK_None:
Aaron Ballman3e839de2015-07-24 12:47:27 +0000187 break;
Alex Denisovb7d85632015-07-24 05:09:40 +0000188 }
Aaron Ballman3e839de2015-07-24 12:47:27 +0000189 llvm_unreachable("LiteralKind can't be converted into a ClassKind");
Alex Denisovb7d85632015-07-24 05:09:40 +0000190}
191
192/// \brief Validates ObjCInterfaceDecl availability.
193/// ObjCInterfaceDecl, used to create ObjC literals, should be defined
194/// if clang not in a debugger mode.
195static bool ValidateObjCLiteralInterfaceDecl(Sema &S, ObjCInterfaceDecl *Decl,
196 SourceLocation Loc,
197 Sema::ObjCLiteralKind LiteralKind) {
198 if (!Decl) {
199 NSAPI::NSClassIdKindKind Kind = ClassKindFromLiteralKind(LiteralKind);
200 IdentifierInfo *II = S.NSAPIObj->getNSClassId(Kind);
201 S.Diag(Loc, diag::err_undeclared_objc_literal_class)
202 << II->getName() << LiteralKind;
203 return false;
204 } else if (!Decl->hasDefinition() && !S.getLangOpts().DebuggerObjCLiteral) {
205 S.Diag(Loc, diag::err_undeclared_objc_literal_class)
206 << Decl->getName() << LiteralKind;
207 S.Diag(Decl->getLocation(), diag::note_forward_class);
208 return false;
209 }
210
211 return true;
212}
213
214/// \brief Looks up ObjCInterfaceDecl of a given NSClassIdKindKind.
215/// Used to create ObjC literals, such as NSDictionary (@{}),
216/// NSArray (@[]) and Boxed Expressions (@())
217static ObjCInterfaceDecl *LookupObjCInterfaceDeclForLiteral(Sema &S,
218 SourceLocation Loc,
219 Sema::ObjCLiteralKind LiteralKind) {
220 NSAPI::NSClassIdKindKind ClassKind = ClassKindFromLiteralKind(LiteralKind);
221 IdentifierInfo *II = S.NSAPIObj->getNSClassId(ClassKind);
222 NamedDecl *IF = S.LookupSingleName(S.TUScope, II, Loc,
223 Sema::LookupOrdinaryName);
224 ObjCInterfaceDecl *ID = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
225 if (!ID && S.getLangOpts().DebuggerObjCLiteral) {
226 ASTContext &Context = S.Context;
227 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
228 ID = ObjCInterfaceDecl::Create (Context, TU, SourceLocation(), II,
229 nullptr, nullptr, SourceLocation());
230 }
231
232 if (!ValidateObjCLiteralInterfaceDecl(S, ID, Loc, LiteralKind)) {
233 ID = nullptr;
234 }
235
236 return ID;
237}
238
Ted Kremeneke65b0862012-03-06 20:05:56 +0000239/// \brief Retrieve the NSNumber factory method that should be used to create
240/// an Objective-C literal for the given type.
241static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
Patrick Beard0caa3942012-04-19 00:25:12 +0000242 QualType NumberType,
243 bool isLiteral = false,
244 SourceRange R = SourceRange()) {
David Blaikie05785d12013-02-20 22:23:23 +0000245 Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
246 S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
247
Ted Kremeneke65b0862012-03-06 20:05:56 +0000248 if (!Kind) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000249 if (isLiteral) {
250 S.Diag(Loc, diag::err_invalid_nsnumber_type)
251 << NumberType << R;
252 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000253 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000254 }
Patrick Beard0caa3942012-04-19 00:25:12 +0000255
Ted Kremeneke65b0862012-03-06 20:05:56 +0000256 // If we already looked up this method, we're done.
257 if (S.NSNumberLiteralMethods[*Kind])
258 return S.NSNumberLiteralMethods[*Kind];
259
260 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
261 /*Instance=*/false);
262
Patrick Beard0caa3942012-04-19 00:25:12 +0000263 ASTContext &CX = S.Context;
264
265 // Look up the NSNumber class, if we haven't done so already. It's cached
266 // in the Sema instance.
267 if (!S.NSNumberDecl) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000268 S.NSNumberDecl = LookupObjCInterfaceDeclForLiteral(S, Loc,
269 Sema::LK_Numeric);
Patrick Beard0caa3942012-04-19 00:25:12 +0000270 if (!S.NSNumberDecl) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000271 return nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000272 }
Alex Denisove36748a2015-02-16 16:17:05 +0000273 }
274
275 if (S.NSNumberPointer.isNull()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000276 // generate the pointer to NSNumber type.
Jordy Roseaca01f92012-05-12 17:32:52 +0000277 QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
278 S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000279 }
280
Ted Kremeneke65b0862012-03-06 20:05:56 +0000281 // Look for the appropriate method within NSNumber.
Jordy Roseaca01f92012-05-12 17:32:52 +0000282 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000283 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000284 // create a stub definition this NSNumber factory method.
Craig Topperc3ec1492014-05-26 06:22:03 +0000285 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000286 Method =
287 ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
288 S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
289 /*isInstance=*/false, /*isVariadic=*/false,
290 /*isPropertyAccessor=*/false,
291 /*isImplicitlyDeclared=*/true,
292 /*isDefined=*/false, ObjCMethodDecl::Required,
293 /*HasRelatedResultType=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000294 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
295 SourceLocation(), SourceLocation(),
Patrick Beard0caa3942012-04-19 00:25:12 +0000296 &CX.Idents.get("value"),
Craig Topperc3ec1492014-05-26 06:22:03 +0000297 NumberType, /*TInfo=*/nullptr,
298 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000299 Method->setMethodParams(S.Context, value, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000300 }
301
Jordy Rose08e500c2012-05-12 17:32:44 +0000302 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
Craig Topperc3ec1492014-05-26 06:22:03 +0000303 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000304
305 // Note: if the parameter type is out-of-line, we'll catch it later in the
306 // implicit conversion.
307
308 S.NSNumberLiteralMethods[*Kind] = Method;
309 return Method;
310}
311
Patrick Beard0caa3942012-04-19 00:25:12 +0000312/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
313/// numeric literal expression. Type of the expression will be "NSNumber *".
Ted Kremeneke65b0862012-03-06 20:05:56 +0000314ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000315 // Determine the type of the literal.
316 QualType NumberType = Number->getType();
317 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
318 // In C, character literals have type 'int'. That's not the type we want
319 // to use to determine the Objective-c literal kind.
320 switch (Char->getKind()) {
321 case CharacterLiteral::Ascii:
Aaron Ballman9a17c852016-01-07 20:59:26 +0000322 case CharacterLiteral::UTF8:
Ted Kremeneke65b0862012-03-06 20:05:56 +0000323 NumberType = Context.CharTy;
324 break;
325
326 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000327 NumberType = Context.getWideCharType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000328 break;
329
330 case CharacterLiteral::UTF16:
331 NumberType = Context.Char16Ty;
332 break;
333
334 case CharacterLiteral::UTF32:
335 NumberType = Context.Char32Ty;
336 break;
337 }
338 }
339
Ted Kremeneke65b0862012-03-06 20:05:56 +0000340 // Look for the appropriate method within NSNumber.
341 // Construct the literal.
Patrick Beard2565c592012-05-01 21:47:19 +0000342 SourceRange NR(Number->getSourceRange());
Patrick Beard0caa3942012-04-19 00:25:12 +0000343 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
Patrick Beard2565c592012-05-01 21:47:19 +0000344 true, NR);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000345 if (!Method)
346 return ExprError();
347
348 // Convert the number to the type that the parameter expects.
Alp Toker03376dc2014-07-07 09:02:20 +0000349 ParmVarDecl *ParamDecl = Method->parameters()[0];
Patrick Beard2565c592012-05-01 21:47:19 +0000350 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
351 ParamDecl);
352 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
353 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000354 Number);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000355 if (ConvertedNumber.isInvalid())
356 return ExprError();
357 Number = ConvertedNumber.get();
358
Patrick Beard2565c592012-05-01 21:47:19 +0000359 // Use the effective source range of the literal, including the leading '@'.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000360 return MaybeBindToTemporary(
Patrick Beard2565c592012-05-01 21:47:19 +0000361 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
362 SourceRange(AtLoc, NR.getEnd())));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000363}
364
365ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
366 SourceLocation ValueLoc,
367 bool Value) {
368 ExprResult Inner;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000369 if (getLangOpts().CPlusPlus) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000370 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
371 } else {
372 // C doesn't actually have a way to represent literal values of type
373 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
374 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
375 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
376 CK_IntegralToBoolean);
377 }
378
379 return BuildObjCNumericLiteral(AtLoc, Inner.get());
380}
381
382/// \brief Check that the given expression is a valid element of an Objective-C
383/// collection literal.
384static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000385 QualType T,
386 bool ArrayLiteral = false) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000387 // If the expression is type-dependent, there's nothing for us to do.
388 if (Element->isTypeDependent())
389 return Element;
390
391 ExprResult Result = S.CheckPlaceholderExpr(Element);
392 if (Result.isInvalid())
393 return ExprError();
394 Element = Result.get();
395
396 // In C++, check for an implicit conversion to an Objective-C object pointer
397 // type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000398 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000399 InitializedEntity Entity
Jordy Roseaca01f92012-05-12 17:32:52 +0000400 = InitializedEntity::InitializeParameter(S.Context, T,
401 /*Consumed=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000402 InitializationKind Kind
Jordy Roseaca01f92012-05-12 17:32:52 +0000403 = InitializationKind::CreateCopy(Element->getLocStart(),
404 SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000405 InitializationSequence Seq(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000406 if (!Seq.Failed())
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000407 return Seq.Perform(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000408 }
409
410 Expr *OrigElement = Element;
411
412 // Perform lvalue-to-rvalue conversion.
413 Result = S.DefaultLvalueConversion(Element);
414 if (Result.isInvalid())
415 return ExprError();
416 Element = Result.get();
417
418 // Make sure that we have an Objective-C pointer type or block.
419 if (!Element->getType()->isObjCObjectPointerType() &&
420 !Element->getType()->isBlockPointerType()) {
421 bool Recovered = false;
422
423 // If this is potentially an Objective-C numeric literal, add the '@'.
424 if (isa<IntegerLiteral>(OrigElement) ||
425 isa<CharacterLiteral>(OrigElement) ||
426 isa<FloatingLiteral>(OrigElement) ||
427 isa<ObjCBoolLiteralExpr>(OrigElement) ||
428 isa<CXXBoolLiteralExpr>(OrigElement)) {
429 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
430 int Which = isa<CharacterLiteral>(OrigElement) ? 1
431 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
432 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
433 : 3;
434
435 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
436 << Which << OrigElement->getSourceRange()
437 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
438
439 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
440 OrigElement);
441 if (Result.isInvalid())
442 return ExprError();
443
444 Element = Result.get();
445 Recovered = true;
446 }
447 }
448 // If this is potentially an Objective-C string literal, add the '@'.
449 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
450 if (String->isAscii()) {
451 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
452 << 0 << OrigElement->getSourceRange()
453 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
454
455 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
456 if (Result.isInvalid())
457 return ExprError();
458
459 Element = Result.get();
460 Recovered = true;
461 }
462 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000463
Ted Kremeneke65b0862012-03-06 20:05:56 +0000464 if (!Recovered) {
465 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
466 << Element->getType();
467 return ExprError();
468 }
469 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000470 if (ArrayLiteral)
Ted Kremenek197fee42013-10-09 22:34:33 +0000471 if (ObjCStringLiteral *getString =
472 dyn_cast<ObjCStringLiteral>(OrigElement)) {
473 if (StringLiteral *SL = getString->getString()) {
474 unsigned numConcat = SL->getNumConcatenated();
475 if (numConcat > 1) {
476 // Only warn if the concatenated string doesn't come from a macro.
477 bool hasMacro = false;
478 for (unsigned i = 0; i < numConcat ; ++i)
479 if (SL->getStrTokenLoc(i).isMacroID()) {
480 hasMacro = true;
481 break;
482 }
483 if (!hasMacro)
484 S.Diag(Element->getLocStart(),
485 diag::warn_concatenated_nsarray_literal)
486 << Element->getType();
487 }
488 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000489 }
490
Ted Kremeneke65b0862012-03-06 20:05:56 +0000491 // Make sure that the element has the type that the container factory
492 // function expects.
493 return S.PerformCopyInitialization(
494 InitializedEntity::InitializeParameter(S.Context, T,
495 /*Consumed=*/false),
496 Element->getLocStart(), Element);
497}
498
Patrick Beard0caa3942012-04-19 00:25:12 +0000499ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
500 if (ValueExpr->isTypeDependent()) {
501 ObjCBoxedExpr *BoxedExpr =
Craig Topperc3ec1492014-05-26 06:22:03 +0000502 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000503 return BoxedExpr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000504 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000505 ObjCMethodDecl *BoxingMethod = nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000506 QualType BoxedType;
507 // Convert the expression to an RValue, so we can check for pointer types...
508 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
509 if (RValue.isInvalid()) {
510 return ExprError();
511 }
Alex Denisovb7d85632015-07-24 05:09:40 +0000512 SourceLocation Loc = SR.getBegin();
Patrick Beard0caa3942012-04-19 00:25:12 +0000513 ValueExpr = RValue.get();
Patrick Beard2565c592012-05-01 21:47:19 +0000514 QualType ValueType(ValueExpr->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +0000515 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
516 QualType PointeeType = PT->getPointeeType();
517 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
518
519 if (!NSStringDecl) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000520 NSStringDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
521 Sema::LK_String);
Patrick Beard0caa3942012-04-19 00:25:12 +0000522 if (!NSStringDecl) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000523 return ExprError();
524 }
Jordy Roseaca01f92012-05-12 17:32:52 +0000525 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
526 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000527 }
528
529 if (!StringWithUTF8StringMethod) {
530 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
531 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
532
533 // Look for the appropriate method within NSString.
Jordy Rose08e500c2012-05-12 17:32:44 +0000534 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
535 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000536 // Debugger needs to work even if NSString hasn't been defined.
Craig Topperc3ec1492014-05-26 06:22:03 +0000537 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000538 ObjCMethodDecl *M = ObjCMethodDecl::Create(
539 Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
540 NSStringPointer, ReturnTInfo, NSStringDecl,
541 /*isInstance=*/false, /*isVariadic=*/false,
542 /*isPropertyAccessor=*/false,
543 /*isImplicitlyDeclared=*/true,
544 /*isDefined=*/false, ObjCMethodDecl::Required,
545 /*HasRelatedResultType=*/false);
Jordy Roseaca01f92012-05-12 17:32:52 +0000546 QualType ConstCharType = Context.CharTy.withConst();
Patrick Beard0caa3942012-04-19 00:25:12 +0000547 ParmVarDecl *value =
548 ParmVarDecl::Create(Context, M,
549 SourceLocation(), SourceLocation(),
550 &Context.Idents.get("value"),
Jordy Roseaca01f92012-05-12 17:32:52 +0000551 Context.getPointerType(ConstCharType),
Craig Topperc3ec1492014-05-26 06:22:03 +0000552 /*TInfo=*/nullptr,
553 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000554 M->setMethodParams(Context, value, None);
Jordy Rose08e500c2012-05-12 17:32:44 +0000555 BoxingMethod = M;
Patrick Beard0caa3942012-04-19 00:25:12 +0000556 }
Jordy Rose890f4572012-05-12 15:53:41 +0000557
Alex Denisovb7d85632015-07-24 05:09:40 +0000558 if (!validateBoxingMethod(*this, Loc, NSStringDecl,
Jordy Rose08e500c2012-05-12 17:32:44 +0000559 stringWithUTF8String, BoxingMethod))
560 return ExprError();
561
562 StringWithUTF8StringMethod = BoxingMethod;
Patrick Beard0caa3942012-04-19 00:25:12 +0000563 }
564
565 BoxingMethod = StringWithUTF8StringMethod;
566 BoxedType = NSStringPointer;
567 }
Patrick Beard2565c592012-05-01 21:47:19 +0000568 } else if (ValueType->isBuiltinType()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000569 // The other types we support are numeric, char and BOOL/bool. We could also
570 // provide limited support for structure types, such as NSRange, NSRect, and
571 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
572 // for more details.
573
574 // Check for a top-level character literal.
575 if (const CharacterLiteral *Char =
576 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
577 // In C, character literals have type 'int'. That's not the type we want
578 // to use to determine the Objective-c literal kind.
579 switch (Char->getKind()) {
580 case CharacterLiteral::Ascii:
Aaron Ballman9a17c852016-01-07 20:59:26 +0000581 case CharacterLiteral::UTF8:
Patrick Beard0caa3942012-04-19 00:25:12 +0000582 ValueType = Context.CharTy;
583 break;
584
585 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000586 ValueType = Context.getWideCharType();
Patrick Beard0caa3942012-04-19 00:25:12 +0000587 break;
588
589 case CharacterLiteral::UTF16:
590 ValueType = Context.Char16Ty;
591 break;
592
593 case CharacterLiteral::UTF32:
594 ValueType = Context.Char32Ty;
595 break;
596 }
597 }
Fariborz Jahanian5d64abb2014-06-18 20:49:02 +0000598 CheckForIntOverflow(ValueExpr);
Patrick Beard0caa3942012-04-19 00:25:12 +0000599 // FIXME: Do I need to do anything special with BoolTy expressions?
600
601 // Look for the appropriate method within NSNumber.
Alex Denisovb7d85632015-07-24 05:09:40 +0000602 BoxingMethod = getNSNumberFactoryMethod(*this, Loc, ValueType);
Patrick Beard0caa3942012-04-19 00:25:12 +0000603 BoxedType = NSNumberPointer;
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000604 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
605 if (!ET->getDecl()->isComplete()) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000606 Diag(Loc, diag::err_objc_incomplete_boxed_expression_type)
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000607 << ValueType << ValueExpr->getSourceRange();
608 return ExprError();
609 }
610
Alex Denisovb7d85632015-07-24 05:09:40 +0000611 BoxingMethod = getNSNumberFactoryMethod(*this, Loc,
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000612 ET->getDecl()->getIntegerType());
613 BoxedType = NSNumberPointer;
Alex Denisovfde64952015-06-26 05:28:36 +0000614 } else if (ValueType->isObjCBoxableRecordType()) {
615 // Support for structure types, that marked as objc_boxable
616 // struct __attribute__((objc_boxable)) s { ... };
617
618 // Look up the NSValue class, if we haven't done so already. It's cached
619 // in the Sema instance.
620 if (!NSValueDecl) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000621 NSValueDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
622 Sema::LK_Boxed);
Alex Denisovfde64952015-06-26 05:28:36 +0000623 if (!NSValueDecl) {
Alex Denisovfde64952015-06-26 05:28:36 +0000624 return ExprError();
625 }
Alex Denisovb7d85632015-07-24 05:09:40 +0000626
Alex Denisovfde64952015-06-26 05:28:36 +0000627 // generate the pointer to NSValue type.
628 QualType NSValueObject = Context.getObjCInterfaceType(NSValueDecl);
629 NSValuePointer = Context.getObjCObjectPointerType(NSValueObject);
630 }
631
632 if (!ValueWithBytesObjCTypeMethod) {
633 IdentifierInfo *II[] = {
634 &Context.Idents.get("valueWithBytes"),
635 &Context.Idents.get("objCType")
636 };
637 Selector ValueWithBytesObjCType = Context.Selectors.getSelector(2, II);
638
639 // Look for the appropriate method within NSValue.
640 BoxingMethod = NSValueDecl->lookupClassMethod(ValueWithBytesObjCType);
641 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
642 // Debugger needs to work even if NSValue hasn't been defined.
643 TypeSourceInfo *ReturnTInfo = nullptr;
644 ObjCMethodDecl *M = ObjCMethodDecl::Create(
645 Context,
646 SourceLocation(),
647 SourceLocation(),
648 ValueWithBytesObjCType,
649 NSValuePointer,
650 ReturnTInfo,
651 NSValueDecl,
652 /*isInstance=*/false,
653 /*isVariadic=*/false,
654 /*isPropertyAccessor=*/false,
655 /*isImplicitlyDeclared=*/true,
656 /*isDefined=*/false,
657 ObjCMethodDecl::Required,
658 /*HasRelatedResultType=*/false);
659
660 SmallVector<ParmVarDecl *, 2> Params;
661
662 ParmVarDecl *bytes =
663 ParmVarDecl::Create(Context, M,
664 SourceLocation(), SourceLocation(),
665 &Context.Idents.get("bytes"),
666 Context.VoidPtrTy.withConst(),
667 /*TInfo=*/nullptr,
668 SC_None, nullptr);
669 Params.push_back(bytes);
670
671 QualType ConstCharType = Context.CharTy.withConst();
672 ParmVarDecl *type =
673 ParmVarDecl::Create(Context, M,
674 SourceLocation(), SourceLocation(),
675 &Context.Idents.get("type"),
676 Context.getPointerType(ConstCharType),
677 /*TInfo=*/nullptr,
678 SC_None, nullptr);
679 Params.push_back(type);
680
681 M->setMethodParams(Context, Params, None);
682 BoxingMethod = M;
683 }
684
Alex Denisovb7d85632015-07-24 05:09:40 +0000685 if (!validateBoxingMethod(*this, Loc, NSValueDecl,
Alex Denisovfde64952015-06-26 05:28:36 +0000686 ValueWithBytesObjCType, BoxingMethod))
687 return ExprError();
688
689 ValueWithBytesObjCTypeMethod = BoxingMethod;
690 }
691
692 if (!ValueType.isTriviallyCopyableType(Context)) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000693 Diag(Loc, diag::err_objc_non_trivially_copyable_boxed_expression_type)
Alex Denisovfde64952015-06-26 05:28:36 +0000694 << ValueType << ValueExpr->getSourceRange();
695 return ExprError();
696 }
697
698 BoxingMethod = ValueWithBytesObjCTypeMethod;
699 BoxedType = NSValuePointer;
Patrick Beard0caa3942012-04-19 00:25:12 +0000700 }
701
702 if (!BoxingMethod) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000703 Diag(Loc, diag::err_objc_illegal_boxed_expression_type)
Patrick Beard0caa3942012-04-19 00:25:12 +0000704 << ValueType << ValueExpr->getSourceRange();
705 return ExprError();
706 }
707
Alex Denisovb7d85632015-07-24 05:09:40 +0000708 DiagnoseUseOfDecl(BoxingMethod, Loc);
Alex Denisovfde64952015-06-26 05:28:36 +0000709
710 ExprResult ConvertedValueExpr;
711 if (ValueType->isObjCBoxableRecordType()) {
712 InitializedEntity IE = InitializedEntity::InitializeTemporary(ValueType);
713 ConvertedValueExpr = PerformCopyInitialization(IE, ValueExpr->getExprLoc(),
714 ValueExpr);
715 } else {
716 // Convert the expression to the type that the parameter requires.
717 ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
718 InitializedEntity IE = InitializedEntity::InitializeParameter(Context,
719 ParamDecl);
720 ConvertedValueExpr = PerformCopyInitialization(IE, SourceLocation(),
721 ValueExpr);
722 }
723
Patrick Beard0caa3942012-04-19 00:25:12 +0000724 if (ConvertedValueExpr.isInvalid())
725 return ExprError();
726 ValueExpr = ConvertedValueExpr.get();
727
728 ObjCBoxedExpr *BoxedExpr =
729 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
730 BoxingMethod, SR);
731 return MaybeBindToTemporary(BoxedExpr);
732}
733
John McCallf2538342012-07-31 05:14:30 +0000734/// Build an ObjC subscript pseudo-object expression, given that
735/// that's supported by the runtime.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000736ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
737 Expr *IndexExpr,
738 ObjCMethodDecl *getterMethod,
739 ObjCMethodDecl *setterMethod) {
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +0000740 assert(!LangOpts.isSubscriptPointerArithmetic());
John McCall5fb5df92012-06-20 06:18:46 +0000741
John McCallf2538342012-07-31 05:14:30 +0000742 // We can't get dependent types here; our callers should have
743 // filtered them out.
744 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
745 "base or index cannot have dependent type here");
746
747 // Filter out placeholders in the index. In theory, overloads could
748 // be preserved here, although that might not actually work correctly.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000749 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
750 if (Result.isInvalid())
751 return ExprError();
752 IndexExpr = Result.get();
753
John McCallf2538342012-07-31 05:14:30 +0000754 // Perform lvalue-to-rvalue conversion on the base.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000755 Result = DefaultLvalueConversion(BaseExpr);
756 if (Result.isInvalid())
757 return ExprError();
758 BaseExpr = Result.get();
John McCallf2538342012-07-31 05:14:30 +0000759
760 // Build the pseudo-object expression.
James Y Knight6c2f06b2015-12-31 04:43:19 +0000761 return new (Context) ObjCSubscriptRefExpr(
762 BaseExpr, IndexExpr, Context.PseudoObjectTy, VK_LValue, OK_ObjCSubscript,
763 getterMethod, setterMethod, RB);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000764}
765
766ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000767 SourceLocation Loc = SR.getBegin();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000768
Alex Denisovb7d85632015-07-24 05:09:40 +0000769 if (!NSArrayDecl) {
770 NSArrayDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
771 Sema::LK_Array);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000772 if (!NSArrayDecl) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000773 return ExprError();
774 }
775 }
Alex Denisovb7d85632015-07-24 05:09:40 +0000776
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000777 // Find the arrayWithObjects:count: method, if we haven't done so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000778 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000779 if (!ArrayWithObjectsMethod) {
780 Selector
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000781 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
782 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000783 if (!Method && getLangOpts().DebuggerObjCLiteral) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000784 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000785 Method = ObjCMethodDecl::Create(
786 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000787 Context.getTranslationUnitDecl(), false /*Instance*/,
Alp Toker314cc812014-01-25 16:55:45 +0000788 false /*isVariadic*/,
789 /*isPropertyAccessor=*/false,
790 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
791 ObjCMethodDecl::Required, false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000792 SmallVector<ParmVarDecl *, 2> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000793 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000794 SourceLocation(),
795 SourceLocation(),
796 &Context.Idents.get("objects"),
797 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000798 /*TInfo=*/nullptr,
799 SC_None, nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000800 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000801 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000802 SourceLocation(),
803 SourceLocation(),
804 &Context.Idents.get("cnt"),
805 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000806 /*TInfo=*/nullptr, SC_None,
807 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000808 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000809 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000810 }
811
Alex Denisovb7d85632015-07-24 05:09:40 +0000812 if (!validateBoxingMethod(*this, Loc, NSArrayDecl, Sel, Method))
Ted Kremeneke65b0862012-03-06 20:05:56 +0000813 return ExprError();
Jordy Rose08e500c2012-05-12 17:32:44 +0000814
Jordy Rose4af44872012-05-12 17:32:56 +0000815 // Dig out the type that all elements should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000816 QualType T = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000817 const PointerType *PtrT = T->getAs<PointerType>();
818 if (!PtrT ||
819 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
820 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
821 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000822 Diag(Method->parameters()[0]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000823 diag::note_objc_literal_method_param)
824 << 0 << T
825 << Context.getPointerType(IdT.withConst());
826 return ExprError();
827 }
828
829 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000830 if (!Method->parameters()[1]->getType()->isIntegerType()) {
Jordy Rose4af44872012-05-12 17:32:56 +0000831 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
832 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000833 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000834 diag::note_objc_literal_method_param)
835 << 1
Alp Toker03376dc2014-07-07 09:02:20 +0000836 << Method->parameters()[1]->getType()
Jordy Rose4af44872012-05-12 17:32:56 +0000837 << "integral";
838 return ExprError();
839 }
840
841 // We've found a good +arrayWithObjects:count: method. Save it!
Jordy Rose08e500c2012-05-12 17:32:44 +0000842 ArrayWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000843 }
844
Alp Toker03376dc2014-07-07 09:02:20 +0000845 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000846 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000847
848 // Check that each of the elements provided is valid in a collection literal,
849 // performing conversions as necessary.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000850 Expr **ElementsBuffer = Elements.data();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000851 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
852 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
853 ElementsBuffer[I],
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000854 RequiredType, true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000855 if (Converted.isInvalid())
856 return ExprError();
857
858 ElementsBuffer[I] = Converted.get();
859 }
860
861 QualType Ty
862 = Context.getObjCObjectPointerType(
863 Context.getObjCInterfaceType(NSArrayDecl));
864
865 return MaybeBindToTemporary(
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000866 ObjCArrayLiteral::Create(Context, Elements, Ty,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000867 ArrayWithObjectsMethod, SR));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000868}
869
Craig Topperd4336e02015-12-24 23:58:15 +0000870ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
871 MutableArrayRef<ObjCDictionaryElement> Elements) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000872 SourceLocation Loc = SR.getBegin();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000873
Alex Denisovb7d85632015-07-24 05:09:40 +0000874 if (!NSDictionaryDecl) {
875 NSDictionaryDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
876 Sema::LK_Dictionary);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000877 if (!NSDictionaryDecl) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000878 return ExprError();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000879 }
880 }
Alex Denisovb7d85632015-07-24 05:09:40 +0000881
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000882 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
883 // so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000884 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000885 if (!DictionaryWithObjectsMethod) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000886 Selector Sel = NSAPIObj->getNSDictionarySelector(
887 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
888 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000889 if (!Method && getLangOpts().DebuggerObjCLiteral) {
890 Method = ObjCMethodDecl::Create(Context,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000891 SourceLocation(), SourceLocation(), Sel,
892 IdT,
Craig Topperc3ec1492014-05-26 06:22:03 +0000893 nullptr /*TypeSourceInfo */,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000894 Context.getTranslationUnitDecl(),
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000895 false /*Instance*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000896 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000897 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
898 ObjCMethodDecl::Required,
899 false);
900 SmallVector<ParmVarDecl *, 3> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000901 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000902 SourceLocation(),
903 SourceLocation(),
904 &Context.Idents.get("objects"),
905 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000906 /*TInfo=*/nullptr, SC_None,
907 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000908 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000909 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000910 SourceLocation(),
911 SourceLocation(),
912 &Context.Idents.get("keys"),
913 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000914 /*TInfo=*/nullptr, SC_None,
915 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000916 Params.push_back(keys);
Jordy Rose08e500c2012-05-12 17:32:44 +0000917 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000918 SourceLocation(),
919 SourceLocation(),
920 &Context.Idents.get("cnt"),
921 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000922 /*TInfo=*/nullptr, SC_None,
923 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000924 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000925 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000926 }
927
Jordy Rose08e500c2012-05-12 17:32:44 +0000928 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
929 Method))
930 return ExprError();
931
Jordy Rose4af44872012-05-12 17:32:56 +0000932 // Dig out the type that all values should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000933 QualType ValueT = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000934 const PointerType *PtrValue = ValueT->getAs<PointerType>();
935 if (!PtrValue ||
936 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000937 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
Jordy Rose4af44872012-05-12 17:32:56 +0000938 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000939 Diag(Method->parameters()[0]->getLocation(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000940 diag::note_objc_literal_method_param)
Jordy Rose4af44872012-05-12 17:32:56 +0000941 << 0 << ValueT
Ted Kremeneke65b0862012-03-06 20:05:56 +0000942 << Context.getPointerType(IdT.withConst());
943 return ExprError();
944 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000945
Jordy Rose4af44872012-05-12 17:32:56 +0000946 // Dig out the type that all keys should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000947 QualType KeyT = Method->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000948 const PointerType *PtrKey = KeyT->getAs<PointerType>();
949 if (!PtrKey ||
950 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
951 IdT)) {
952 bool err = true;
953 if (PtrKey) {
954 if (QIDNSCopying.isNull()) {
955 // key argument of selector is id<NSCopying>?
956 if (ObjCProtocolDecl *NSCopyingPDecl =
957 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
958 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
959 QIDNSCopying =
Douglas Gregore9d95f12015-07-07 03:57:35 +0000960 Context.getObjCObjectType(Context.ObjCBuiltinIdTy, { },
961 llvm::makeArrayRef(
962 (ObjCProtocolDecl**) PQ,
Douglas Gregorab209d82015-07-07 03:58:42 +0000963 1),
964 false);
Jordy Rose4af44872012-05-12 17:32:56 +0000965 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
966 }
967 }
968 if (!QIDNSCopying.isNull())
969 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
970 QIDNSCopying);
971 }
972
973 if (err) {
974 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
975 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000976 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000977 diag::note_objc_literal_method_param)
978 << 1 << KeyT
979 << Context.getPointerType(IdT.withConst());
980 return ExprError();
981 }
982 }
983
984 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000985 QualType CountType = Method->parameters()[2]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000986 if (!CountType->isIntegerType()) {
987 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
988 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000989 Diag(Method->parameters()[2]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000990 diag::note_objc_literal_method_param)
991 << 2 << CountType
992 << "integral";
993 return ExprError();
994 }
995
996 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
997 DictionaryWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000998 }
999
Alp Toker03376dc2014-07-07 09:02:20 +00001000 QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +00001001 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
Alp Toker03376dc2014-07-07 09:02:20 +00001002 QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +00001003 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
1004
Ted Kremeneke65b0862012-03-06 20:05:56 +00001005 // Check that each of the keys and values provided is valid in a collection
1006 // literal, performing conversions as necessary.
1007 bool HasPackExpansions = false;
Craig Topperd4336e02015-12-24 23:58:15 +00001008 for (ObjCDictionaryElement &Element : Elements) {
Ted Kremeneke65b0862012-03-06 20:05:56 +00001009 // Check the key.
Craig Topperd4336e02015-12-24 23:58:15 +00001010 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Element.Key,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001011 KeyT);
1012 if (Key.isInvalid())
1013 return ExprError();
1014
1015 // Check the value.
1016 ExprResult Value
Craig Topperd4336e02015-12-24 23:58:15 +00001017 = CheckObjCCollectionLiteralElement(*this, Element.Value, ValueT);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001018 if (Value.isInvalid())
1019 return ExprError();
1020
Craig Topperd4336e02015-12-24 23:58:15 +00001021 Element.Key = Key.get();
1022 Element.Value = Value.get();
Ted Kremeneke65b0862012-03-06 20:05:56 +00001023
Craig Topperd4336e02015-12-24 23:58:15 +00001024 if (Element.EllipsisLoc.isInvalid())
Ted Kremeneke65b0862012-03-06 20:05:56 +00001025 continue;
1026
Craig Topperd4336e02015-12-24 23:58:15 +00001027 if (!Element.Key->containsUnexpandedParameterPack() &&
1028 !Element.Value->containsUnexpandedParameterPack()) {
1029 Diag(Element.EllipsisLoc,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001030 diag::err_pack_expansion_without_parameter_packs)
Craig Topperd4336e02015-12-24 23:58:15 +00001031 << SourceRange(Element.Key->getLocStart(),
1032 Element.Value->getLocEnd());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001033 return ExprError();
1034 }
1035
1036 HasPackExpansions = true;
1037 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001038
1039 QualType Ty
1040 = Context.getObjCObjectPointerType(
Robert Wilhelm88e02492013-08-19 07:57:02 +00001041 Context.getObjCInterfaceType(NSDictionaryDecl));
1042 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
Craig Topperd4336e02015-12-24 23:58:15 +00001043 Context, Elements, 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,
Craig Topper07fa1762015-11-15 02:31:46 +00001092 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;
Richard Smith01d96982016-12-02 23:00:28 +00001115 S.Diag(AtLoc, diag::warn_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 ||
Richard Smith01d96982016-12-02 23:00:28 +00001134 S.Diags.isIgnored(diag::warn_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())
Douglas Gregore83b9562015-07-07 03:57:53 +00001282 return Method->getSendResultType(ReceiverType);
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.
Douglas Gregore83b9562015-07-07 03:57:53 +00001290 if (auto nullability = Method->getSendResultType(ReceiverType)
1291 ->getNullability(Context)){
Douglas Gregor813a0662015-06-19 18:14:38 +00001292 // Strip off any outer nullability sugar from the provided type.
1293 (void)AttributedType::stripOuterNullability(type);
1294
1295 // Form a new attributed type using the method result type's nullability.
1296 return Context.getAttributedType(
1297 AttributedType::getNullabilityAttrKind(*nullability),
1298 type,
1299 type);
1300 }
1301
1302 return type;
1303 };
1304
Douglas Gregor33823722011-06-11 01:09:30 +00001305 // If a method has a related return type:
1306 // - if the method found is an instance method, but the message send
1307 // was a class message send, T is the declared return type of the method
1308 // found
1309 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregore83b9562015-07-07 03:57:53 +00001310 return stripObjCInstanceType(Context,
1311 Method->getSendResultType(ReceiverType));
Douglas Gregor813a0662015-06-19 18:14:38 +00001312
1313 // - if the receiver is super, T is a pointer to the class of the
Douglas Gregor33823722011-06-11 01:09:30 +00001314 // enclosing method definition
1315 if (isSuperMessage) {
Douglas Gregor813a0662015-06-19 18:14:38 +00001316 if (ObjCMethodDecl *CurMethod = S.getCurMethodDecl())
1317 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) {
1318 return transferNullability(
1319 Context.getObjCObjectPointerType(
1320 Context.getObjCInterfaceType(Class)));
1321 }
Douglas Gregor33823722011-06-11 01:09:30 +00001322 }
Douglas Gregor813a0662015-06-19 18:14:38 +00001323
Douglas Gregor33823722011-06-11 01:09:30 +00001324 // - if the receiver is the name of a class U, T is a pointer to U
Douglas Gregore83b9562015-07-07 03:57:53 +00001325 if (ReceiverType->getAsObjCInterfaceType())
Douglas Gregor813a0662015-06-19 18:14:38 +00001326 return transferNullability(Context.getObjCObjectPointerType(ReceiverType));
1327 // - if the receiver is of type Class or qualified Class type,
Douglas Gregor33823722011-06-11 01:09:30 +00001328 // T is the declared return type of the method.
1329 if (ReceiverType->isObjCClassType() ||
1330 ReceiverType->isObjCQualifiedClassType())
Douglas Gregore83b9562015-07-07 03:57:53 +00001331 return stripObjCInstanceType(Context,
1332 Method->getSendResultType(ReceiverType));
Douglas Gregor813a0662015-06-19 18:14:38 +00001333
Douglas Gregor33823722011-06-11 01:09:30 +00001334 // - if the receiver is id, qualified id, Class, or qualified Class, T
1335 // is the receiver type, otherwise
1336 // - T is the type of the receiver expression.
Douglas Gregor813a0662015-06-19 18:14:38 +00001337 return transferNullability(ReceiverType);
1338}
1339
1340QualType Sema::getMessageSendResultType(QualType ReceiverType,
1341 ObjCMethodDecl *Method,
1342 bool isClassMessage,
1343 bool isSuperMessage) {
1344 // Produce the result type.
1345 QualType resultType = getBaseMessageSendResultType(*this, ReceiverType,
1346 Method,
1347 isClassMessage,
1348 isSuperMessage);
1349
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001350 // If this is a class message, ignore the nullability of the receiver.
1351 if (isClassMessage)
1352 return resultType;
1353
Douglas Gregor813a0662015-06-19 18:14:38 +00001354 // Map the nullability of the result into a table index.
1355 unsigned receiverNullabilityIdx = 0;
1356 if (auto nullability = ReceiverType->getNullability(Context))
1357 receiverNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1358
1359 unsigned resultNullabilityIdx = 0;
1360 if (auto nullability = resultType->getNullability(Context))
1361 resultNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1362
1363 // The table of nullability mappings, indexed by the receiver's nullability
1364 // and then the result type's nullability.
1365 static const uint8_t None = 0;
1366 static const uint8_t NonNull = 1;
1367 static const uint8_t Nullable = 2;
1368 static const uint8_t Unspecified = 3;
1369 static const uint8_t nullabilityMap[4][4] = {
1370 // None NonNull Nullable Unspecified
1371 /* None */ { None, None, Nullable, None },
1372 /* NonNull */ { None, NonNull, Nullable, Unspecified },
1373 /* Nullable */ { Nullable, Nullable, Nullable, Nullable },
1374 /* Unspecified */ { None, Unspecified, Nullable, Unspecified }
1375 };
1376
1377 unsigned newResultNullabilityIdx
1378 = nullabilityMap[receiverNullabilityIdx][resultNullabilityIdx];
1379 if (newResultNullabilityIdx == resultNullabilityIdx)
1380 return resultType;
1381
1382 // Strip off the existing nullability. This removes as little type sugar as
1383 // possible.
1384 do {
1385 if (auto attributed = dyn_cast<AttributedType>(resultType.getTypePtr())) {
1386 resultType = attributed->getModifiedType();
1387 } else {
1388 resultType = resultType.getDesugaredType(Context);
1389 }
1390 } while (resultType->getNullability(Context));
1391
1392 // Add nullability back if needed.
1393 if (newResultNullabilityIdx > 0) {
1394 auto newNullability
1395 = static_cast<NullabilityKind>(newResultNullabilityIdx-1);
1396 return Context.getAttributedType(
1397 AttributedType::getNullabilityAttrKind(newNullability),
1398 resultType, resultType);
1399 }
1400
1401 return resultType;
Douglas Gregor33823722011-06-11 01:09:30 +00001402}
John McCall5f2d5562011-02-03 09:00:02 +00001403
John McCall5ec7e7d2013-03-19 07:04:25 +00001404/// Look for an ObjC method whose result type exactly matches the given type.
1405static const ObjCMethodDecl *
1406findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1407 QualType instancetype) {
Alp Toker314cc812014-01-25 16:55:45 +00001408 if (MD->getReturnType() == instancetype)
1409 return MD;
John McCall5ec7e7d2013-03-19 07:04:25 +00001410
1411 // For these purposes, a method in an @implementation overrides a
1412 // declaration in the @interface.
1413 if (const ObjCImplDecl *impl =
1414 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1415 const ObjCContainerDecl *iface;
1416 if (const ObjCCategoryImplDecl *catImpl =
1417 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1418 iface = catImpl->getCategoryDecl();
1419 } else {
1420 iface = impl->getClassInterface();
1421 }
1422
1423 const ObjCMethodDecl *ifaceMD =
1424 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1425 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1426 }
1427
1428 SmallVector<const ObjCMethodDecl *, 4> overrides;
1429 MD->getOverriddenMethods(overrides);
1430 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1431 if (const ObjCMethodDecl *result =
1432 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1433 return result;
1434 }
1435
Craig Topperc3ec1492014-05-26 06:22:03 +00001436 return nullptr;
John McCall5ec7e7d2013-03-19 07:04:25 +00001437}
1438
1439void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1440 // Only complain if we're in an ObjC method and the required return
1441 // type doesn't match the method's declared return type.
1442 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1443 if (!MD || !MD->hasRelatedResultType() ||
Alp Toker314cc812014-01-25 16:55:45 +00001444 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
John McCall5ec7e7d2013-03-19 07:04:25 +00001445 return;
1446
1447 // Look for a method overridden by this method which explicitly uses
1448 // 'instancetype'.
1449 if (const ObjCMethodDecl *overridden =
1450 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
Aaron Ballman41b10ac2014-08-01 13:20:09 +00001451 SourceRange range = overridden->getReturnTypeSourceRange();
1452 SourceLocation loc = range.getBegin();
John McCall5ec7e7d2013-03-19 07:04:25 +00001453 if (loc.isInvalid())
1454 loc = overridden->getLocation();
1455 Diag(loc, diag::note_related_result_type_explicit)
1456 << /*current method*/ 1 << range;
1457 return;
1458 }
1459
1460 // Otherwise, if we have an interesting method family, note that.
1461 // This should always trigger if the above didn't.
1462 if (ObjCMethodFamily family = MD->getMethodFamily())
1463 Diag(MD->getLocation(), diag::note_related_result_type_family)
1464 << /*current method*/ 1
1465 << family;
1466}
1467
Douglas Gregor33823722011-06-11 01:09:30 +00001468void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1469 E = E->IgnoreParenImpCasts();
1470 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1471 if (!MsgSend)
1472 return;
1473
1474 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1475 if (!Method)
1476 return;
1477
1478 if (!Method->hasRelatedResultType())
1479 return;
Alp Toker314cc812014-01-25 16:55:45 +00001480
1481 if (Context.hasSameUnqualifiedType(
1482 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
Douglas Gregor33823722011-06-11 01:09:30 +00001483 return;
Alp Toker314cc812014-01-25 16:55:45 +00001484
1485 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
Douglas Gregorbab8a962011-09-08 01:46:34 +00001486 Context.getObjCInstanceType()))
1487 return;
1488
Douglas Gregor33823722011-06-11 01:09:30 +00001489 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1490 << Method->isInstanceMethod() << Method->getSelector()
1491 << MsgSend->getType();
1492}
1493
1494bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001495 MultiExprArg Args,
1496 Selector Sel,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001497 ArrayRef<SourceLocation> SelectorLocs,
1498 ObjCMethodDecl *Method,
Douglas Gregor33823722011-06-11 01:09:30 +00001499 bool isClassMessage, bool isSuperMessage,
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001500 SourceLocation lbrac, SourceLocation rbrac,
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00001501 SourceRange RecRange,
John McCall7decc9e2010-11-18 06:31:45 +00001502 QualType &ReturnType, ExprValueKind &VK) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001503 SourceLocation SelLoc;
1504 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1505 SelLoc = SelectorLocs.front();
1506 else
1507 SelLoc = lbrac;
1508
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001509 if (!Method) {
Daniel Dunbar83876b42008-09-11 00:04:36 +00001510 // Apply default argument promotion as for (C99 6.5.2.2p6).
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001511 for (unsigned i = 0, e = Args.size(); i != e; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001512 if (Args[i]->isTypeDependent())
1513 continue;
1514
John McCallcc5788c2013-03-04 07:34:02 +00001515 ExprResult result;
1516 if (getLangOpts().DebuggerSupport) {
1517 QualType paramTy; // ignored
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001518 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
John McCallcc5788c2013-03-04 07:34:02 +00001519 } else {
1520 result = DefaultArgumentPromotion(Args[i]);
1521 }
1522 if (result.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001523 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001524 Args[i] = result.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001525 }
Daniel Dunbar83876b42008-09-11 00:04:36 +00001526
John McCall31168b02011-06-15 23:02:42 +00001527 unsigned DiagID;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001528 if (getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00001529 DiagID = diag::err_arc_method_not_found;
1530 else
1531 DiagID = isClassMessage ? diag::warn_class_method_not_found
1532 : diag::warn_inst_method_not_found;
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001533 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001534 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
Fariborz Jahanian06499232013-06-18 17:10:58 +00001535 if (OMD && !OMD->isInvalidDecl()) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001536 if (getLangOpts().ObjCAutoRefCount)
Richard Smithf8812672016-12-02 22:38:31 +00001537 DiagID = diag::err_method_not_found_with_typo;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001538 else
1539 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1540 : diag::warn_instance_method_not_found_with_typo;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001541 Selector MatchedSel = OMD->getSelector();
1542 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
Fariborz Jahanian5ab87502014-08-12 22:16:41 +00001543 if (MatchedSel.isUnarySelector())
1544 Diag(SelLoc, DiagID)
1545 << Sel<< isClassMessage << MatchedSel
1546 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1547 else
1548 Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001549 }
1550 else
1551 Diag(SelLoc, DiagID)
1552 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001553 SelectorLocs.back());
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001554 // Find the class to which we are sending this message.
1555 if (ReceiverType->isObjCObjectPointerType()) {
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00001556 if (ObjCInterfaceDecl *ThisClass =
1557 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()) {
1558 Diag(ThisClass->getLocation(), diag::note_receiver_class_declared);
1559 if (!RecRange.isInvalid())
1560 if (ThisClass->lookupClassMethod(Sel))
1561 Diag(RecRange.getBegin(),diag::note_receiver_expr_here)
1562 << FixItHint::CreateReplacement(RecRange,
1563 ThisClass->getNameAsString());
1564 }
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001565 }
1566 }
John McCall3f4138c2011-07-13 17:56:40 +00001567
1568 // In debuggers, we want to use __unknown_anytype for these
1569 // results so that clients can cast them.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001570 if (getLangOpts().DebuggerSupport) {
John McCall3f4138c2011-07-13 17:56:40 +00001571 ReturnType = Context.UnknownAnyTy;
1572 } else {
1573 ReturnType = Context.getObjCIdType();
1574 }
John McCall7decc9e2010-11-18 06:31:45 +00001575 VK = VK_RValue;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001576 return false;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001577 }
Mike Stump11289f42009-09-09 15:08:12 +00001578
Douglas Gregor33823722011-06-11 01:09:30 +00001579 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1580 isSuperMessage);
Alp Toker314cc812014-01-25 16:55:45 +00001581 VK = Expr::getValueKindForType(Method->getReturnType());
Mike Stump11289f42009-09-09 15:08:12 +00001582
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001583 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian60462092010-04-08 00:30:06 +00001584 // Method might have more arguments than selector indicates. This is due
1585 // to addition of c-style arguments in method.
1586 if (Method->param_size() > Sel.getNumArgs())
1587 NumNamedArgs = Method->param_size();
1588 // FIXME. This need be cleaned up.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001589 if (Args.size() < NumNamedArgs) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001590 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001591 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
Fariborz Jahanian60462092010-04-08 00:30:06 +00001592 return false;
1593 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001594
Douglas Gregore83b9562015-07-07 03:57:53 +00001595 // Compute the set of type arguments to be substituted into each parameter
1596 // type.
1597 Optional<ArrayRef<QualType>> typeArgs
1598 = ReceiverType->getObjCSubstitutions(Method->getDeclContext());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001599 bool IsError = false;
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001600 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001601 // We can't do any type-checking on a type-dependent argument.
1602 if (Args[i]->isTypeDependent())
1603 continue;
1604
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001605 Expr *argExpr = Args[i];
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001606
Alp Toker03376dc2014-07-07 09:02:20 +00001607 ParmVarDecl *param = Method->parameters()[i];
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001608 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump11289f42009-09-09 15:08:12 +00001609
John McCall4124c492011-10-17 18:40:02 +00001610 // Strip the unbridged-cast placeholder expression off unless it's
1611 // a consumed argument.
1612 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1613 !param->hasAttr<CFConsumedAttr>())
1614 argExpr = stripARCUnbridgedCast(argExpr);
1615
John McCallea0a39e2012-11-14 00:49:39 +00001616 // If the parameter is __unknown_anytype, infer its type
1617 // from the argument.
1618 if (param->getType() == Context.UnknownAnyTy) {
John McCallcc5788c2013-03-04 07:34:02 +00001619 QualType paramType;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001620 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
John McCallcc5788c2013-03-04 07:34:02 +00001621 if (argE.isInvalid()) {
John McCallea0a39e2012-11-14 00:49:39 +00001622 IsError = true;
John McCallcc5788c2013-03-04 07:34:02 +00001623 } else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001624 Args[i] = argE.get();
John McCallea0a39e2012-11-14 00:49:39 +00001625
John McCallcc5788c2013-03-04 07:34:02 +00001626 // Update the parameter type in-place.
1627 param->setType(paramType);
1628 }
1629 continue;
John McCallea0a39e2012-11-14 00:49:39 +00001630 }
1631
Douglas Gregore83b9562015-07-07 03:57:53 +00001632 QualType origParamType = param->getType();
1633 QualType paramType = param->getType();
1634 if (typeArgs)
1635 paramType = paramType.substObjCTypeArgs(
1636 Context,
1637 *typeArgs,
1638 ObjCSubstitutionContext::Parameter);
1639
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001640 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
Douglas Gregore83b9562015-07-07 03:57:53 +00001641 paramType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001642 diag::err_call_incomplete_argument, argExpr))
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001643 return true;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001644
Douglas Gregore83b9562015-07-07 03:57:53 +00001645 InitializedEntity Entity
1646 = InitializedEntity::InitializeParameter(Context, param, paramType);
Fariborz Jahaniana1db7df2014-07-31 17:39:50 +00001647 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001648 if (ArgE.isInvalid())
1649 IsError = true;
Douglas Gregore83b9562015-07-07 03:57:53 +00001650 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001651 Args[i] = ArgE.getAs<Expr>();
Douglas Gregore83b9562015-07-07 03:57:53 +00001652
1653 // If we are type-erasing a block to a block-compatible
1654 // Objective-C pointer type, we may need to extend the lifetime
1655 // of the block object.
1656 if (typeArgs && Args[i]->isRValue() && paramType->isBlockPointerType() &&
Bob Wilson7e9fd562015-10-02 01:05:29 +00001657 Args[i]->getType()->isBlockPointerType() &&
1658 origParamType->isObjCObjectPointerType()) {
Douglas Gregore83b9562015-07-07 03:57:53 +00001659 ExprResult arg = Args[i];
1660 maybeExtendBlockObject(arg);
1661 Args[i] = arg.get();
1662 }
1663 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001664 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001665
1666 // Promote additional arguments to variadic methods.
1667 if (Method->isVariadic()) {
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001668 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001669 if (Args[i]->isTypeDependent())
1670 continue;
1671
Jordy Roseaca01f92012-05-12 17:32:52 +00001672 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
Craig Topperc3ec1492014-05-26 06:22:03 +00001673 nullptr);
John Wiegley01296292011-04-08 18:41:53 +00001674 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001675 Args[i] = Arg.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001676 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001677 } else {
1678 // Check for extra arguments to non-variadic methods.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001679 if (Args.size() != NumNamedArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00001680 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001681 diag::err_typecheck_call_too_many_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001682 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001683 << Method->getSourceRange()
Chris Lattner3b054132008-11-19 05:08:23 +00001684 << SourceRange(Args[NumNamedArgs]->getLocStart(),
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001685 Args.back()->getLocEnd());
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001686 }
1687 }
1688
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001689 DiagnoseSentinelCalls(Method, SelLoc, Args);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001690
1691 // Do additional checkings on method.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001692 IsError |= CheckObjCMethodCall(
Craig Topper8c2a2a02014-08-30 16:55:39 +00001693 Method, SelLoc, makeArrayRef(Args.data(), Args.size()));
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001694
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001695 return IsError;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001696}
1697
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001698bool Sema::isSelfExpr(Expr *RExpr) {
Fariborz Jahanianb3b1e172011-03-27 19:53:47 +00001699 // 'self' is objc 'self' in an objc method only.
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001700 ObjCMethodDecl *Method =
1701 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1702 return isSelfExpr(RExpr, Method);
1703}
1704
1705bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
John McCallfe96e0b2011-11-06 09:01:30 +00001706 if (!method) return false;
1707
John McCall31168b02011-06-15 23:02:42 +00001708 receiver = receiver->IgnoreParenLValueCasts();
1709 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCallfe96e0b2011-11-06 09:01:30 +00001710 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregor486b74e2011-09-27 16:10:05 +00001711 return true;
1712 return false;
Steve Naroff3f49fee2009-03-04 15:11:40 +00001713}
1714
John McCall526ab472011-10-25 17:37:35 +00001715/// LookupMethodInType - Look up a method in an ObjCObjectType.
1716ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1717 bool isInstance) {
1718 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1719 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1720 // Look it up in the main interface (and categories, etc.)
1721 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1722 return method;
1723
1724 // Okay, look for "private" methods declared in any
1725 // @implementations we've seen.
Anna Zaksc77a3b12012-07-27 19:07:44 +00001726 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1727 return method;
John McCall526ab472011-10-25 17:37:35 +00001728 }
1729
1730 // Check qualifiers.
Aaron Ballman1683f7b2014-03-17 15:55:30 +00001731 for (const auto *I : objType->quals())
1732 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
John McCall526ab472011-10-25 17:37:35 +00001733 return method;
1734
Craig Topperc3ec1492014-05-26 06:22:03 +00001735 return nullptr;
John McCall526ab472011-10-25 17:37:35 +00001736}
1737
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001738/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1739/// list of a qualified objective pointer type.
1740ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1741 const ObjCObjectPointerType *OPT,
1742 bool Instance)
1743{
Craig Topperc3ec1492014-05-26 06:22:03 +00001744 ObjCMethodDecl *MD = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +00001745 for (const auto *PROTO : OPT->quals()) {
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001746 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1747 return MD;
1748 }
1749 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001750 return nullptr;
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001751}
1752
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001753/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1754/// objective C interface. This is a property reference expression.
John McCalldadc5752010-08-24 06:29:42 +00001755ExprResult Sema::
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001756HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001757 Expr *BaseExpr, SourceLocation OpLoc,
1758 DeclarationName MemberName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001759 SourceLocation MemberLoc,
1760 SourceLocation SuperLoc, QualType SuperType,
1761 bool Super) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001762 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1763 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00001764
Benjamin Kramer365082d2012-05-19 16:34:46 +00001765 if (!MemberName.isIdentifier()) {
Douglas Gregord6459312011-04-20 18:19:55 +00001766 Diag(MemberLoc, diag::err_invalid_property_name)
1767 << MemberName << QualType(OPT, 0);
1768 return ExprError();
1769 }
Benjamin Kramer365082d2012-05-19 16:34:46 +00001770
1771 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregord6459312011-04-20 18:19:55 +00001772
Douglas Gregor4123a862011-11-14 22:10:01 +00001773 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1774 : BaseExpr->getSourceRange();
1775 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001776 diag::err_property_not_found_forward_class,
1777 MemberName, BaseRange))
Fariborz Jahanian7cabbe02010-12-16 00:56:28 +00001778 return ExprError();
Douglas Gregoracf4fd32015-11-03 01:15:46 +00001779
Manman Ren5b786402016-01-28 18:49:28 +00001780 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(
1781 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001782 // Check whether we can reference this property.
1783 if (DiagnoseUseOfDecl(PD, MemberLoc))
1784 return ExprError();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001785 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001786 return new (Context)
1787 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1788 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001789 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001790 return new (Context)
1791 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1792 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001793 }
1794 // Check protocols on qualified interfaces.
Aaron Ballman83731462014-03-17 16:14:00 +00001795 for (const auto *I : OPT->quals())
Manman Ren5b786402016-01-28 18:49:28 +00001796 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
1797 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001798 // Check whether we can reference this property.
1799 if (DiagnoseUseOfDecl(PD, MemberLoc))
1800 return ExprError();
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001801
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001802 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001803 return new (Context) ObjCPropertyRefExpr(
1804 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
1805 SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001806 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001807 return new (Context)
1808 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1809 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001810 }
1811 // If that failed, look for an "implicit" property by seeing if the nullary
1812 // selector is implemented.
1813
1814 // FIXME: The logic for looking up nullary and unary selectors should be
1815 // shared with the code in ActOnInstanceMessage.
1816
1817 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1818 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001819
Manman Ren2b2b1a92016-06-28 23:01:49 +00001820 // May be found in property's qualified list.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001821 if (!Getter)
1822 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001823
1824 // If this reference is in an @implementation, check for 'private' methods.
1825 if (!Getter)
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001826 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001827
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001828 if (Getter) {
1829 // Check if we can reference this property.
1830 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1831 return ExprError();
1832 }
1833 // If we found a getter then this may be a valid dot-reference, we
1834 // will look for the matching setter, in case it is needed.
1835 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001836 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1837 PP.getSelectorTable(), Member);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001838 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001839
Manman Ren2b2b1a92016-06-28 23:01:49 +00001840 // May be found in property's qualified list.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001841 if (!Setter)
1842 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1843
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001844 if (!Setter) {
1845 // If this reference is in an @implementation, also check for 'private'
1846 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001847 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001848 }
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001849
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001850 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1851 return ExprError();
1852
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001853 // Special warning if member name used in a property-dot for a setter accessor
1854 // does not use a property with same name; e.g. obj.X = ... for a property with
1855 // name 'x'.
Manman Ren5b786402016-01-28 18:49:28 +00001856 if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor() &&
1857 !IFace->FindPropertyDeclaration(
1858 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Fariborz Jahanian4eda2c02014-08-15 17:39:00 +00001859 if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) {
1860 // Do not warn if user is using property-dot syntax to make call to
1861 // user named setter.
1862 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter))
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001863 Diag(MemberLoc,
1864 diag::warn_property_access_suggest)
1865 << MemberName << QualType(OPT, 0) << PDecl->getName()
1866 << FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
Fariborz Jahanian4eda2c02014-08-15 17:39:00 +00001867 }
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001868 }
1869
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001870 if (Getter || Setter) {
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001871 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001872 return new (Context)
1873 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1874 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001875 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001876 return new (Context)
1877 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1878 OK_ObjCProperty, MemberLoc, BaseExpr);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001879
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001880 }
1881
1882 // Attempt to correct for typos in property names.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001883 if (TypoCorrection Corrected =
1884 CorrectTypo(DeclarationNameInfo(MemberName, MemberLoc),
1885 LookupOrdinaryName, nullptr, nullptr,
1886 llvm::make_unique<DeclFilterCCC<ObjCPropertyDecl>>(),
1887 CTK_ErrorRecovery, IFace, false, OPT)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001888 DeclarationName TypoResult = Corrected.getCorrection();
Manman Ren2b2b1a92016-06-28 23:01:49 +00001889 if (TypoResult.isIdentifier() &&
1890 TypoResult.getAsIdentifierInfo() == Member) {
1891 // There is no need to try the correction if it is the same.
1892 NamedDecl *ChosenDecl =
1893 Corrected.isKeyword() ? nullptr : Corrected.getFoundDecl();
1894 if (ChosenDecl && isa<ObjCPropertyDecl>(ChosenDecl))
1895 if (cast<ObjCPropertyDecl>(ChosenDecl)->isClassProperty()) {
1896 // This is a class property, we should not use the instance to
1897 // access it.
1898 Diag(MemberLoc, diag::err_class_property_found) << MemberName
1899 << OPT->getInterfaceDecl()->getName()
1900 << FixItHint::CreateReplacement(BaseExpr->getSourceRange(),
1901 OPT->getInterfaceDecl()->getName());
1902 return ExprError();
1903 }
1904 } else {
1905 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1906 << MemberName << QualType(OPT, 0));
1907 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1908 TypoResult, MemberLoc,
1909 SuperLoc, SuperType, Super);
1910 }
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001911 }
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001912 ObjCInterfaceDecl *ClassDeclared;
1913 if (ObjCIvarDecl *Ivar =
1914 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1915 QualType T = Ivar->getType();
1916 if (const ObjCObjectPointerType * OBJPT =
1917 T->getAsObjCInterfacePointerType()) {
Douglas Gregor4123a862011-11-14 22:10:01 +00001918 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001919 diag::err_property_not_as_forward_class,
1920 MemberName, BaseExpr))
Douglas Gregor4123a862011-11-14 22:10:01 +00001921 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001922 }
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001923 Diag(MemberLoc,
1924 diag::err_ivar_access_using_property_syntax_suggest)
1925 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1926 << FixItHint::CreateReplacement(OpLoc, "->");
1927 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001928 }
Chris Lattner90c58fa2010-04-11 07:51:10 +00001929
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001930 Diag(MemberLoc, diag::err_property_not_found)
1931 << MemberName << QualType(OPT, 0);
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001932 if (Setter)
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001933 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001934 << MemberName << BaseExpr->getSourceRange();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001935 return ExprError();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001936}
1937
John McCalldadc5752010-08-24 06:29:42 +00001938ExprResult Sema::
Chris Lattnera36ec422010-04-11 08:28:14 +00001939ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1940 IdentifierInfo &propertyName,
1941 SourceLocation receiverNameLoc,
1942 SourceLocation propertyNameLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00001943
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001944 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001945 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1946 receiverNameLoc);
Douglas Gregor33823722011-06-11 01:09:30 +00001947
Douglas Gregore83b9562015-07-07 03:57:53 +00001948 QualType SuperType;
Craig Topperc3ec1492014-05-26 06:22:03 +00001949 if (!IFace) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001950 // If the "receiver" is 'super' in a method, handle it as an expression-like
1951 // property reference.
John McCall5f2d5562011-02-03 09:00:02 +00001952 if (receiverNamePtr->isStr("super")) {
Eli Friedman24af8502012-02-03 22:47:37 +00001953 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Douglas Gregore83b9562015-07-07 03:57:53 +00001954 if (auto classDecl = CurMethod->getClassInterface()) {
1955 SuperType = QualType(classDecl->getSuperClassType(), 0);
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001956 if (CurMethod->isInstanceMethod()) {
Douglas Gregore83b9562015-07-07 03:57:53 +00001957 if (SuperType.isNull()) {
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001958 // The current class does not have a superclass.
Richard Smithf8812672016-12-02 22:38:31 +00001959 Diag(receiverNameLoc, diag::err_root_class_cannot_use_super)
Douglas Gregore83b9562015-07-07 03:57:53 +00001960 << CurMethod->getClassInterface()->getIdentifier();
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001961 return ExprError();
1962 }
Douglas Gregore83b9562015-07-07 03:57:53 +00001963 QualType T = Context.getObjCObjectPointerType(SuperType);
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001964
Douglas Gregore83b9562015-07-07 03:57:53 +00001965 return HandleExprPropertyRefExpr(T->castAs<ObjCObjectPointerType>(),
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001966 /*BaseExpr*/nullptr,
1967 SourceLocation()/*OpLoc*/,
1968 &propertyName,
1969 propertyNameLoc,
1970 receiverNameLoc, T, true);
Fariborz Jahanian05e2aaa2013-03-11 22:26:33 +00001971 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001972
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001973 // Otherwise, if this is a class method, try dispatching to our
1974 // superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00001975 IFace = CurMethod->getClassInterface()->getSuperClass();
Chris Lattnera36ec422010-04-11 08:28:14 +00001976 }
Chris Lattnera36ec422010-04-11 08:28:14 +00001977 }
John McCall5f2d5562011-02-03 09:00:02 +00001978 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001979
1980 if (!IFace) {
Alp Tokerec543272013-12-24 09:48:30 +00001981 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
1982 << tok::l_paren;
Chris Lattnera36ec422010-04-11 08:28:14 +00001983 return ExprError();
1984 }
1985 }
1986
1987 // Search for a declared property first.
Steve Naroff9527bbf2009-03-09 21:12:44 +00001988 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001989 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001990
1991 // If this reference is in an @implementation, check for 'private' methods.
1992 if (!Getter)
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001993 Getter = IFace->lookupPrivateClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001994
1995 if (Getter) {
1996 // FIXME: refactor/share with ActOnMemberReference().
1997 // Check if we can reference this property.
1998 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1999 return ExprError();
2000 }
Mike Stump11289f42009-09-09 15:08:12 +00002001
Steve Naroff9527bbf2009-03-09 21:12:44 +00002002 // Look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00002003 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00002004 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
Douglas Gregore83b9562015-07-07 03:57:53 +00002005 PP.getSelectorTable(),
Adrian Prantla4ce9062013-06-07 22:29:12 +00002006 &propertyName);
Mike Stump11289f42009-09-09 15:08:12 +00002007
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002008 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002009 if (!Setter) {
2010 // If this reference is in an @implementation, also check for 'private'
2011 // methods.
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00002012 Setter = IFace->lookupPrivateClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002013 }
2014 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00002015 if (!Setter)
2016 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002017
2018 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
2019 return ExprError();
2020
2021 if (Getter || Setter) {
Douglas Gregore83b9562015-07-07 03:57:53 +00002022 if (!SuperType.isNull())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002023 return new (Context)
2024 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
2025 OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
Douglas Gregore83b9562015-07-07 03:57:53 +00002026 SuperType);
Douglas Gregor33823722011-06-11 01:09:30 +00002027
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002028 return new (Context) ObjCPropertyRefExpr(
2029 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
2030 propertyNameLoc, receiverNameLoc, IFace);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002031 }
2032 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
2033 << &propertyName << Context.getObjCInterfaceType(IFace));
2034}
2035
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002036namespace {
2037
2038class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
2039 public:
2040 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
2041 // Determine whether "super" is acceptable in the current context.
2042 if (Method && Method->getClassInterface())
2043 WantObjCSuper = Method->getClassInterface()->getSuperClass();
2044 }
2045
Craig Toppere14c0f82014-03-12 04:55:44 +00002046 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002047 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
2048 candidate.isKeyword("super");
2049 }
2050};
2051
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002052} // end anonymous namespace
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002053
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002054Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregore5798dc2010-04-21 20:38:13 +00002055 IdentifierInfo *Name,
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002056 SourceLocation NameLoc,
2057 bool IsSuper,
Douglas Gregore5798dc2010-04-21 20:38:13 +00002058 bool HasTrailingDot,
John McCallba7bf592010-08-24 05:47:05 +00002059 ParsedType &ReceiverType) {
David Blaikieefdccaa2016-01-15 23:43:34 +00002060 ReceiverType = nullptr;
Douglas Gregore5798dc2010-04-21 20:38:13 +00002061
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002062 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor57756ea2010-10-14 22:11:03 +00002063 // messaging super. If the identifier is "super" and there is a
2064 // trailing dot, it's an instance message.
2065 if (IsSuper && S->isInObjcMethodScope())
2066 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002067
2068 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
2069 LookupName(Result, S);
2070
2071 switch (Result.getResultKind()) {
2072 case LookupResult::NotFound:
Douglas Gregorca7136b2010-04-19 20:09:36 +00002073 // Normal name lookup didn't find anything. If we're in an
2074 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor57756ea2010-10-14 22:11:03 +00002075 // FIXME: This is a hack. Ivar lookup should be part of normal
2076 // lookup.
Douglas Gregorca7136b2010-04-19 20:09:36 +00002077 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidis3a8de5b2011-11-09 00:22:48 +00002078 if (!Method->getClassInterface()) {
2079 // Fall back: let the parser try to parse it as an instance message.
2080 return ObjCInstanceMessage;
2081 }
2082
Douglas Gregorca7136b2010-04-19 20:09:36 +00002083 ObjCInterfaceDecl *ClassDeclared;
2084 if (Method->getClassInterface()->lookupInstanceVariable(Name,
2085 ClassDeclared))
2086 return ObjCInstanceMessage;
2087 }
Douglas Gregor57756ea2010-10-14 22:11:03 +00002088
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002089 // Break out; we'll perform typo correction below.
2090 break;
2091
2092 case LookupResult::NotFoundInCurrentInstantiation:
2093 case LookupResult::FoundOverloaded:
2094 case LookupResult::FoundUnresolvedValue:
2095 case LookupResult::Ambiguous:
2096 Result.suppressDiagnostics();
2097 return ObjCInstanceMessage;
2098
2099 case LookupResult::Found: {
Fariborz Jahanian14889fc2011-02-08 00:23:07 +00002100 // If the identifier is a class or not, and there is a trailing dot,
2101 // it's an instance message.
2102 if (HasTrailingDot)
2103 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002104 // We found something. If it's a type, then we have a class
2105 // message. Otherwise, it's an instance message.
2106 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregore5798dc2010-04-21 20:38:13 +00002107 QualType T;
2108 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
2109 T = Context.getObjCInterfaceType(Class);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00002110 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
Douglas Gregore5798dc2010-04-21 20:38:13 +00002111 T = Context.getTypeDeclType(Type);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00002112 DiagnoseUseOfDecl(Type, NameLoc);
2113 }
2114 else
Douglas Gregore5798dc2010-04-21 20:38:13 +00002115 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002116
Douglas Gregore5798dc2010-04-21 20:38:13 +00002117 // We have a class message, and T is the type we're
2118 // messaging. Build source-location information for it.
2119 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +00002120 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregore5798dc2010-04-21 20:38:13 +00002121 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002122 }
2123 }
2124
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002125 if (TypoCorrection Corrected = CorrectTypo(
2126 Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr,
2127 llvm::make_unique<ObjCInterfaceOrSuperCCC>(getCurMethodDecl()),
2128 CTK_ErrorRecovery, nullptr, false, nullptr, false)) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002129 if (Corrected.isKeyword()) {
2130 // If we've found the keyword "super" (the only keyword that would be
2131 // returned by CorrectTypo), this is a send to super.
Richard Smithf9b15102013-08-17 00:46:16 +00002132 diagnoseTypo(Corrected,
2133 PDiag(diag::err_unknown_receiver_suggest) << Name);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002134 return ObjCSuperMessage;
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002135 } else if (ObjCInterfaceDecl *Class =
Richard Smithf9b15102013-08-17 00:46:16 +00002136 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002137 // If we found a declaration, correct when it refers to an Objective-C
2138 // class.
Richard Smithf9b15102013-08-17 00:46:16 +00002139 diagnoseTypo(Corrected,
2140 PDiag(diag::err_unknown_receiver_suggest) << Name);
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002141 QualType T = Context.getObjCInterfaceType(Class);
2142 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2143 ReceiverType = CreateParsedType(T, TSInfo);
2144 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002145 }
2146 }
Richard Smithf9b15102013-08-17 00:46:16 +00002147
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002148 // Fall back: let the parser try to parse it as an instance message.
2149 return ObjCInstanceMessage;
2150}
Steve Naroff9527bbf2009-03-09 21:12:44 +00002151
John McCalldadc5752010-08-24 06:29:42 +00002152ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002153 SourceLocation SuperLoc,
2154 Selector Sel,
2155 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002156 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002157 SourceLocation RBracLoc,
2158 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002159 // Determine whether we are inside a method or not.
Eli Friedman24af8502012-02-03 22:47:37 +00002160 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregor4fdba132010-04-21 20:01:04 +00002161 if (!Method) {
2162 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
2163 return ExprError();
2164 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002165
Douglas Gregor4fdba132010-04-21 20:01:04 +00002166 ObjCInterfaceDecl *Class = Method->getClassInterface();
2167 if (!Class) {
Richard Smithf8812672016-12-02 22:38:31 +00002168 Diag(SuperLoc, diag::err_no_super_class_message)
Douglas Gregor4fdba132010-04-21 20:01:04 +00002169 << Method->getDeclName();
2170 return ExprError();
2171 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002172
Douglas Gregore83b9562015-07-07 03:57:53 +00002173 QualType SuperTy(Class->getSuperClassType(), 0);
2174 if (SuperTy.isNull()) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002175 // The current class does not have a superclass.
Richard Smithf8812672016-12-02 22:38:31 +00002176 Diag(SuperLoc, diag::err_root_class_cannot_use_super)
Ted Kremenek499897b2011-01-23 17:21:34 +00002177 << Class->getIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002178 return ExprError();
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002179 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002180
Douglas Gregor4fdba132010-04-21 20:01:04 +00002181 // We are in a method whose class has a superclass, so 'super'
2182 // is acting as a keyword.
Jordan Rose2afd6612012-10-19 16:05:26 +00002183 if (Method->getSelector() == Sel)
2184 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber715abaf2011-08-22 17:25:57 +00002185
Jordan Rose2afd6612012-10-19 16:05:26 +00002186 if (Method->isInstanceMethod()) {
Douglas Gregor4fdba132010-04-21 20:01:04 +00002187 // Since we are in an instance method, this is an instance
2188 // message to the superclass instance.
Douglas Gregor4fdba132010-04-21 20:01:04 +00002189 SuperTy = Context.getObjCObjectPointerType(SuperTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00002190 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
2191 Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002192 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002193 }
Douglas Gregor4fdba132010-04-21 20:01:04 +00002194
2195 // Since we are in a class method, this is a class message to
2196 // the superclass.
Craig Topperc3ec1492014-05-26 06:22:03 +00002197 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
Douglas Gregore83b9562015-07-07 03:57:53 +00002198 SuperTy,
Craig Topperc3ec1492014-05-26 06:22:03 +00002199 SuperLoc, Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002200 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002201}
2202
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002203ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
2204 bool isSuperReceiver,
2205 SourceLocation Loc,
2206 Selector Sel,
2207 ObjCMethodDecl *Method,
2208 MultiExprArg Args) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002209 TypeSourceInfo *receiverTypeInfo = nullptr;
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002210 if (!ReceiverType.isNull())
2211 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
2212
2213 return BuildClassMessage(receiverTypeInfo, ReceiverType,
2214 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
2215 Sel, Method, Loc, Loc, Loc, Args,
2216 /*isImplicit=*/true);
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002217}
2218
Ted Kremeneke65b0862012-03-06 20:05:56 +00002219static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2220 unsigned DiagID,
2221 bool (*refactor)(const ObjCMessageExpr *,
2222 const NSAPI &, edit::Commit &)) {
2223 SourceLocation MsgLoc = Msg->getExprLoc();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002224 if (S.Diags.isIgnored(DiagID, MsgLoc))
Ted Kremeneke65b0862012-03-06 20:05:56 +00002225 return;
2226
2227 SourceManager &SM = S.SourceMgr;
2228 edit::Commit ECommit(SM, S.LangOpts);
2229 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2230 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2231 << Msg->getSelector() << Msg->getSourceRange();
2232 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2233 if (!ECommit.isCommitable())
2234 return;
2235 for (edit::Commit::edit_iterator
2236 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2237 const edit::Commit::Edit &Edit = *I;
2238 switch (Edit.Kind) {
2239 case edit::Commit::Act_Insert:
2240 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2241 Edit.Text,
2242 Edit.BeforePrev));
2243 break;
2244 case edit::Commit::Act_InsertFromRange:
2245 Builder.AddFixItHint(
2246 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2247 Edit.getInsertFromRange(SM),
2248 Edit.BeforePrev));
2249 break;
2250 case edit::Commit::Act_Remove:
2251 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2252 break;
2253 }
2254 }
2255 }
2256}
2257
2258static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2259 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2260 edit::rewriteObjCRedundantCallWithLiteral);
2261}
2262
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002263/// \brief Diagnose use of %s directive in an NSString which is being passed
2264/// as formatting string to formatting method.
2265static void
2266DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S,
2267 ObjCMethodDecl *Method,
2268 Selector Sel,
2269 Expr **Args, unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002270 unsigned Idx = 0;
2271 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002272 ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily();
2273 if (SFFamily == ObjCStringFormatFamily::SFF_NSString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002274 Idx = 0;
2275 Format = true;
2276 }
2277 else if (Method) {
2278 for (const auto *I : Method->specific_attrs<FormatAttr>()) {
2279 if (S.GetFormatNSStringIdx(I, Idx)) {
2280 Format = true;
2281 break;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002282 }
2283 }
2284 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002285 if (!Format || NumArgs <= Idx)
2286 return;
2287
2288 Expr *FormatExpr = Args[Idx];
2289 if (ObjCStringLiteral *OSL =
2290 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) {
2291 StringLiteral *FormatString = OSL->getString();
2292 if (S.FormatStringHasSArg(FormatString)) {
2293 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2294 << "%s" << 0 << 0;
2295 if (Method)
2296 S.Diag(Method->getLocation(), diag::note_method_declared_at)
2297 << Method->getDeclName();
2298 }
2299 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002300}
2301
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002302/// \brief Build an Objective-C class message expression.
2303///
2304/// This routine takes care of both normal class messages and
2305/// class messages to the superclass.
2306///
2307/// \param ReceiverTypeInfo Type source information that describes the
2308/// receiver of this message. This may be NULL, in which case we are
2309/// sending to the superclass and \p SuperLoc must be a valid source
2310/// location.
2311
2312/// \param ReceiverType The type of the object receiving the
2313/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2314/// type as that refers to. For a superclass send, this is the type of
2315/// the superclass.
2316///
2317/// \param SuperLoc The location of the "super" keyword in a
2318/// superclass message.
2319///
2320/// \param Sel The selector to which the message is being sent.
2321///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002322/// \param Method The method that this class message is invoking, if
2323/// already known.
2324///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002325/// \param LBracLoc The location of the opening square bracket ']'.
2326///
James Dennettffad8b72012-06-22 08:10:18 +00002327/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002328///
James Dennettffad8b72012-06-22 08:10:18 +00002329/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002330ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002331 QualType ReceiverType,
2332 SourceLocation SuperLoc,
2333 Selector Sel,
2334 ObjCMethodDecl *Method,
2335 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002336 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002337 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002338 MultiExprArg ArgsIn,
2339 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002340 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00002341 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002342 if (LBracLoc.isInvalid()) {
2343 Diag(Loc, diag::err_missing_open_square_message_send)
2344 << FixItHint::CreateInsertion(Loc, "[");
2345 LBracLoc = Loc;
2346 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002347 SourceLocation SelLoc;
2348 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2349 SelLoc = SelectorLocs.front();
2350 else
2351 SelLoc = Loc;
2352
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002353 if (ReceiverType->isDependentType()) {
2354 // If the receiver type is dependent, we can't type-check anything
2355 // at this point. Build a dependent expression.
2356 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002357 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002358 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002359 return ObjCMessageExpr::Create(
2360 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
2361 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2362 isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002363 }
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002364
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002365 // Find the class to which we are sending this message.
Craig Topperc3ec1492014-05-26 06:22:03 +00002366 ObjCInterfaceDecl *Class = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00002367 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2368 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002369 Diag(Loc, diag::err_invalid_receiver_class_message)
2370 << ReceiverType;
2371 return ExprError();
Steve Naroffe2177fb2008-07-25 19:39:00 +00002372 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002373 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanianc27cd1b2011-10-15 19:18:36 +00002374 // objc++ diagnoses during typename annotation.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002375 if (!getLangOpts().CPlusPlus)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002376 (void)DiagnoseUseOfDecl(Class, SelLoc);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002377 // Find the method we are messaging.
Douglas Gregorb5186b12010-04-22 17:01:48 +00002378 if (!Method) {
Douglas Gregor4123a862011-11-14 22:10:01 +00002379 SourceRange TypeRange
2380 = SuperLoc.isValid()? SourceRange(SuperLoc)
2381 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002382 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002383 (getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002384 ? diag::err_arc_receiver_forward_class
2385 : diag::warn_receiver_forward_class),
2386 TypeRange)) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002387 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorb5186b12010-04-22 17:01:48 +00002388 Method = LookupFactoryMethodInGlobalPool(Sel,
2389 SourceRange(LBracLoc, RBracLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00002390 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002391 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2392 << Method->getDeclName();
2393 }
2394 if (!Method)
2395 Method = Class->lookupClassMethod(Sel);
2396
2397 // If we have an implementation in scope, check "private" methods.
2398 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002399 Method = Class->lookupPrivateClassMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002400
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002401 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002402 return ExprError();
Fariborz Jahanian1bd844d2009-05-08 23:02:36 +00002403 }
Mike Stump11289f42009-09-09 15:08:12 +00002404
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002405 // Check the argument types and determine the result type.
2406 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002407 ExprValueKind VK = VK_RValue;
2408
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002409 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002410 Expr **Args = ArgsIn.data();
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002411 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2412 Sel, SelectorLocs,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00002413 Method, true,
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00002414 SuperLoc.isValid(), LBracLoc, RBracLoc,
2415 SourceRange(),
Douglas Gregor33823722011-06-11 01:09:30 +00002416 ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002417 return ExprError();
Ted Kremeneka3a37ae2008-06-24 15:50:53 +00002418
Alp Toker314cc812014-01-25 16:55:45 +00002419 if (Method && !Method->getReturnType()->isVoidType() &&
2420 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002421 diag::err_illegal_message_expr_incomplete_type))
2422 return ExprError();
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002423
Fariborz Jahaniane8b45502014-08-22 19:52:49 +00002424 // Warn about explicit call of +initialize on its own class. But not on 'super'.
Fariborz Jahanian42292282014-08-25 21:27:38 +00002425 if (Method && Method->getMethodFamily() == OMF_initialize) {
2426 if (!SuperLoc.isValid()) {
2427 const ObjCInterfaceDecl *ID =
2428 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext());
2429 if (ID == Class) {
2430 Diag(Loc, diag::warn_direct_initialize_call);
2431 Diag(Method->getLocation(), diag::note_method_declared_at)
2432 << Method->getDeclName();
2433 }
2434 }
2435 else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2436 // [super initialize] is allowed only within an +initialize implementation
2437 if (CurMeth->getMethodFamily() != OMF_initialize) {
2438 Diag(Loc, diag::warn_direct_super_initialize_call);
2439 Diag(Method->getLocation(), diag::note_method_declared_at)
2440 << Method->getDeclName();
2441 Diag(CurMeth->getLocation(), diag::note_method_declared_at)
2442 << CurMeth->getDeclName();
2443 }
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002444 }
2445 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002446
2447 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2448
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002449 // Construct the appropriate ObjCMessageExpr.
Ted Kremeneke65b0862012-03-06 20:05:56 +00002450 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002451 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002452 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002453 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002454 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002455 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002456 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002457 else {
John McCall7decc9e2010-11-18 06:31:45 +00002458 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002459 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002460 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002461 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002462 if (!isImplicit)
2463 checkCocoaAPI(*this, Result);
2464 }
Douglas Gregoraae38d62010-05-22 05:17:18 +00002465 return MaybeBindToTemporary(Result);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002466}
2467
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002468// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002469// ArgExprs is optional - if it is present, the number of expressions
2470// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002471ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor3e972002010-09-15 23:19:31 +00002472 ParsedType Receiver,
2473 Selector Sel,
2474 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002475 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor3e972002010-09-15 23:19:31 +00002476 SourceLocation RBracLoc,
2477 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002478 TypeSourceInfo *ReceiverTypeInfo;
2479 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2480 if (ReceiverType.isNull())
2481 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002482
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002483 if (!ReceiverTypeInfo)
2484 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2485
2486 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002487 /*SuperLoc=*/SourceLocation(), Sel,
2488 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2489 Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002490}
2491
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002492ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2493 QualType ReceiverType,
2494 SourceLocation Loc,
2495 Selector Sel,
2496 ObjCMethodDecl *Method,
2497 MultiExprArg Args) {
2498 return BuildInstanceMessage(Receiver, ReceiverType,
2499 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2500 Sel, Method, Loc, Loc, Loc, Args,
2501 /*isImplicit=*/true);
2502}
2503
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002504/// \brief Build an Objective-C instance message expression.
2505///
2506/// This routine takes care of both normal instance messages and
2507/// instance messages to the superclass instance.
2508///
2509/// \param Receiver The expression that computes the object that will
2510/// receive this message. This may be empty, in which case we are
2511/// sending to the superclass instance and \p SuperLoc must be a valid
2512/// source location.
2513///
2514/// \param ReceiverType The (static) type of the object receiving the
2515/// message. When a \p Receiver expression is provided, this is the
2516/// same type as that expression. For a superclass instance send, this
2517/// is a pointer to the type of the superclass.
2518///
2519/// \param SuperLoc The location of the "super" keyword in a
2520/// superclass instance message.
2521///
2522/// \param Sel The selector to which the message is being sent.
2523///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002524/// \param Method The method that this instance message is invoking, if
2525/// already known.
2526///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002527/// \param LBracLoc The location of the opening square bracket ']'.
2528///
James Dennettffad8b72012-06-22 08:10:18 +00002529/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002530///
James Dennettffad8b72012-06-22 08:10:18 +00002531/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002532ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002533 QualType ReceiverType,
2534 SourceLocation SuperLoc,
2535 Selector Sel,
2536 ObjCMethodDecl *Method,
2537 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002538 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002539 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002540 MultiExprArg ArgsIn,
2541 bool isImplicit) {
Chandler Carruth3d402842016-11-04 06:11:54 +00002542 assert((Receiver || SuperLoc.isValid()) && "If the Receiver is null, the "
2543 "SuperLoc must be valid so we can "
2544 "use it instead.");
2545
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002546 // The location of the receiver.
2547 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002548 SourceRange RecRange =
2549 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2550 SourceLocation SelLoc;
2551 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2552 SelLoc = SelectorLocs.front();
2553 else
2554 SelLoc = Loc;
2555
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002556 if (LBracLoc.isInvalid()) {
2557 Diag(Loc, diag::err_missing_open_square_message_send)
2558 << FixItHint::CreateInsertion(Loc, "[");
2559 LBracLoc = Loc;
2560 }
2561
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002562 // If we have a receiver expression, perform appropriate promotions
2563 // and determine receiver type.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002564 if (Receiver) {
John McCall4124c492011-10-17 18:40:02 +00002565 if (Receiver->hasPlaceholderType()) {
Douglas Gregord8fb1e32011-12-01 01:37:36 +00002566 ExprResult Result;
2567 if (Receiver->getType() == Context.UnknownAnyTy)
2568 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2569 else
2570 Result = CheckPlaceholderExpr(Receiver);
2571 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002572 Receiver = Result.get();
John McCall4124c492011-10-17 18:40:02 +00002573 }
2574
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002575 if (Receiver->isTypeDependent()) {
2576 // If the receiver is type-dependent, we can't type-check anything
2577 // at this point. Build a dependent expression.
2578 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002579 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002580 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002581 return ObjCMessageExpr::Create(
2582 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
2583 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2584 RBracLoc, isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002585 }
2586
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002587 // If necessary, apply function/array conversion to the receiver.
2588 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00002589 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2590 if (Result.isInvalid())
2591 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002592 Receiver = Result.get();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002593 ReceiverType = Receiver->getType();
John McCall80c93a02013-03-01 09:20:14 +00002594
2595 // If the receiver is an ObjC pointer, a block pointer, or an
2596 // __attribute__((NSObject)) pointer, we don't need to do any
2597 // special conversion in order to look up a receiver.
2598 if (ReceiverType->isObjCRetainableType()) {
2599 // do nothing
2600 } else if (!getLangOpts().ObjCAutoRefCount &&
2601 !Context.getObjCIdType().isNull() &&
2602 (ReceiverType->isPointerType() ||
2603 ReceiverType->isIntegerType())) {
2604 // Implicitly convert integers and pointers to 'id' but emit a warning.
2605 // But not in ARC.
2606 Diag(Loc, diag::warn_bad_receiver_type)
2607 << ReceiverType
2608 << Receiver->getSourceRange();
2609 if (ReceiverType->isPointerType()) {
2610 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002611 CK_CPointerToObjCPointerCast).get();
John McCall80c93a02013-03-01 09:20:14 +00002612 } else {
2613 // TODO: specialized warning on null receivers?
2614 bool IsNull = Receiver->isNullPointerConstant(Context,
2615 Expr::NPC_ValueDependentIsNull);
2616 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2617 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002618 Kind).get();
John McCall80c93a02013-03-01 09:20:14 +00002619 }
2620 ReceiverType = Receiver->getType();
2621 } else if (getLangOpts().CPlusPlus) {
Douglas Gregor4b60a152013-11-07 22:34:54 +00002622 // The receiver must be a complete type.
2623 if (RequireCompleteType(Loc, Receiver->getType(),
2624 diag::err_incomplete_receiver_type))
2625 return ExprError();
2626
John McCall80c93a02013-03-01 09:20:14 +00002627 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2628 if (result.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002629 Receiver = result.get();
John McCall80c93a02013-03-01 09:20:14 +00002630 ReceiverType = Receiver->getType();
2631 }
2632 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002633 }
2634
John McCall80c93a02013-03-01 09:20:14 +00002635 // There's a somewhat weird interaction here where we assume that we
2636 // won't actually have a method unless we also don't need to do some
2637 // of the more detailed type-checking on the receiver.
2638
Douglas Gregorb5186b12010-04-22 17:01:48 +00002639 if (!Method) {
Douglas Gregorab209d82015-07-07 03:58:42 +00002640 // Handle messages to id and __kindof types (where we use the
2641 // global method pool).
Douglas Gregorab209d82015-07-07 03:58:42 +00002642 const ObjCObjectType *typeBound = nullptr;
2643 bool receiverIsIdLike = ReceiverType->isObjCIdOrObjectKindOfType(Context,
2644 typeBound);
2645 if (receiverIsIdLike || ReceiverType->isBlockPointerType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002646 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
Manman Rend2a3cd72016-04-07 19:30:20 +00002647 SmallVector<ObjCMethodDecl*, 4> Methods;
Manman Ren7ed4f982016-04-07 19:32:24 +00002648 // If we have a type bound, further filter the methods.
Manman Rend2a3cd72016-04-07 19:30:20 +00002649 CollectMultipleMethodsInGlobalPool(Sel, Methods, true/*InstanceFirst*/,
Manman Ren7ed4f982016-04-07 19:32:24 +00002650 true/*CheckTheOther*/, typeBound);
Manman Rend2a3cd72016-04-07 19:30:20 +00002651 if (!Methods.empty()) {
George Burgess IV52d07de2016-09-01 01:26:58 +00002652 // We choose the first method as the initial candidate, then try to
Manman Rend2a3cd72016-04-07 19:30:20 +00002653 // select a better one.
2654 Method = Methods[0];
2655
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00002656 if (ObjCMethodDecl *BestMethod =
Manman Rend2a3cd72016-04-07 19:30:20 +00002657 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(), Methods))
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00002658 Method = BestMethod;
Manman Rend2a3cd72016-04-07 19:30:20 +00002659
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002660 if (!AreMultipleMethodsInGlobalPool(Sel, Method,
2661 SourceRange(LBracLoc, RBracLoc),
Manman Rend2a3cd72016-04-07 19:30:20 +00002662 receiverIsIdLike, Methods))
2663 DiagnoseUseOfDecl(Method, SelLoc);
Fariborz Jahanian05e77f82014-11-07 23:51:15 +00002664 }
Douglas Gregorab209d82015-07-07 03:58:42 +00002665 } else if (ReceiverType->isObjCClassOrClassKindOfType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002666 ReceiverType->isObjCQualifiedClassType()) {
2667 // Handle messages to Class.
Nico Weber2e0c8f72014-12-27 03:58:08 +00002668 // We allow sending a message to a qualified Class ("Class<foo>"), which
2669 // is ok as long as one of the protocols implements the selector (if not,
2670 // warn).
Douglas Gregorab209d82015-07-07 03:58:42 +00002671 if (!ReceiverType->isObjCClassOrClassKindOfType()) {
2672 const ObjCObjectPointerType *QClassTy
2673 = ReceiverType->getAsObjCQualifiedClassType();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002674 // Search protocols for class methods.
2675 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2676 if (!Method) {
2677 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2678 // warn if instance method found for a Class message.
2679 if (Method) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002680 Diag(SelLoc, diag::warn_instance_method_on_class_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002681 << Method->getSelector() << Sel;
Ted Kremenek59b10db2012-02-27 22:55:11 +00002682 Diag(Method->getLocation(), diag::note_method_declared_at)
2683 << Method->getDeclName();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002684 }
Steve Naroff3f49fee2009-03-04 15:11:40 +00002685 }
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002686 } else {
2687 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2688 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2689 // First check the public methods in the class interface.
2690 Method = ClassDecl->lookupClassMethod(Sel);
2691
2692 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002693 Method = ClassDecl->lookupPrivateClassMethod(Sel);
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002694 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002695 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002696 return ExprError();
2697 }
2698 if (!Method) {
2699 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregor486b74e2011-09-27 16:10:05 +00002700 if (!Receiver || !isSelfExpr(Receiver)) {
Manman Rend2a3cd72016-04-07 19:30:20 +00002701 // If no class (factory) method was found, check if an _instance_
2702 // method of the same name exists in the root class only.
2703 SmallVector<ObjCMethodDecl*, 4> Methods;
2704 CollectMultipleMethodsInGlobalPool(Sel, Methods,
2705 false/*InstanceFirst*/,
2706 true/*CheckTheOther*/);
2707 if (!Methods.empty()) {
George Burgess IV52d07de2016-09-01 01:26:58 +00002708 // We choose the first method as the initial candidate, then try
Manman Rend2a3cd72016-04-07 19:30:20 +00002709 // to select a better one.
2710 Method = Methods[0];
2711
2712 // If we find an instance method, emit waring.
2713 if (Method->isInstanceMethod()) {
2714 if (const ObjCInterfaceDecl *ID =
2715 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2716 if (ID->getSuperClass())
2717 Diag(SelLoc, diag::warn_root_inst_method_not_found)
2718 << Sel << SourceRange(LBracLoc, RBracLoc);
2719 }
2720 }
2721
2722 if (ObjCMethodDecl *BestMethod =
2723 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
2724 Methods))
2725 Method = BestMethod;
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002726 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002727 }
2728 }
2729 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002730 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00002731 ObjCInterfaceDecl *ClassDecl = nullptr;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002732
2733 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2734 // long as one of the protocols implements the selector (if not, warn).
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002735 // And as long as message is not deprecated/unavailable (warn if it is).
Douglas Gregorb5186b12010-04-22 17:01:48 +00002736 if (const ObjCObjectPointerType *QIdTy
2737 = ReceiverType->getAsObjCQualifiedIdType()) {
2738 // Search protocols for instance methods.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002739 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2740 if (!Method)
2741 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002742 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002743 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002744 } else if (const ObjCObjectPointerType *OCIType
2745 = ReceiverType->getAsObjCInterfacePointerType()) {
2746 // We allow sending a message to a pointer to an interface (an object).
2747 ClassDecl = OCIType->getInterfaceDecl();
John McCall31168b02011-06-15 23:02:42 +00002748
Douglas Gregor4123a862011-11-14 22:10:01 +00002749 // Try to complete the type. Under ARC, this is a hard error from which
2750 // we don't try to recover.
Richard Smithdb0ac552015-12-18 22:40:25 +00002751 // FIXME: In the non-ARC case, this will still be a hard error if the
2752 // definition is found in a module that's not visible.
Craig Topperc3ec1492014-05-26 06:22:03 +00002753 const ObjCInterfaceDecl *forwardClass = nullptr;
Douglas Gregor4123a862011-11-14 22:10:01 +00002754 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002755 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002756 ? diag::err_arc_receiver_forward_instance
2757 : diag::warn_receiver_forward_instance,
2758 Receiver? Receiver->getSourceRange()
2759 : SourceRange(SuperLoc))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002760 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregor4123a862011-11-14 22:10:01 +00002761 return ExprError();
2762
2763 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanianc934de62012-02-03 01:02:44 +00002764 Diag(Receiver ? Receiver->getLocStart()
2765 : SuperLoc, diag::note_receiver_is_id);
Craig Topperc3ec1492014-05-26 06:22:03 +00002766 Method = nullptr;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002767 } else {
2768 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCall31168b02011-06-15 23:02:42 +00002769 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002770
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002771 if (!Method)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002772 // Search protocol qualifiers.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002773 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2774
Douglas Gregorb5186b12010-04-22 17:01:48 +00002775 if (!Method) {
2776 // If we have implementations in scope, check "private" methods.
Anna Zaksc77a3b12012-07-27 19:07:44 +00002777 Method = ClassDecl->lookupPrivateMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002778
David Blaikiebbafb8a2012-03-11 07:00:24 +00002779 if (!Method && getLangOpts().ObjCAutoRefCount) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002780 Diag(SelLoc, diag::err_arc_may_not_respond)
2781 << OCIType->getPointeeType() << Sel << RecRange
Fariborz Jahanian32c13502012-11-28 01:27:44 +00002782 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
John McCall31168b02011-06-15 23:02:42 +00002783 return ExprError();
2784 }
2785
Douglas Gregor486b74e2011-09-27 16:10:05 +00002786 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002787 // If we still haven't found a method, look in the global pool. This
2788 // behavior isn't very desirable, however we need it for GCC
2789 // compatibility. FIXME: should we deviate??
2790 if (OCIType->qual_empty()) {
Manman Rend2a3cd72016-04-07 19:30:20 +00002791 SmallVector<ObjCMethodDecl*, 4> Methods;
2792 CollectMultipleMethodsInGlobalPool(Sel, Methods,
2793 true/*InstanceFirst*/,
2794 false/*CheckTheOther*/);
2795 if (!Methods.empty()) {
George Burgess IV52d07de2016-09-01 01:26:58 +00002796 // We choose the first method as the initial candidate, then try
Manman Rend2a3cd72016-04-07 19:30:20 +00002797 // to select a better one.
2798 Method = Methods[0];
2799
2800 if (ObjCMethodDecl *BestMethod =
2801 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
2802 Methods))
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002803 Method = BestMethod;
Manman Rend2a3cd72016-04-07 19:30:20 +00002804
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002805 AreMultipleMethodsInGlobalPool(Sel, Method,
2806 SourceRange(LBracLoc, RBracLoc),
Manman Rend2a3cd72016-04-07 19:30:20 +00002807 true/*receiverIdOrClass*/,
2808 Methods);
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002809 }
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +00002810 if (Method && !forwardClass)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002811 Diag(SelLoc, diag::warn_maynot_respond)
2812 << OCIType->getInterfaceDecl()->getIdentifier()
2813 << Sel << RecRange;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002814 }
2815 }
2816 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002817 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002818 return ExprError();
John McCallfec112d2011-09-09 06:11:02 +00002819 } else {
John McCall80c93a02013-03-01 09:20:14 +00002820 // Reject other random receiver types (e.g. structs).
2821 Diag(Loc, diag::err_bad_receiver_type)
2822 << ReceiverType << Receiver->getSourceRange();
2823 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002824 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002825 }
Chris Lattner6b946cc2008-07-21 05:57:44 +00002826 }
Mike Stump11289f42009-09-09 15:08:12 +00002827
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002828 FunctionScopeInfo *DIFunctionScopeInfo =
2829 (Method && Method->getMethodFamily() == OMF_init)
Craig Topperc3ec1492014-05-26 06:22:03 +00002830 ? getEnclosingFunction() : nullptr;
2831
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002832 if (DIFunctionScopeInfo &&
2833 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002834 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2835 bool isDesignatedInitChain = false;
2836 if (SuperLoc.isValid()) {
2837 if (const ObjCObjectPointerType *
2838 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2839 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
Argyrios Kyrtzidisd664a342013-12-13 03:48:17 +00002840 // Either we know this is a designated initializer or we
2841 // conservatively assume it because we don't know for sure.
2842 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2843 ID->isDesignatedInitializer(Sel)) {
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002844 isDesignatedInitChain = true;
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002845 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002846 }
2847 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002848 }
2849 }
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002850 if (!isDesignatedInitChain) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002851 const ObjCMethodDecl *InitMethod = nullptr;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002852 bool isDesignated =
2853 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2854 assert(isDesignated && InitMethod);
2855 (void)isDesignated;
2856 Diag(SelLoc, SuperLoc.isValid() ?
2857 diag::warn_objc_designated_init_non_designated_init_call :
2858 diag::warn_objc_designated_init_non_super_designated_init_call);
2859 Diag(InitMethod->getLocation(),
2860 diag::note_objc_designated_init_marked_here);
2861 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002862 }
2863
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002864 if (DIFunctionScopeInfo &&
2865 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002866 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2867 if (SuperLoc.isValid()) {
2868 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2869 } else {
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002870 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002871 }
2872 }
2873
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002874 // Check the message arguments.
2875 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002876 Expr **Args = ArgsIn.data();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002877 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002878 ExprValueKind VK = VK_RValue;
Fariborz Jahanian68500912010-12-01 01:07:24 +00002879 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2880 ReceiverType->isObjCQualifiedClassType());
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002881 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2882 Sel, SelectorLocs, Method,
Douglas Gregor33823722011-06-11 01:09:30 +00002883 ClassMessage, SuperLoc.isValid(),
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00002884 LBracLoc, RBracLoc, RecRange, ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002885 return ExprError();
Alp Toker314cc812014-01-25 16:55:45 +00002886
2887 if (Method && !Method->getReturnType()->isVoidType() &&
2888 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002889 diag::err_illegal_message_expr_incomplete_type))
2890 return ExprError();
Douglas Gregor9a129192010-04-21 00:45:42 +00002891
John McCall31168b02011-06-15 23:02:42 +00002892 // In ARC, forbid the user from sending messages to
2893 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002894 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002895 ObjCMethodFamily family =
2896 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2897 switch (family) {
2898 case OMF_init:
2899 if (Method)
2900 checkInitMethod(Method, ReceiverType);
2901
2902 case OMF_None:
2903 case OMF_alloc:
2904 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00002905 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002906 case OMF_mutableCopy:
2907 case OMF_new:
2908 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002909 case OMF_initialize:
John McCall31168b02011-06-15 23:02:42 +00002910 break;
2911
2912 case OMF_dealloc:
2913 case OMF_retain:
2914 case OMF_release:
2915 case OMF_autorelease:
2916 case OMF_retainCount:
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002917 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
2918 << Sel << RecRange;
John McCall31168b02011-06-15 23:02:42 +00002919 break;
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002920
2921 case OMF_performSelector:
2922 if (Method && NumArgs >= 1) {
2923 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2924 Selector ArgSel = SelExp->getSelector();
2925 ObjCMethodDecl *SelMethod =
2926 LookupInstanceMethodInGlobalPool(ArgSel,
2927 SelExp->getSourceRange());
2928 if (!SelMethod)
2929 SelMethod =
2930 LookupFactoryMethodInGlobalPool(ArgSel,
2931 SelExp->getSourceRange());
2932 if (SelMethod) {
2933 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2934 switch (SelFamily) {
2935 case OMF_alloc:
2936 case OMF_copy:
2937 case OMF_mutableCopy:
2938 case OMF_new:
2939 case OMF_self:
2940 case OMF_init:
2941 // Issue error, unless ns_returns_not_retained.
2942 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2943 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002944 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002945 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002946 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2947 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002948 }
2949 break;
2950 default:
2951 // +0 call. OK. unless ns_returns_retained.
2952 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2953 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002954 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002955 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002956 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2957 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002958 }
2959 break;
2960 }
2961 }
2962 } else {
2963 // error (may leak).
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002964 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002965 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2966 }
2967 }
2968 break;
John McCall31168b02011-06-15 23:02:42 +00002969 }
2970 }
2971
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002972 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2973
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002974 // Construct the appropriate ObjCMessageExpr instance.
John McCall31168b02011-06-15 23:02:42 +00002975 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002976 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002977 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002978 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002979 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002980 makeArrayRef(Args, NumArgs), RBracLoc,
2981 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002982 else {
John McCall7decc9e2010-11-18 06:31:45 +00002983 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002984 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002985 makeArrayRef(Args, NumArgs), RBracLoc,
2986 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002987 if (!isImplicit)
2988 checkCocoaAPI(*this, Result);
2989 }
John McCall31168b02011-06-15 23:02:42 +00002990
David Blaikiebbafb8a2012-03-11 07:00:24 +00002991 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002992 // In ARC, annotate delegate init calls.
2993 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregor486b74e2011-09-27 16:10:05 +00002994 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCall31168b02011-06-15 23:02:42 +00002995 // Only consider init calls *directly* in init implementations,
2996 // not within blocks.
2997 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2998 if (method && method->getMethodFamily() == OMF_init) {
2999 // The implicit assignment to self means we also don't want to
3000 // consume the result.
3001 Result->setDelegateInitCall(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003002 return Result;
John McCall31168b02011-06-15 23:02:42 +00003003 }
3004 }
3005
3006 // In ARC, check for message sends which are likely to introduce
3007 // retain cycles.
3008 checkRetainCycles(Result);
Jordan Rose22487652012-10-11 16:06:21 +00003009
3010 if (!isImplicit && Method) {
3011 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
3012 bool IsWeak =
3013 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
3014 if (!IsWeak && Sel.isUnarySelector())
3015 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003016 if (IsWeak &&
3017 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
3018 getCurFunction()->recordUseOfWeak(Result, Prop);
Jordan Rose22487652012-10-11 16:06:21 +00003019 }
3020 }
John McCall31168b02011-06-15 23:02:42 +00003021 }
Alex Denisove1d882c2015-03-04 17:55:52 +00003022
3023 CheckObjCCircularContainer(Result);
3024
Douglas Gregoraae38d62010-05-22 05:17:18 +00003025 return MaybeBindToTemporary(Result);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003026}
3027
Fariborz Jahanian02447d82013-01-22 18:35:43 +00003028static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
3029 if (ObjCSelectorExpr *OSE =
3030 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
3031 Selector Sel = OSE->getSelector();
3032 SourceLocation Loc = OSE->getAtLoc();
Chandler Carruth12c8f652015-03-27 00:55:05 +00003033 auto Pos = S.ReferencedSelectors.find(Sel);
Fariborz Jahanian02447d82013-01-22 18:35:43 +00003034 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
3035 S.ReferencedSelectors.erase(Pos);
3036 }
3037}
3038
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003039// ActOnInstanceMessage - used for both unary and keyword messages.
3040// ArgExprs is optional - if it is present, the number of expressions
3041// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00003042ExprResult Sema::ActOnInstanceMessage(Scope *S,
3043 Expr *Receiver,
3044 Selector Sel,
3045 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00003046 ArrayRef<SourceLocation> SelectorLocs,
John McCalldadc5752010-08-24 06:29:42 +00003047 SourceLocation RBracLoc,
3048 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003049 if (!Receiver)
3050 return ExprError();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00003051
3052 // A ParenListExpr can show up while doing error recovery with invalid code.
3053 if (isa<ParenListExpr>(Receiver)) {
3054 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
3055 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003056 Receiver = Result.get();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00003057 }
Fariborz Jahanian17748062013-01-22 19:05:17 +00003058
3059 if (RespondsToSelectorSel.isNull()) {
3060 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
3061 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
3062 }
3063 if (Sel == RespondsToSelectorSel)
Fariborz Jahanian02447d82013-01-22 18:35:43 +00003064 RemoveSelectorFromWarningCache(*this, Args[0]);
Craig Topperc3ec1492014-05-26 06:22:03 +00003065
John McCallb268a282010-08-23 23:25:46 +00003066 return BuildInstanceMessage(Receiver, Receiver->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003067 /*SuperLoc=*/SourceLocation(), Sel,
3068 /*Method=*/nullptr, LBracLoc, SelectorLocs,
3069 RBracLoc, Args);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00003070}
Chris Lattner2a3569b2008-04-07 05:30:13 +00003071
John McCall31168b02011-06-15 23:02:42 +00003072enum ARCConversionTypeClass {
John McCalle4fe2452011-10-01 01:01:08 +00003073 /// int, void, struct A
John McCall31168b02011-06-15 23:02:42 +00003074 ACTC_none,
John McCalle4fe2452011-10-01 01:01:08 +00003075
3076 /// id, void (^)()
John McCall31168b02011-06-15 23:02:42 +00003077 ACTC_retainable,
John McCalle4fe2452011-10-01 01:01:08 +00003078
3079 /// id*, id***, void (^*)(),
3080 ACTC_indirectRetainable,
3081
3082 /// void* might be a normal C type, or it might a CF type.
3083 ACTC_voidPtr,
3084
3085 /// struct A*
3086 ACTC_coreFoundation
John McCall31168b02011-06-15 23:02:42 +00003087};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003088
John McCalle4fe2452011-10-01 01:01:08 +00003089static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
3090 return (ACTC == ACTC_retainable ||
3091 ACTC == ACTC_coreFoundation ||
3092 ACTC == ACTC_voidPtr);
3093}
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003094
John McCalle4fe2452011-10-01 01:01:08 +00003095static bool isAnyCLike(ARCConversionTypeClass ACTC) {
3096 return ACTC == ACTC_none ||
3097 ACTC == ACTC_voidPtr ||
3098 ACTC == ACTC_coreFoundation;
3099}
3100
John McCall31168b02011-06-15 23:02:42 +00003101static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCalle4fe2452011-10-01 01:01:08 +00003102 bool isIndirect = false;
John McCall31168b02011-06-15 23:02:42 +00003103
3104 // Ignore an outermost reference type.
John McCalle4fe2452011-10-01 01:01:08 +00003105 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall31168b02011-06-15 23:02:42 +00003106 type = ref->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00003107 isIndirect = true;
3108 }
John McCall31168b02011-06-15 23:02:42 +00003109
3110 // Drill through pointers and arrays recursively.
3111 while (true) {
3112 if (const PointerType *ptr = type->getAs<PointerType>()) {
3113 type = ptr->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00003114
3115 // The first level of pointer may be the innermost pointer on a CF type.
3116 if (!isIndirect) {
3117 if (type->isVoidType()) return ACTC_voidPtr;
3118 if (type->isRecordType()) return ACTC_coreFoundation;
3119 }
John McCall31168b02011-06-15 23:02:42 +00003120 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
3121 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
3122 } else {
3123 break;
3124 }
John McCalle4fe2452011-10-01 01:01:08 +00003125 isIndirect = true;
John McCall31168b02011-06-15 23:02:42 +00003126 }
3127
John McCalle4fe2452011-10-01 01:01:08 +00003128 if (isIndirect) {
3129 if (type->isObjCARCBridgableType())
3130 return ACTC_indirectRetainable;
3131 return ACTC_none;
3132 }
3133
3134 if (type->isObjCARCBridgableType())
3135 return ACTC_retainable;
3136
3137 return ACTC_none;
John McCall31168b02011-06-15 23:02:42 +00003138}
3139
3140namespace {
John McCalle4fe2452011-10-01 01:01:08 +00003141 /// A result from the cast checker.
3142 enum ACCResult {
3143 /// Cannot be casted.
3144 ACC_invalid,
3145
3146 /// Can be safely retained or not retained.
3147 ACC_bottom,
3148
3149 /// Can be casted at +0.
3150 ACC_plusZero,
3151
3152 /// Can be casted at +1.
3153 ACC_plusOne
3154 };
3155 ACCResult merge(ACCResult left, ACCResult right) {
3156 if (left == right) return left;
3157 if (left == ACC_bottom) return right;
3158 if (right == ACC_bottom) return left;
3159 return ACC_invalid;
3160 }
3161
3162 /// A checker which white-lists certain expressions whose conversion
3163 /// to or from retainable type would otherwise be forbidden in ARC.
3164 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
3165 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
3166
John McCall31168b02011-06-15 23:02:42 +00003167 ASTContext &Context;
John McCalle4fe2452011-10-01 01:01:08 +00003168 ARCConversionTypeClass SourceClass;
3169 ARCConversionTypeClass TargetClass;
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003170 bool Diagnose;
John McCalle4fe2452011-10-01 01:01:08 +00003171
3172 static bool isCFType(QualType type) {
3173 // Someday this can use ns_bridged. For now, it has to do this.
3174 return type->isCARCBridgableType();
John McCall31168b02011-06-15 23:02:42 +00003175 }
John McCalle4fe2452011-10-01 01:01:08 +00003176
3177 public:
3178 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003179 ARCConversionTypeClass target, bool diagnose)
3180 : Context(Context), SourceClass(source), TargetClass(target),
3181 Diagnose(diagnose) {}
John McCalle4fe2452011-10-01 01:01:08 +00003182
3183 using super::Visit;
3184 ACCResult Visit(Expr *e) {
3185 return super::Visit(e->IgnoreParens());
3186 }
3187
3188 ACCResult VisitStmt(Stmt *s) {
3189 return ACC_invalid;
3190 }
3191
3192 /// Null pointer constants can be casted however you please.
3193 ACCResult VisitExpr(Expr *e) {
3194 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
3195 return ACC_bottom;
3196 return ACC_invalid;
3197 }
3198
3199 /// Objective-C string literals can be safely casted.
3200 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
3201 // If we're casting to any retainable type, go ahead. Global
3202 // strings are immune to retains, so this is bottom.
3203 if (isAnyRetainable(TargetClass)) return ACC_bottom;
3204
3205 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00003206 }
3207
John McCalle4fe2452011-10-01 01:01:08 +00003208 /// Look through certain implicit and explicit casts.
3209 ACCResult VisitCastExpr(CastExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00003210 switch (e->getCastKind()) {
3211 case CK_NullToPointer:
John McCalle4fe2452011-10-01 01:01:08 +00003212 return ACC_bottom;
3213
John McCall31168b02011-06-15 23:02:42 +00003214 case CK_NoOp:
3215 case CK_LValueToRValue:
3216 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00003217 case CK_CPointerToObjCPointerCast:
3218 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00003219 case CK_AnyPointerToBlockPointerCast:
3220 return Visit(e->getSubExpr());
John McCalle4fe2452011-10-01 01:01:08 +00003221
John McCall31168b02011-06-15 23:02:42 +00003222 default:
John McCalle4fe2452011-10-01 01:01:08 +00003223 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00003224 }
3225 }
John McCalle4fe2452011-10-01 01:01:08 +00003226
3227 /// Look through unary extension.
3228 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00003229 return Visit(e->getSubExpr());
3230 }
John McCalle4fe2452011-10-01 01:01:08 +00003231
3232 /// Ignore the LHS of a comma operator.
3233 ACCResult VisitBinComma(BinaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00003234 return Visit(e->getRHS());
3235 }
John McCalle4fe2452011-10-01 01:01:08 +00003236
3237 /// Conditional operators are okay if both sides are okay.
3238 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
3239 ACCResult left = Visit(e->getTrueExpr());
3240 if (left == ACC_invalid) return ACC_invalid;
3241 return merge(left, Visit(e->getFalseExpr()));
John McCall31168b02011-06-15 23:02:42 +00003242 }
John McCalle4fe2452011-10-01 01:01:08 +00003243
John McCallfe96e0b2011-11-06 09:01:30 +00003244 /// Look through pseudo-objects.
3245 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
3246 // If we're getting here, we should always have a result.
3247 return Visit(e->getResultExpr());
3248 }
3249
John McCalle4fe2452011-10-01 01:01:08 +00003250 /// Statement expressions are okay if their result expression is okay.
3251 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00003252 return Visit(e->getSubStmt()->body_back());
3253 }
John McCall31168b02011-06-15 23:02:42 +00003254
John McCalle4fe2452011-10-01 01:01:08 +00003255 /// Some declaration references are okay.
3256 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
John McCalle4fe2452011-10-01 01:01:08 +00003257 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
Ben Langmuir443aa4b2015-02-25 20:09:06 +00003258 // References to global constants are okay.
John McCalle4fe2452011-10-01 01:01:08 +00003259 if (isAnyRetainable(TargetClass) &&
3260 isAnyRetainable(SourceClass) &&
3261 var &&
3262 var->getStorageClass() == SC_Extern &&
Ben Langmuir443aa4b2015-02-25 20:09:06 +00003263 var->getType().isConstQualified()) {
3264
3265 // In system headers, they can also be assumed to be immune to retains.
3266 // These are things like 'kCFStringTransformToLatin'.
3267 if (Context.getSourceManager().isInSystemHeader(var->getLocation()))
3268 return ACC_bottom;
3269
3270 return ACC_plusZero;
John McCalle4fe2452011-10-01 01:01:08 +00003271 }
3272
3273 // Nothing else.
3274 return ACC_invalid;
Fariborz Jahanian78876372011-06-21 17:38:29 +00003275 }
John McCalle4fe2452011-10-01 01:01:08 +00003276
3277 /// Some calls are okay.
3278 ACCResult VisitCallExpr(CallExpr *e) {
3279 if (FunctionDecl *fn = e->getDirectCallee())
3280 if (ACCResult result = checkCallToFunction(fn))
3281 return result;
3282
3283 return super::VisitCallExpr(e);
3284 }
3285
3286 ACCResult checkCallToFunction(FunctionDecl *fn) {
3287 // Require a CF*Ref return type.
Alp Toker314cc812014-01-25 16:55:45 +00003288 if (!isCFType(fn->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003289 return ACC_invalid;
3290
3291 if (!isAnyRetainable(TargetClass))
3292 return ACC_invalid;
3293
3294 // Honor an explicit 'not retained' attribute.
3295 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3296 return ACC_plusZero;
3297
3298 // Honor an explicit 'retained' attribute, except that for
3299 // now we're not going to permit implicit handling of +1 results,
3300 // because it's a bit frightening.
3301 if (fn->hasAttr<CFReturnsRetainedAttr>())
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003302 return Diagnose ? ACC_plusOne
3303 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003304
3305 // Recognize this specific builtin function, which is used by CFSTR.
3306 unsigned builtinID = fn->getBuiltinID();
3307 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3308 return ACC_bottom;
3309
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003310 // Otherwise, don't do anything implicit with an unaudited function.
3311 if (!fn->hasAttr<CFAuditedTransferAttr>())
3312 return ACC_invalid;
3313
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003314 // Otherwise, it's +0 unless it follows the create convention.
3315 if (ento::coreFoundation::followsCreateRule(fn))
3316 return Diagnose ? ACC_plusOne
3317 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003318
John McCalle4fe2452011-10-01 01:01:08 +00003319 return ACC_plusZero;
3320 }
3321
3322 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3323 return checkCallToMethod(e->getMethodDecl());
3324 }
3325
3326 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3327 ObjCMethodDecl *method;
3328 if (e->isExplicitProperty())
3329 method = e->getExplicitProperty()->getGetterMethodDecl();
3330 else
3331 method = e->getImplicitPropertyGetter();
3332 return checkCallToMethod(method);
3333 }
3334
3335 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3336 if (!method) return ACC_invalid;
3337
3338 // Check for message sends to functions returning CF types. We
3339 // just obey the Cocoa conventions with these, even though the
3340 // return type is CF.
Alp Toker314cc812014-01-25 16:55:45 +00003341 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003342 return ACC_invalid;
3343
3344 // If the method is explicitly marked not-retained, it's +0.
3345 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3346 return ACC_plusZero;
3347
3348 // If the method is explicitly marked as returning retained, or its
3349 // selector follows a +1 Cocoa convention, treat it as +1.
3350 if (method->hasAttr<CFReturnsRetainedAttr>())
3351 return ACC_plusOne;
3352
3353 switch (method->getSelector().getMethodFamily()) {
3354 case OMF_alloc:
3355 case OMF_copy:
3356 case OMF_mutableCopy:
3357 case OMF_new:
3358 return ACC_plusOne;
3359
3360 default:
3361 // Otherwise, treat it as +0.
3362 return ACC_plusZero;
Fariborz Jahanian9b83be82011-06-21 19:42:38 +00003363 }
3364 }
John McCalle4fe2452011-10-01 01:01:08 +00003365 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003366} // end anonymous namespace
Fariborz Jahanian4ad56862011-06-20 20:54:42 +00003367
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003368bool Sema::isKnownName(StringRef name) {
3369 if (name.empty())
3370 return false;
3371 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003372 Sema::LookupOrdinaryName);
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003373 return LookupName(R, TUScope, false);
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003374}
3375
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003376static void addFixitForObjCARCConversion(Sema &S,
3377 DiagnosticBuilder &DiagB,
3378 Sema::CheckedConversionKind CCK,
3379 SourceLocation afterLParen,
3380 QualType castType,
3381 Expr *castExpr,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003382 Expr *realCast,
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003383 const char *bridgeKeyword,
3384 const char *CFBridgeName) {
3385 // We handle C-style and implicit casts here.
3386 switch (CCK) {
3387 case Sema::CCK_ImplicitConversion:
3388 case Sema::CCK_CStyleCast:
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003389 case Sema::CCK_OtherCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003390 break;
3391 case Sema::CCK_FunctionalCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003392 return;
3393 }
3394
3395 if (CFBridgeName) {
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003396 if (CCK == Sema::CCK_OtherCast) {
3397 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3398 SourceRange range(NCE->getOperatorLoc(),
3399 NCE->getAngleBrackets().getEnd());
3400 SmallString<32> BridgeCall;
3401
3402 SourceManager &SM = S.getSourceManager();
3403 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3404 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3405 BridgeCall += ' ';
3406
3407 BridgeCall += CFBridgeName;
3408 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3409 }
3410 return;
3411 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003412 Expr *castedE = castExpr;
3413 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3414 castedE = CCE->getSubExpr();
3415 castedE = castedE->IgnoreImpCasts();
3416 SourceRange range = castedE->getSourceRange();
Jordan Rose288c4212012-06-07 01:10:31 +00003417
3418 SmallString<32> BridgeCall;
3419
3420 SourceManager &SM = S.getSourceManager();
3421 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3422 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3423 BridgeCall += ' ';
3424
3425 BridgeCall += CFBridgeName;
3426
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003427 if (isa<ParenExpr>(castedE)) {
3428 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003429 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003430 } else {
Jordan Rose288c4212012-06-07 01:10:31 +00003431 BridgeCall += '(';
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003432 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003433 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003434 DiagB.AddFixItHint(FixItHint::CreateInsertion(
Craig Topper07fa1762015-11-15 02:31:46 +00003435 S.getLocForEndOfToken(range.getEnd()),
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003436 ")"));
3437 }
3438 return;
3439 }
3440
3441 if (CCK == Sema::CCK_CStyleCast) {
3442 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003443 } else if (CCK == Sema::CCK_OtherCast) {
3444 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3445 std::string castCode = "(";
3446 castCode += bridgeKeyword;
3447 castCode += castType.getAsString();
3448 castCode += ")";
3449 SourceRange Range(NCE->getOperatorLoc(),
3450 NCE->getAngleBrackets().getEnd());
3451 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3452 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003453 } else {
3454 std::string castCode = "(";
3455 castCode += bridgeKeyword;
3456 castCode += castType.getAsString();
3457 castCode += ")";
3458 Expr *castedE = castExpr->IgnoreImpCasts();
3459 SourceRange range = castedE->getSourceRange();
3460 if (isa<ParenExpr>(castedE)) {
3461 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3462 castCode));
3463 } else {
3464 castCode += "(";
3465 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3466 castCode));
3467 DiagB.AddFixItHint(FixItHint::CreateInsertion(
Craig Topper07fa1762015-11-15 02:31:46 +00003468 S.getLocForEndOfToken(range.getEnd()),
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003469 ")"));
3470 }
3471 }
3472}
3473
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003474template <typename T>
3475static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3476 TypedefNameDecl *TDNDecl = TD->getDecl();
3477 QualType QT = TDNDecl->getUnderlyingType();
3478 if (QT->isPointerType()) {
3479 QT = QT->getPointeeType();
3480 if (const RecordType *RT = QT->getAs<RecordType>())
Fariborz Jahanian9af6a782014-06-11 19:10:46 +00003481 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
Aaron Ballman2084f8f2013-12-19 13:20:36 +00003482 return RD->getAttr<T>();
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003483 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003484 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003485}
3486
3487static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3488 TypedefNameDecl *&TDNDecl) {
3489 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3490 TDNDecl = TD->getDecl();
3491 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3492 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3493 return ObjCBAttr;
3494 T = TDNDecl->getUnderlyingType();
3495 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003496 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003497}
3498
John McCall4124c492011-10-17 18:40:02 +00003499static void
3500diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3501 QualType castType, ARCConversionTypeClass castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003502 Expr *castExpr, Expr *realCast,
3503 ARCConversionTypeClass exprACTC,
John McCall4124c492011-10-17 18:40:02 +00003504 Sema::CheckedConversionKind CCK) {
John McCall31168b02011-06-15 23:02:42 +00003505 SourceLocation loc =
John McCalle4fe2452011-10-01 01:01:08 +00003506 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCall31168b02011-06-15 23:02:42 +00003507
John McCall4124c492011-10-17 18:40:02 +00003508 if (S.makeUnavailableInSystemHeader(loc,
John McCallc6af8c62015-10-28 05:03:19 +00003509 UnavailableAttr::IR_ARCForbiddenConversion))
John McCall31168b02011-06-15 23:02:42 +00003510 return;
John McCall4124c492011-10-17 18:40:02 +00003511
3512 QualType castExprType = castExpr->getType();
Bob Wilsonf5c53b82016-02-13 01:41:41 +00003513 // Defer emitting a diagnostic for bridge-related casts; that will be
3514 // handled by CheckObjCBridgeRelatedConversions.
Craig Topperc3ec1492014-05-26 06:22:03 +00003515 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003516 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3517 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3518 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
Fariborz Jahanian1ad83a32014-06-18 23:22:38 +00003519 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003520 return;
John McCall31168b02011-06-15 23:02:42 +00003521
John McCall640767f2011-06-17 06:50:50 +00003522 unsigned srcKind = 0;
John McCall31168b02011-06-15 23:02:42 +00003523 switch (exprACTC) {
John McCalle4fe2452011-10-01 01:01:08 +00003524 case ACTC_none:
3525 case ACTC_coreFoundation:
3526 case ACTC_voidPtr:
3527 srcKind = (castExprType->isPointerType() ? 1 : 0);
3528 break;
3529 case ACTC_retainable:
3530 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3531 break;
3532 case ACTC_indirectRetainable:
3533 srcKind = 4;
3534 break;
John McCall31168b02011-06-15 23:02:42 +00003535 }
3536
John McCall4124c492011-10-17 18:40:02 +00003537 // Check whether this could be fixed with a bridge cast.
Craig Topper07fa1762015-11-15 02:31:46 +00003538 SourceLocation afterLParen = S.getLocForEndOfToken(castRange.getBegin());
John McCall4124c492011-10-17 18:40:02 +00003539 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCall31168b02011-06-15 23:02:42 +00003540
John McCall4124c492011-10-17 18:40:02 +00003541 // Bridge from an ARC type to a CF type.
3542 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003543
John McCall4124c492011-10-17 18:40:02 +00003544 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3545 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3546 << 2 // of C pointer type
3547 << castExprType
3548 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3549 << castType
3550 << castRange
3551 << castExpr->getSourceRange();
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003552 bool br = S.isKnownName("CFBridgingRelease");
Jordan Rose4502b532012-07-31 01:07:43 +00003553 ACCResult CreateRule =
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003554 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003555 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003556 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003557 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003558 DiagnosticBuilder DiagB =
3559 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3560 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Craig Topperc3ec1492014-05-26 06:22:03 +00003561
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003562 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003563 castType, castExpr, realCast, "__bridge ",
3564 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003565 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003566 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003567 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003568 DiagnosticBuilder DiagB =
3569 (CCK == Sema::CCK_OtherCast && !br) ?
3570 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3571 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3572 diag::note_arc_bridge_transfer)
3573 << castExprType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003574
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003575 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003576 castType, castExpr, realCast, "__bridge_transfer ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003577 br ? "CFBridgingRelease" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003578 }
John McCall4124c492011-10-17 18:40:02 +00003579
3580 return;
3581 }
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003582
John McCall4124c492011-10-17 18:40:02 +00003583 // Bridge from a CF type to an ARC type.
3584 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003585 bool br = S.isKnownName("CFBridgingRetain");
John McCall4124c492011-10-17 18:40:02 +00003586 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3587 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3588 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3589 << castExprType
3590 << 2 // to C pointer type
3591 << castType
3592 << castRange
3593 << castExpr->getSourceRange();
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003594 ACCResult CreateRule =
3595 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003596 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003597 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003598 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003599 DiagnosticBuilder DiagB =
3600 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3601 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003602 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003603 castType, castExpr, realCast, "__bridge ",
3604 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003605 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003606 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003607 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003608 DiagnosticBuilder DiagB =
3609 (CCK == Sema::CCK_OtherCast && !br) ?
3610 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3611 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3612 diag::note_arc_bridge_retained)
3613 << castType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003614
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003615 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003616 castType, castExpr, realCast, "__bridge_retained ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003617 br ? "CFBridgingRetain" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003618 }
John McCall4124c492011-10-17 18:40:02 +00003619
3620 return;
John McCall31168b02011-06-15 23:02:42 +00003621 }
3622
John McCall4124c492011-10-17 18:40:02 +00003623 S.Diag(loc, diag::err_arc_mismatched_cast)
3624 << (CCK != Sema::CCK_ImplicitConversion)
3625 << srcKind << castExprType << castType
John McCall31168b02011-06-15 23:02:42 +00003626 << castRange << castExpr->getSourceRange();
3627}
3628
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003629template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003630static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3631 bool &HadTheAttribute, bool warn) {
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003632 QualType T = castExpr->getType();
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003633 HadTheAttribute = false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003634 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3635 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003636 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003637 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003638 HadTheAttribute = true;
Fariborz Jahanianc9e266b2014-12-11 22:56:26 +00003639 if (Parm->isStr("id"))
3640 return true;
3641
Craig Topperc3ec1492014-05-26 06:22:03 +00003642 NamedDecl *Target = nullptr;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003643 // Check for an existing type with this name.
3644 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3645 Sema::LookupOrdinaryName);
3646 if (S.LookupName(R, S.TUScope)) {
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003647 Target = R.getFoundDecl();
3648 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3649 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3650 if (const ObjCObjectPointerType *InterfacePointerType =
3651 castType->getAsObjCInterfacePointerType()) {
3652 ObjCInterfaceDecl *CastClass
3653 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003654 if ((CastClass == ExprClass) ||
Fariborz Jahanian27aa9b42015-04-10 22:07:47 +00003655 (CastClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003656 return true;
3657 if (warn)
3658 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3659 << T << Target->getName() << castType->getPointeeType();
3660 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003661 } else if (castType->isObjCIdType() ||
3662 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3663 castType, ExprClass)))
3664 // ok to cast to 'id'.
3665 // casting to id<p-list> is ok if bridge type adopts all of
3666 // p-list protocols.
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)
3671 << T << Target->getName() << castType;
3672 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3673 S.Diag(Target->getLocStart(), diag::note_declared_at);
3674 }
3675 return false;
Fariborz Jahanian2c312122013-11-16 23:22:37 +00003676 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003677 }
Fariborz Jahanian696c8872015-04-09 23:39:53 +00003678 } else if (!castType->isObjCIdType()) {
3679 S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface)
3680 << castExpr->getType() << Parm;
3681 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3682 if (Target)
3683 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003684 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003685 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003686 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003687 return false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003688 }
3689 T = TDNDecl->getUnderlyingType();
3690 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003691 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003692}
3693
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003694template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003695static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
3696 bool &HadTheAttribute, bool warn) {
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003697 QualType T = castType;
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003698 HadTheAttribute = false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003699 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3700 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003701 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003702 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003703 HadTheAttribute = true;
John McCallaf6b3f82015-03-10 18:41:23 +00003704 if (Parm->isStr("id"))
3705 return true;
3706
Craig Topperc3ec1492014-05-26 06:22:03 +00003707 NamedDecl *Target = nullptr;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003708 // Check for an existing type with this name.
3709 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3710 Sema::LookupOrdinaryName);
3711 if (S.LookupName(R, S.TUScope)) {
3712 Target = R.getFoundDecl();
3713 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3714 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3715 if (const ObjCObjectPointerType *InterfacePointerType =
3716 castExpr->getType()->getAsObjCInterfacePointerType()) {
3717 ObjCInterfaceDecl *ExprClass
3718 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003719 if ((CastClass == ExprClass) ||
3720 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003721 return true;
3722 if (warn) {
3723 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3724 << castExpr->getType()->getPointeeType() << T;
3725 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3726 }
3727 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003728 } else if (castExpr->getType()->isObjCIdType() ||
3729 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3730 castExpr->getType(), CastClass)))
3731 // ok to cast an 'id' expression to a CFtype.
3732 // ok to cast an 'id<plist>' expression to CFtype provided plist
3733 // adopts all of CFtype's ObjetiveC's class plist.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003734 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003735 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003736 if (warn) {
3737 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3738 << castExpr->getType() << castType;
3739 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3740 S.Diag(Target->getLocStart(), diag::note_declared_at);
3741 }
3742 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003743 }
3744 }
3745 }
3746 S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject)
3747 << castExpr->getType() << castType;
3748 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3749 if (Target)
3750 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003751 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003752 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003753 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003754 }
3755 T = TDNDecl->getUnderlyingType();
3756 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003757 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003758}
3759
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003760void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003761 if (!getLangOpts().ObjC1)
3762 return;
Alp Tokerf6a24ce2013-12-05 16:25:25 +00003763 // warn in presence of __bridge casting to or from a toll free bridge cast.
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003764 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3765 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003766 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003767 bool HasObjCBridgeAttr;
3768 bool ObjCBridgeAttrWillNotWarn =
3769 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3770 false);
3771 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3772 return;
3773 bool HasObjCBridgeMutableAttr;
3774 bool ObjCBridgeMutableAttrWillNotWarn =
3775 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3776 HasObjCBridgeMutableAttr, false);
3777 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3778 return;
3779
3780 if (HasObjCBridgeAttr)
3781 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3782 true);
3783 else if (HasObjCBridgeMutableAttr)
3784 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3785 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003786 }
3787 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003788 bool HasObjCBridgeAttr;
3789 bool ObjCBridgeAttrWillNotWarn =
3790 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3791 false);
3792 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3793 return;
3794 bool HasObjCBridgeMutableAttr;
3795 bool ObjCBridgeMutableAttrWillNotWarn =
3796 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3797 HasObjCBridgeMutableAttr, false);
3798 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3799 return;
3800
3801 if (HasObjCBridgeAttr)
3802 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3803 true);
3804 else if (HasObjCBridgeMutableAttr)
3805 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3806 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003807 }
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003808}
3809
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003810void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
3811 QualType SrcType = castExpr->getType();
3812 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
3813 if (PRE->isExplicitProperty()) {
3814 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
3815 SrcType = PDecl->getType();
3816 }
3817 else if (PRE->isImplicitProperty()) {
3818 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
3819 SrcType = Getter->getReturnType();
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003820 }
3821 }
3822
3823 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
3824 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
3825 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
3826 return;
3827 CheckObjCBridgeRelatedConversions(castExpr->getLocStart(),
3828 castType, SrcType, castExpr);
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003829}
3830
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00003831bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
3832 CastKind &Kind) {
3833 if (!getLangOpts().ObjC1)
3834 return false;
3835 ARCConversionTypeClass exprACTC =
3836 classifyTypeForARCConversion(castExpr->getType());
3837 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3838 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
3839 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
3840 CheckTollFreeBridgeCast(castType, castExpr);
3841 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
3842 : CK_CPointerToObjCPointerCast;
3843 return true;
3844 }
3845 return false;
3846}
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003847
3848bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
3849 QualType DestType, QualType SrcType,
3850 ObjCInterfaceDecl *&RelatedClass,
3851 ObjCMethodDecl *&ClassMethod,
3852 ObjCMethodDecl *&InstanceMethod,
3853 TypedefNameDecl *&TDNDecl,
George Burgess IV60bc9722016-01-13 23:36:34 +00003854 bool CfToNs, bool Diagnose) {
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003855 QualType T = CfToNs ? SrcType : DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003856 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
3857 if (!ObjCBAttr)
3858 return false;
3859
3860 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
3861 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
3862 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
3863 if (!RCId)
3864 return false;
Craig Topperc3ec1492014-05-26 06:22:03 +00003865 NamedDecl *Target = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003866 // Check for an existing type with this name.
3867 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
3868 Sema::LookupOrdinaryName);
3869 if (!LookupName(R, TUScope)) {
George Burgess IV60bc9722016-01-13 23:36:34 +00003870 if (Diagnose) {
3871 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
3872 << SrcType << DestType;
3873 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3874 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003875 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003876 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003877 Target = R.getFoundDecl();
3878 if (Target && isa<ObjCInterfaceDecl>(Target))
3879 RelatedClass = cast<ObjCInterfaceDecl>(Target);
3880 else {
George Burgess IV60bc9722016-01-13 23:36:34 +00003881 if (Diagnose) {
3882 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
3883 << SrcType << DestType;
3884 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3885 if (Target)
3886 Diag(Target->getLocStart(), diag::note_declared_at);
3887 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003888 return false;
3889 }
3890
3891 // Check for an existing class method with the given selector name.
3892 if (CfToNs && CMId) {
3893 Selector Sel = Context.Selectors.getUnarySelector(CMId);
3894 ClassMethod = RelatedClass->lookupMethod(Sel, false);
3895 if (!ClassMethod) {
George Burgess IV60bc9722016-01-13 23:36:34 +00003896 if (Diagnose) {
3897 Diag(Loc, diag::err_objc_bridged_related_known_method)
3898 << SrcType << DestType << Sel << false;
3899 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3900 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003901 return false;
3902 }
3903 }
3904
3905 // Check for an existing instance method with the given selector name.
3906 if (!CfToNs && IMId) {
3907 Selector Sel = Context.Selectors.getNullarySelector(IMId);
3908 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
3909 if (!InstanceMethod) {
George Burgess IV60bc9722016-01-13 23:36:34 +00003910 if (Diagnose) {
3911 Diag(Loc, diag::err_objc_bridged_related_known_method)
3912 << SrcType << DestType << Sel << true;
3913 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3914 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003915 return false;
3916 }
3917 }
3918 return true;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003919}
3920
3921bool
3922Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003923 QualType DestType, QualType SrcType,
George Burgess IV60bc9722016-01-13 23:36:34 +00003924 Expr *&SrcExpr, bool Diagnose) {
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003925 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
3926 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
3927 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
3928 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
3929 if (!CfToNs && !NsToCf)
3930 return false;
3931
3932 ObjCInterfaceDecl *RelatedClass;
Craig Topperc3ec1492014-05-26 06:22:03 +00003933 ObjCMethodDecl *ClassMethod = nullptr;
3934 ObjCMethodDecl *InstanceMethod = nullptr;
3935 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003936 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
George Burgess IV60bc9722016-01-13 23:36:34 +00003937 ClassMethod, InstanceMethod, TDNDecl,
3938 CfToNs, Diagnose))
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003939 return false;
3940
3941 if (CfToNs) {
3942 // Implicit conversion from CF to ObjC object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003943 if (ClassMethod) {
George Burgess IV60bc9722016-01-13 23:36:34 +00003944 if (Diagnose) {
3945 std::string ExpressionString = "[";
3946 ExpressionString += RelatedClass->getNameAsString();
3947 ExpressionString += " ";
3948 ExpressionString += ClassMethod->getSelector().getAsString();
3949 SourceLocation SrcExprEndLoc = getLocForEndOfToken(SrcExpr->getLocEnd());
3950 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
3951 Diag(Loc, diag::err_objc_bridged_related_known_method)
3952 << SrcType << DestType << ClassMethod->getSelector() << false
3953 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString)
3954 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
3955 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3956 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003957
Bob Wilsonf5c53b82016-02-13 01:41:41 +00003958 QualType receiverType = Context.getObjCInterfaceType(RelatedClass);
3959 // Argument.
3960 Expr *args[] = { SrcExpr };
3961 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003962 ClassMethod->getLocation(),
3963 ClassMethod->getSelector(), ClassMethod,
3964 MultiExprArg(args, 1));
Bob Wilsonf5c53b82016-02-13 01:41:41 +00003965 SrcExpr = msg.get();
3966 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003967 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003968 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003969 }
3970 else {
3971 // Implicit conversion from ObjC type to CF object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003972 if (InstanceMethod) {
George Burgess IV60bc9722016-01-13 23:36:34 +00003973 if (Diagnose) {
3974 std::string ExpressionString;
3975 SourceLocation SrcExprEndLoc =
3976 getLocForEndOfToken(SrcExpr->getLocEnd());
3977 if (InstanceMethod->isPropertyAccessor())
3978 if (const ObjCPropertyDecl *PDecl =
3979 InstanceMethod->findPropertyDecl()) {
3980 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
3981 ExpressionString = ".";
3982 ExpressionString += PDecl->getNameAsString();
3983 Diag(Loc, diag::err_objc_bridged_related_known_method)
3984 << SrcType << DestType << InstanceMethod->getSelector() << true
3985 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3986 }
3987 if (ExpressionString.empty()) {
3988 // Provide a fixit: [ObjectExpr InstanceMethod]
3989 ExpressionString = " ";
3990 ExpressionString += InstanceMethod->getSelector().getAsString();
3991 ExpressionString += "]";
3992
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003993 Diag(Loc, diag::err_objc_bridged_related_known_method)
George Burgess IV60bc9722016-01-13 23:36:34 +00003994 << SrcType << DestType << InstanceMethod->getSelector() << true
3995 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[")
3996 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003997 }
George Burgess IV60bc9722016-01-13 23:36:34 +00003998 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3999 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00004000
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004001 ExprResult msg =
4002 BuildInstanceMessageImplicit(SrcExpr, SrcType,
4003 InstanceMethod->getLocation(),
4004 InstanceMethod->getSelector(),
4005 InstanceMethod, None);
4006 SrcExpr = msg.get();
4007 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00004008 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00004009 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004010 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00004011 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004012}
4013
John McCall4124c492011-10-17 18:40:02 +00004014Sema::ARCConversionResult
4015Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanian25eef192013-07-31 21:40:51 +00004016 Expr *&castExpr, CheckedConversionKind CCK,
George Burgess IV60bc9722016-01-13 23:36:34 +00004017 bool Diagnose,
Fariborz Jahanianc03ef572014-06-18 23:52:49 +00004018 bool DiagnoseCFAudited,
4019 BinaryOperatorKind Opc) {
John McCall4124c492011-10-17 18:40:02 +00004020 QualType castExprType = castExpr->getType();
4021
4022 // For the purposes of the classification, we assume reference types
4023 // will bind to temporaries.
4024 QualType effCastType = castType;
4025 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
4026 effCastType = ref->getPointeeType();
4027
4028 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
4029 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00004030 if (exprACTC == castACTC) {
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004031 // Check for viability and report error if casting an rvalue to a
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00004032 // life-time qualifier.
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004033 if (castACTC == ACTC_retainable &&
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00004034 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
George Burgess IV60bc9722016-01-13 23:36:34 +00004035 castType != castExprType) {
Fariborz Jahanian244b1872011-10-29 00:06:10 +00004036 const Type *DT = castType.getTypePtr();
4037 QualType QDT = castType;
4038 // We desugar some types but not others. We ignore those
4039 // that cannot happen in a cast; i.e. auto, and those which
4040 // should not be de-sugared; i.e typedef.
4041 if (const ParenType *PT = dyn_cast<ParenType>(DT))
4042 QDT = PT->desugar();
4043 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
4044 QDT = TP->desugar();
4045 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
4046 QDT = AT->desugar();
4047 if (QDT != castType &&
4048 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004049 if (Diagnose) {
4050 SourceLocation loc = (castRange.isValid() ? castRange.getBegin()
4051 : castExpr->getExprLoc());
4052 Diag(loc, diag::err_arc_nolifetime_behavior);
4053 }
4054 return ACR_error;
Fariborz Jahanian244b1872011-10-29 00:06:10 +00004055 }
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00004056 }
4057 return ACR_okay;
4058 }
4059
John McCall4124c492011-10-17 18:40:02 +00004060 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
4061
4062 // Allow all of these types to be cast to integer types (but not
4063 // vice-versa).
4064 if (castACTC == ACTC_none && castType->isIntegralType(Context))
4065 return ACR_okay;
4066
4067 // Allow casts between pointers to lifetime types (e.g., __strong id*)
4068 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
4069 // must be explicit.
4070 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
4071 return ACR_okay;
4072 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
4073 CCK != CCK_ImplicitConversion)
4074 return ACR_okay;
4075
Fariborz Jahanian36986c62012-07-27 22:37:07 +00004076 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
John McCall4124c492011-10-17 18:40:02 +00004077 // For invalid casts, fall through.
4078 case ACC_invalid:
4079 break;
4080
4081 // Do nothing for both bottom and +0.
4082 case ACC_bottom:
4083 case ACC_plusZero:
4084 return ACR_okay;
4085
4086 // If the result is +1, consume it here.
4087 case ACC_plusOne:
4088 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
4089 CK_ARCConsumeObject, castExpr,
Craig Topperc3ec1492014-05-26 06:22:03 +00004090 nullptr, VK_RValue);
Tim Shen4a05bb82016-06-21 20:29:17 +00004091 Cleanup.setExprNeedsCleanups(true);
John McCall4124c492011-10-17 18:40:02 +00004092 return ACR_okay;
4093 }
4094
4095 // If this is a non-implicit cast from id or block type to a
4096 // CoreFoundation type, delay complaining in case the cast is used
4097 // in an acceptable context.
4098 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
4099 CCK != CCK_ImplicitConversion)
4100 return ACR_unbridged;
4101
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004102 // Issue a diagnostic about a missing @-sign when implicit casting a cstring
4103 // to 'NSString *', instead of falling through to report a "bridge cast"
4104 // diagnostic.
Fariborz Jahanian283bf892013-12-18 21:04:43 +00004105 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
George Burgess IV60bc9722016-01-13 23:36:34 +00004106 ConversionToObjCStringLiteralCheck(castType, castExpr, Diagnose))
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004107 return ACR_error;
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00004108
Fariborz Jahanian25eef192013-07-31 21:40:51 +00004109 // Do not issue "bridge cast" diagnostic when implicit casting
4110 // a retainable object to a CF type parameter belonging to an audited
4111 // CF API function. Let caller issue a normal type mismatched diagnostic
4112 // instead.
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004113 if ((!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
4114 castACTC != ACTC_coreFoundation) &&
4115 !(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
4116 (Opc == BO_NE || Opc == BO_EQ))) {
4117 if (Diagnose)
George Burgess IV60bc9722016-01-13 23:36:34 +00004118 diagnoseObjCARCConversion(*this, castRange, castType, castACTC, castExpr,
4119 castExpr, exprACTC, CCK);
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004120 return ACR_error;
4121 }
John McCall4124c492011-10-17 18:40:02 +00004122 return ACR_okay;
4123}
4124
4125/// Given that we saw an expression with the ARCUnbridgedCastTy
4126/// placeholder type, complain bitterly.
4127void Sema::diagnoseARCUnbridgedCast(Expr *e) {
4128 // We expect the spurious ImplicitCastExpr to already have been stripped.
4129 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4130 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
4131
4132 SourceRange castRange;
4133 QualType castType;
4134 CheckedConversionKind CCK;
4135
4136 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
4137 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
4138 castType = cast->getTypeAsWritten();
4139 CCK = CCK_CStyleCast;
4140 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
4141 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
4142 castType = cast->getTypeAsWritten();
4143 CCK = CCK_OtherCast;
4144 } else {
4145 castType = cast->getType();
4146 CCK = CCK_ImplicitConversion;
4147 }
4148
4149 ARCConversionTypeClass castACTC =
4150 classifyTypeForARCConversion(castType.getNonReferenceType());
4151
4152 Expr *castExpr = realCast->getSubExpr();
4153 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
4154
4155 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00004156 castExpr, realCast, ACTC_retainable, CCK);
John McCall4124c492011-10-17 18:40:02 +00004157}
4158
4159/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
4160/// type, remove the placeholder cast.
4161Expr *Sema::stripARCUnbridgedCast(Expr *e) {
4162 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4163
4164 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
4165 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
4166 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
4167 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
4168 assert(uo->getOpcode() == UO_Extension);
4169 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
4170 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
4171 sub->getValueKind(), sub->getObjectKind(),
4172 uo->getOperatorLoc());
4173 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
4174 assert(!gse->isResultDependent());
4175
4176 unsigned n = gse->getNumAssocs();
4177 SmallVector<Expr*, 4> subExprs(n);
4178 SmallVector<TypeSourceInfo*, 4> subTypes(n);
4179 for (unsigned i = 0; i != n; ++i) {
4180 subTypes[i] = gse->getAssocTypeSourceInfo(i);
4181 Expr *sub = gse->getAssocExpr(i);
4182 if (i == gse->getResultIndex())
4183 sub = stripARCUnbridgedCast(sub);
4184 subExprs[i] = sub;
4185 }
4186
4187 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
4188 gse->getControllingExpr(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00004189 subTypes, subExprs,
4190 gse->getDefaultLoc(),
John McCall4124c492011-10-17 18:40:02 +00004191 gse->getRParenLoc(),
4192 gse->containsUnexpandedParameterPack(),
4193 gse->getResultIndex());
4194 } else {
4195 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
4196 return cast<ImplicitCastExpr>(e)->getSubExpr();
4197 }
4198}
4199
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004200bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
4201 QualType exprType) {
4202 QualType canCastType =
4203 Context.getCanonicalType(castType).getUnqualifiedType();
4204 QualType canExprType =
4205 Context.getCanonicalType(exprType).getUnqualifiedType();
4206 if (isa<ObjCObjectPointerType>(canCastType) &&
4207 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
4208 canExprType->isObjCObjectPointerType()) {
4209 if (const ObjCObjectPointerType *ObjT =
4210 canExprType->getAs<ObjCObjectPointerType>())
Richard Smith802c4b72012-08-23 06:16:52 +00004211 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
4212 return !ObjI->isArcWeakrefUnavailable();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004213 }
4214 return true;
4215}
4216
John McCall4db5c3c2011-07-07 06:58:02 +00004217/// Look for an ObjCReclaimReturnedObject cast and destroy it.
4218static Expr *maybeUndoReclaimObject(Expr *e) {
4219 // For now, we just undo operands that are *immediately* reclaim
4220 // expressions, which prevents the vast majority of potential
4221 // problems here. To catch them all, we'd need to rebuild arbitrary
4222 // value-propagating subexpressions --- we can't reliably rebuild
4223 // in-place because of expression sharing.
4224 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall2d637d22011-09-10 06:18:15 +00004225 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall4db5c3c2011-07-07 06:58:02 +00004226 return ice->getSubExpr();
4227
4228 return e;
4229}
4230
John McCall31168b02011-06-15 23:02:42 +00004231ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
4232 ObjCBridgeCastKind Kind,
4233 SourceLocation BridgeKeywordLoc,
4234 TypeSourceInfo *TSInfo,
4235 Expr *SubExpr) {
John McCalleb075542011-08-26 00:48:42 +00004236 ExprResult SubResult = UsualUnaryConversions(SubExpr);
4237 if (SubResult.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004238 SubExpr = SubResult.get();
John McCalleb075542011-08-26 00:48:42 +00004239
John McCall31168b02011-06-15 23:02:42 +00004240 QualType T = TSInfo->getType();
4241 QualType FromType = SubExpr->getType();
4242
John McCall9320b872011-09-09 05:25:32 +00004243 CastKind CK;
4244
John McCall31168b02011-06-15 23:02:42 +00004245 bool MustConsume = false;
4246 if (T->isDependentType() || SubExpr->isTypeDependent()) {
4247 // Okay: we'll build a dependent expression type.
John McCall9320b872011-09-09 05:25:32 +00004248 CK = CK_Dependent;
John McCall31168b02011-06-15 23:02:42 +00004249 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
4250 // Casting CF -> id
John McCall9320b872011-09-09 05:25:32 +00004251 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
4252 : CK_CPointerToObjCPointerCast);
John McCall31168b02011-06-15 23:02:42 +00004253 switch (Kind) {
4254 case OBC_Bridge:
4255 break;
4256
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004257 case OBC_BridgeRetained: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00004258 bool br = isKnownName("CFBridgingRelease");
John McCall31168b02011-06-15 23:02:42 +00004259 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4260 << 2
4261 << FromType
4262 << (T->isBlockPointerType()? 1 : 0)
4263 << T
4264 << SubExpr->getSourceRange()
4265 << Kind;
4266 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4267 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
4268 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004269 << FromType << br
John McCall31168b02011-06-15 23:02:42 +00004270 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004271 br ? "CFBridgingRelease "
4272 : "__bridge_transfer ");
John McCall31168b02011-06-15 23:02:42 +00004273
4274 Kind = OBC_Bridge;
4275 break;
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004276 }
John McCall31168b02011-06-15 23:02:42 +00004277
4278 case OBC_BridgeTransfer:
4279 // We must consume the Objective-C object produced by the cast.
4280 MustConsume = true;
4281 break;
4282 }
4283 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
4284 // Okay: id -> CF
John McCall9320b872011-09-09 05:25:32 +00004285 CK = CK_BitCast;
John McCall31168b02011-06-15 23:02:42 +00004286 switch (Kind) {
Fariborz Jahanian214567c2014-10-28 17:26:21 +00004287 case OBC_Bridge:
4288 // Reclaiming a value that's going to be __bridge-casted to CF
4289 // is very dangerous, so we don't do it.
4290 SubExpr = maybeUndoReclaimObject(SubExpr);
4291 break;
John McCall31168b02011-06-15 23:02:42 +00004292
4293 case OBC_BridgeRetained:
4294 // Produce the object before casting it.
4295 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall2d637d22011-09-10 06:18:15 +00004296 CK_ARCProduceObject,
Craig Topperc3ec1492014-05-26 06:22:03 +00004297 SubExpr, nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004298 break;
4299
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004300 case OBC_BridgeTransfer: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00004301 bool br = isKnownName("CFBridgingRetain");
John McCall31168b02011-06-15 23:02:42 +00004302 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4303 << (FromType->isBlockPointerType()? 1 : 0)
4304 << FromType
4305 << 2
4306 << T
4307 << SubExpr->getSourceRange()
4308 << Kind;
4309
4310 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4311 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
4312 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004313 << T << br
4314 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4315 br ? "CFBridgingRetain " : "__bridge_retained");
John McCall31168b02011-06-15 23:02:42 +00004316
4317 Kind = OBC_Bridge;
4318 break;
4319 }
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004320 }
John McCall31168b02011-06-15 23:02:42 +00004321 } else {
4322 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
4323 << FromType << T << Kind
4324 << SubExpr->getSourceRange()
4325 << TSInfo->getTypeLoc().getSourceRange();
4326 return ExprError();
4327 }
4328
John McCall9320b872011-09-09 05:25:32 +00004329 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCall31168b02011-06-15 23:02:42 +00004330 BridgeKeywordLoc,
4331 TSInfo, SubExpr);
4332
4333 if (MustConsume) {
Tim Shen4a05bb82016-06-21 20:29:17 +00004334 Cleanup.setExprNeedsCleanups(true);
John McCall2d637d22011-09-10 06:18:15 +00004335 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
Craig Topperc3ec1492014-05-26 06:22:03 +00004336 nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004337 }
4338
4339 return Result;
4340}
4341
4342ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
4343 SourceLocation LParenLoc,
4344 ObjCBridgeCastKind Kind,
4345 SourceLocation BridgeKeywordLoc,
4346 ParsedType Type,
4347 SourceLocation RParenLoc,
4348 Expr *SubExpr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004349 TypeSourceInfo *TSInfo = nullptr;
John McCall31168b02011-06-15 23:02:42 +00004350 QualType T = GetTypeFromParser(Type, &TSInfo);
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00004351 if (Kind == OBC_Bridge)
4352 CheckTollFreeBridgeCast(T, SubExpr);
John McCall31168b02011-06-15 23:02:42 +00004353 if (!TSInfo)
4354 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
4355 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
4356 SubExpr);
4357}