blob: 6a725c485d57e2481d5b39b6b263a0d3fd86f7bd [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;
Alex Lorenz49370ac2017-11-08 21:33:15 +0000567 // Transfer the nullability from method's return type.
568 Optional<NullabilityKind> Nullability =
569 BoxingMethod->getReturnType()->getNullability(Context);
570 if (Nullability)
571 BoxedType = Context.getAttributedType(
572 AttributedType::getNullabilityAttrKind(*Nullability), BoxedType,
573 BoxedType);
Patrick Beard0caa3942012-04-19 00:25:12 +0000574 }
Patrick Beard2565c592012-05-01 21:47:19 +0000575 } else if (ValueType->isBuiltinType()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000576 // The other types we support are numeric, char and BOOL/bool. We could also
577 // provide limited support for structure types, such as NSRange, NSRect, and
578 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
579 // for more details.
580
581 // Check for a top-level character literal.
582 if (const CharacterLiteral *Char =
583 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
584 // In C, character literals have type 'int'. That's not the type we want
585 // to use to determine the Objective-c literal kind.
586 switch (Char->getKind()) {
587 case CharacterLiteral::Ascii:
Aaron Ballman9a17c852016-01-07 20:59:26 +0000588 case CharacterLiteral::UTF8:
Patrick Beard0caa3942012-04-19 00:25:12 +0000589 ValueType = Context.CharTy;
590 break;
591
592 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000593 ValueType = Context.getWideCharType();
Patrick Beard0caa3942012-04-19 00:25:12 +0000594 break;
595
596 case CharacterLiteral::UTF16:
597 ValueType = Context.Char16Ty;
598 break;
599
600 case CharacterLiteral::UTF32:
601 ValueType = Context.Char32Ty;
602 break;
603 }
604 }
Patrick Beard0caa3942012-04-19 00:25:12 +0000605 // FIXME: Do I need to do anything special with BoolTy expressions?
606
607 // Look for the appropriate method within NSNumber.
Alex Denisovb7d85632015-07-24 05:09:40 +0000608 BoxingMethod = getNSNumberFactoryMethod(*this, Loc, ValueType);
Patrick Beard0caa3942012-04-19 00:25:12 +0000609 BoxedType = NSNumberPointer;
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000610 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
611 if (!ET->getDecl()->isComplete()) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000612 Diag(Loc, diag::err_objc_incomplete_boxed_expression_type)
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000613 << ValueType << ValueExpr->getSourceRange();
614 return ExprError();
615 }
616
Alex Denisovb7d85632015-07-24 05:09:40 +0000617 BoxingMethod = getNSNumberFactoryMethod(*this, Loc,
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000618 ET->getDecl()->getIntegerType());
619 BoxedType = NSNumberPointer;
Alex Denisovfde64952015-06-26 05:28:36 +0000620 } else if (ValueType->isObjCBoxableRecordType()) {
621 // Support for structure types, that marked as objc_boxable
622 // struct __attribute__((objc_boxable)) s { ... };
623
624 // Look up the NSValue class, if we haven't done so already. It's cached
625 // in the Sema instance.
626 if (!NSValueDecl) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000627 NSValueDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
628 Sema::LK_Boxed);
Alex Denisovfde64952015-06-26 05:28:36 +0000629 if (!NSValueDecl) {
Alex Denisovfde64952015-06-26 05:28:36 +0000630 return ExprError();
631 }
Alex Denisovb7d85632015-07-24 05:09:40 +0000632
Alex Denisovfde64952015-06-26 05:28:36 +0000633 // generate the pointer to NSValue type.
634 QualType NSValueObject = Context.getObjCInterfaceType(NSValueDecl);
635 NSValuePointer = Context.getObjCObjectPointerType(NSValueObject);
636 }
637
638 if (!ValueWithBytesObjCTypeMethod) {
639 IdentifierInfo *II[] = {
640 &Context.Idents.get("valueWithBytes"),
641 &Context.Idents.get("objCType")
642 };
643 Selector ValueWithBytesObjCType = Context.Selectors.getSelector(2, II);
644
645 // Look for the appropriate method within NSValue.
646 BoxingMethod = NSValueDecl->lookupClassMethod(ValueWithBytesObjCType);
647 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
648 // Debugger needs to work even if NSValue hasn't been defined.
649 TypeSourceInfo *ReturnTInfo = nullptr;
650 ObjCMethodDecl *M = ObjCMethodDecl::Create(
651 Context,
652 SourceLocation(),
653 SourceLocation(),
654 ValueWithBytesObjCType,
655 NSValuePointer,
656 ReturnTInfo,
657 NSValueDecl,
658 /*isInstance=*/false,
659 /*isVariadic=*/false,
660 /*isPropertyAccessor=*/false,
661 /*isImplicitlyDeclared=*/true,
662 /*isDefined=*/false,
663 ObjCMethodDecl::Required,
664 /*HasRelatedResultType=*/false);
665
666 SmallVector<ParmVarDecl *, 2> Params;
667
668 ParmVarDecl *bytes =
669 ParmVarDecl::Create(Context, M,
670 SourceLocation(), SourceLocation(),
671 &Context.Idents.get("bytes"),
672 Context.VoidPtrTy.withConst(),
673 /*TInfo=*/nullptr,
674 SC_None, nullptr);
675 Params.push_back(bytes);
676
677 QualType ConstCharType = Context.CharTy.withConst();
678 ParmVarDecl *type =
679 ParmVarDecl::Create(Context, M,
680 SourceLocation(), SourceLocation(),
681 &Context.Idents.get("type"),
682 Context.getPointerType(ConstCharType),
683 /*TInfo=*/nullptr,
684 SC_None, nullptr);
685 Params.push_back(type);
686
687 M->setMethodParams(Context, Params, None);
688 BoxingMethod = M;
689 }
690
Alex Denisovb7d85632015-07-24 05:09:40 +0000691 if (!validateBoxingMethod(*this, Loc, NSValueDecl,
Alex Denisovfde64952015-06-26 05:28:36 +0000692 ValueWithBytesObjCType, BoxingMethod))
693 return ExprError();
694
695 ValueWithBytesObjCTypeMethod = BoxingMethod;
696 }
697
698 if (!ValueType.isTriviallyCopyableType(Context)) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000699 Diag(Loc, diag::err_objc_non_trivially_copyable_boxed_expression_type)
Alex Denisovfde64952015-06-26 05:28:36 +0000700 << ValueType << ValueExpr->getSourceRange();
701 return ExprError();
702 }
703
704 BoxingMethod = ValueWithBytesObjCTypeMethod;
705 BoxedType = NSValuePointer;
Patrick Beard0caa3942012-04-19 00:25:12 +0000706 }
707
708 if (!BoxingMethod) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000709 Diag(Loc, diag::err_objc_illegal_boxed_expression_type)
Patrick Beard0caa3942012-04-19 00:25:12 +0000710 << ValueType << ValueExpr->getSourceRange();
711 return ExprError();
712 }
713
Alex Denisovb7d85632015-07-24 05:09:40 +0000714 DiagnoseUseOfDecl(BoxingMethod, Loc);
Alex Denisovfde64952015-06-26 05:28:36 +0000715
716 ExprResult ConvertedValueExpr;
717 if (ValueType->isObjCBoxableRecordType()) {
718 InitializedEntity IE = InitializedEntity::InitializeTemporary(ValueType);
719 ConvertedValueExpr = PerformCopyInitialization(IE, ValueExpr->getExprLoc(),
720 ValueExpr);
721 } else {
722 // Convert the expression to the type that the parameter requires.
723 ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
724 InitializedEntity IE = InitializedEntity::InitializeParameter(Context,
725 ParamDecl);
726 ConvertedValueExpr = PerformCopyInitialization(IE, SourceLocation(),
727 ValueExpr);
728 }
729
Patrick Beard0caa3942012-04-19 00:25:12 +0000730 if (ConvertedValueExpr.isInvalid())
731 return ExprError();
732 ValueExpr = ConvertedValueExpr.get();
733
734 ObjCBoxedExpr *BoxedExpr =
735 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
736 BoxingMethod, SR);
737 return MaybeBindToTemporary(BoxedExpr);
738}
739
John McCallf2538342012-07-31 05:14:30 +0000740/// Build an ObjC subscript pseudo-object expression, given that
741/// that's supported by the runtime.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000742ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
743 Expr *IndexExpr,
744 ObjCMethodDecl *getterMethod,
745 ObjCMethodDecl *setterMethod) {
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +0000746 assert(!LangOpts.isSubscriptPointerArithmetic());
John McCall5fb5df92012-06-20 06:18:46 +0000747
John McCallf2538342012-07-31 05:14:30 +0000748 // We can't get dependent types here; our callers should have
749 // filtered them out.
750 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
751 "base or index cannot have dependent type here");
752
753 // Filter out placeholders in the index. In theory, overloads could
754 // be preserved here, although that might not actually work correctly.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000755 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
756 if (Result.isInvalid())
757 return ExprError();
758 IndexExpr = Result.get();
759
John McCallf2538342012-07-31 05:14:30 +0000760 // Perform lvalue-to-rvalue conversion on the base.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000761 Result = DefaultLvalueConversion(BaseExpr);
762 if (Result.isInvalid())
763 return ExprError();
764 BaseExpr = Result.get();
John McCallf2538342012-07-31 05:14:30 +0000765
766 // Build the pseudo-object expression.
James Y Knight6c2f06b2015-12-31 04:43:19 +0000767 return new (Context) ObjCSubscriptRefExpr(
768 BaseExpr, IndexExpr, Context.PseudoObjectTy, VK_LValue, OK_ObjCSubscript,
769 getterMethod, setterMethod, RB);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000770}
771
772ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000773 SourceLocation Loc = SR.getBegin();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000774
Alex Denisovb7d85632015-07-24 05:09:40 +0000775 if (!NSArrayDecl) {
776 NSArrayDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
777 Sema::LK_Array);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000778 if (!NSArrayDecl) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000779 return ExprError();
780 }
781 }
Alex Denisovb7d85632015-07-24 05:09:40 +0000782
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000783 // Find the arrayWithObjects:count: method, if we haven't done so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000784 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000785 if (!ArrayWithObjectsMethod) {
786 Selector
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000787 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
788 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000789 if (!Method && getLangOpts().DebuggerObjCLiteral) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000790 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000791 Method = ObjCMethodDecl::Create(
792 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000793 Context.getTranslationUnitDecl(), false /*Instance*/,
Alp Toker314cc812014-01-25 16:55:45 +0000794 false /*isVariadic*/,
795 /*isPropertyAccessor=*/false,
796 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
797 ObjCMethodDecl::Required, false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000798 SmallVector<ParmVarDecl *, 2> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000799 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000800 SourceLocation(),
801 SourceLocation(),
802 &Context.Idents.get("objects"),
803 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000804 /*TInfo=*/nullptr,
805 SC_None, nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000806 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000807 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000808 SourceLocation(),
809 SourceLocation(),
810 &Context.Idents.get("cnt"),
811 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000812 /*TInfo=*/nullptr, SC_None,
813 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000814 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000815 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000816 }
817
Alex Denisovb7d85632015-07-24 05:09:40 +0000818 if (!validateBoxingMethod(*this, Loc, NSArrayDecl, Sel, Method))
Ted Kremeneke65b0862012-03-06 20:05:56 +0000819 return ExprError();
Jordy Rose08e500c2012-05-12 17:32:44 +0000820
Jordy Rose4af44872012-05-12 17:32:56 +0000821 // Dig out the type that all elements should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000822 QualType T = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000823 const PointerType *PtrT = T->getAs<PointerType>();
824 if (!PtrT ||
825 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
826 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
827 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000828 Diag(Method->parameters()[0]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000829 diag::note_objc_literal_method_param)
830 << 0 << T
831 << Context.getPointerType(IdT.withConst());
832 return ExprError();
833 }
834
835 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000836 if (!Method->parameters()[1]->getType()->isIntegerType()) {
Jordy Rose4af44872012-05-12 17:32:56 +0000837 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
838 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000839 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000840 diag::note_objc_literal_method_param)
841 << 1
Alp Toker03376dc2014-07-07 09:02:20 +0000842 << Method->parameters()[1]->getType()
Jordy Rose4af44872012-05-12 17:32:56 +0000843 << "integral";
844 return ExprError();
845 }
846
847 // We've found a good +arrayWithObjects:count: method. Save it!
Jordy Rose08e500c2012-05-12 17:32:44 +0000848 ArrayWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000849 }
850
Alp Toker03376dc2014-07-07 09:02:20 +0000851 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000852 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000853
854 // Check that each of the elements provided is valid in a collection literal,
855 // performing conversions as necessary.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000856 Expr **ElementsBuffer = Elements.data();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000857 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
858 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
859 ElementsBuffer[I],
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000860 RequiredType, true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000861 if (Converted.isInvalid())
862 return ExprError();
863
864 ElementsBuffer[I] = Converted.get();
865 }
866
867 QualType Ty
868 = Context.getObjCObjectPointerType(
869 Context.getObjCInterfaceType(NSArrayDecl));
870
871 return MaybeBindToTemporary(
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000872 ObjCArrayLiteral::Create(Context, Elements, Ty,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000873 ArrayWithObjectsMethod, SR));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000874}
875
Craig Topperd4336e02015-12-24 23:58:15 +0000876ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
877 MutableArrayRef<ObjCDictionaryElement> Elements) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000878 SourceLocation Loc = SR.getBegin();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000879
Alex Denisovb7d85632015-07-24 05:09:40 +0000880 if (!NSDictionaryDecl) {
881 NSDictionaryDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
882 Sema::LK_Dictionary);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000883 if (!NSDictionaryDecl) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000884 return ExprError();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000885 }
886 }
Alex Denisovb7d85632015-07-24 05:09:40 +0000887
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000888 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
889 // so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000890 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000891 if (!DictionaryWithObjectsMethod) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000892 Selector Sel = NSAPIObj->getNSDictionarySelector(
893 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
894 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000895 if (!Method && getLangOpts().DebuggerObjCLiteral) {
896 Method = ObjCMethodDecl::Create(Context,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000897 SourceLocation(), SourceLocation(), Sel,
898 IdT,
Craig Topperc3ec1492014-05-26 06:22:03 +0000899 nullptr /*TypeSourceInfo */,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000900 Context.getTranslationUnitDecl(),
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000901 false /*Instance*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000902 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000903 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
904 ObjCMethodDecl::Required,
905 false);
906 SmallVector<ParmVarDecl *, 3> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000907 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000908 SourceLocation(),
909 SourceLocation(),
910 &Context.Idents.get("objects"),
911 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000912 /*TInfo=*/nullptr, SC_None,
913 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000914 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000915 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000916 SourceLocation(),
917 SourceLocation(),
918 &Context.Idents.get("keys"),
919 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000920 /*TInfo=*/nullptr, SC_None,
921 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000922 Params.push_back(keys);
Jordy Rose08e500c2012-05-12 17:32:44 +0000923 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000924 SourceLocation(),
925 SourceLocation(),
926 &Context.Idents.get("cnt"),
927 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000928 /*TInfo=*/nullptr, SC_None,
929 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000930 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000931 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000932 }
933
Jordy Rose08e500c2012-05-12 17:32:44 +0000934 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
935 Method))
936 return ExprError();
937
Jordy Rose4af44872012-05-12 17:32:56 +0000938 // Dig out the type that all values should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000939 QualType ValueT = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000940 const PointerType *PtrValue = ValueT->getAs<PointerType>();
941 if (!PtrValue ||
942 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000943 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
Jordy Rose4af44872012-05-12 17:32:56 +0000944 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000945 Diag(Method->parameters()[0]->getLocation(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000946 diag::note_objc_literal_method_param)
Jordy Rose4af44872012-05-12 17:32:56 +0000947 << 0 << ValueT
Ted Kremeneke65b0862012-03-06 20:05:56 +0000948 << Context.getPointerType(IdT.withConst());
949 return ExprError();
950 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000951
Jordy Rose4af44872012-05-12 17:32:56 +0000952 // Dig out the type that all keys should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000953 QualType KeyT = Method->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000954 const PointerType *PtrKey = KeyT->getAs<PointerType>();
955 if (!PtrKey ||
956 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
957 IdT)) {
958 bool err = true;
959 if (PtrKey) {
960 if (QIDNSCopying.isNull()) {
961 // key argument of selector is id<NSCopying>?
962 if (ObjCProtocolDecl *NSCopyingPDecl =
963 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
964 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
965 QIDNSCopying =
Douglas Gregore9d95f12015-07-07 03:57:35 +0000966 Context.getObjCObjectType(Context.ObjCBuiltinIdTy, { },
967 llvm::makeArrayRef(
968 (ObjCProtocolDecl**) PQ,
Douglas Gregorab209d82015-07-07 03:58:42 +0000969 1),
970 false);
Jordy Rose4af44872012-05-12 17:32:56 +0000971 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
972 }
973 }
974 if (!QIDNSCopying.isNull())
975 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
976 QIDNSCopying);
977 }
978
979 if (err) {
980 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
981 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000982 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000983 diag::note_objc_literal_method_param)
984 << 1 << KeyT
985 << Context.getPointerType(IdT.withConst());
986 return ExprError();
987 }
988 }
989
990 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000991 QualType CountType = Method->parameters()[2]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000992 if (!CountType->isIntegerType()) {
993 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
994 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000995 Diag(Method->parameters()[2]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000996 diag::note_objc_literal_method_param)
997 << 2 << CountType
998 << "integral";
999 return ExprError();
1000 }
1001
1002 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
1003 DictionaryWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001004 }
1005
Alp Toker03376dc2014-07-07 09:02:20 +00001006 QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +00001007 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
Alp Toker03376dc2014-07-07 09:02:20 +00001008 QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +00001009 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
1010
Ted Kremeneke65b0862012-03-06 20:05:56 +00001011 // Check that each of the keys and values provided is valid in a collection
1012 // literal, performing conversions as necessary.
1013 bool HasPackExpansions = false;
Craig Topperd4336e02015-12-24 23:58:15 +00001014 for (ObjCDictionaryElement &Element : Elements) {
Ted Kremeneke65b0862012-03-06 20:05:56 +00001015 // Check the key.
Craig Topperd4336e02015-12-24 23:58:15 +00001016 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Element.Key,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001017 KeyT);
1018 if (Key.isInvalid())
1019 return ExprError();
1020
1021 // Check the value.
1022 ExprResult Value
Craig Topperd4336e02015-12-24 23:58:15 +00001023 = CheckObjCCollectionLiteralElement(*this, Element.Value, ValueT);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001024 if (Value.isInvalid())
1025 return ExprError();
1026
Craig Topperd4336e02015-12-24 23:58:15 +00001027 Element.Key = Key.get();
1028 Element.Value = Value.get();
Ted Kremeneke65b0862012-03-06 20:05:56 +00001029
Craig Topperd4336e02015-12-24 23:58:15 +00001030 if (Element.EllipsisLoc.isInvalid())
Ted Kremeneke65b0862012-03-06 20:05:56 +00001031 continue;
1032
Craig Topperd4336e02015-12-24 23:58:15 +00001033 if (!Element.Key->containsUnexpandedParameterPack() &&
1034 !Element.Value->containsUnexpandedParameterPack()) {
1035 Diag(Element.EllipsisLoc,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001036 diag::err_pack_expansion_without_parameter_packs)
Craig Topperd4336e02015-12-24 23:58:15 +00001037 << SourceRange(Element.Key->getLocStart(),
1038 Element.Value->getLocEnd());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001039 return ExprError();
1040 }
1041
1042 HasPackExpansions = true;
1043 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001044
1045 QualType Ty
1046 = Context.getObjCObjectPointerType(
Robert Wilhelm88e02492013-08-19 07:57:02 +00001047 Context.getObjCInterfaceType(NSDictionaryDecl));
1048 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
Craig Topperd4336e02015-12-24 23:58:15 +00001049 Context, Elements, HasPackExpansions, Ty,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +00001050 DictionaryWithObjectsMethod, SR));
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001051}
1052
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +00001053ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregorabd9e962010-04-20 15:39:42 +00001054 TypeSourceInfo *EncodedTypeInfo,
Anders Carlsson315d2292009-06-07 18:45:35 +00001055 SourceLocation RParenLoc) {
Douglas Gregorabd9e962010-04-20 15:39:42 +00001056 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlsson315d2292009-06-07 18:45:35 +00001057 QualType StrTy;
Mike Stump11289f42009-09-09 15:08:12 +00001058 if (EncodedType->isDependentType())
Anders Carlsson315d2292009-06-07 18:45:35 +00001059 StrTy = Context.DependentTy;
1060 else {
Fariborz Jahaniand9bc6c32011-06-16 22:34:44 +00001061 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
1062 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +00001063 if (RequireCompleteType(AtLoc, EncodedType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001064 diag::err_incomplete_type_objc_at_encode,
1065 EncodedTypeInfo->getTypeLoc()))
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +00001066 return ExprError();
1067
Anders Carlsson315d2292009-06-07 18:45:35 +00001068 std::string Str;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00001069 QualType NotEncodedT;
1070 Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT);
1071 if (!NotEncodedT.isNull())
1072 Diag(AtLoc, diag::warn_incomplete_encoded_type)
1073 << EncodedType << NotEncodedT;
Anders Carlsson315d2292009-06-07 18:45:35 +00001074
1075 // The type of @encode is the same as the type of the corresponding string,
1076 // which is an array type.
1077 StrTy = Context.CharTy;
1078 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001079 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Anders Carlsson315d2292009-06-07 18:45:35 +00001080 StrTy.addConst();
1081 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
1082 ArrayType::Normal, 0);
1083 }
Mike Stump11289f42009-09-09 15:08:12 +00001084
Douglas Gregorabd9e962010-04-20 15:39:42 +00001085 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlsson315d2292009-06-07 18:45:35 +00001086}
1087
John McCallfaf5fb42010-08-26 23:41:50 +00001088ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1089 SourceLocation EncodeLoc,
1090 SourceLocation LParenLoc,
1091 ParsedType ty,
1092 SourceLocation RParenLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001093 // FIXME: Preserve type source info ?
Douglas Gregorabd9e962010-04-20 15:39:42 +00001094 TypeSourceInfo *TInfo;
1095 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
1096 if (!TInfo)
1097 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
Craig Topper07fa1762015-11-15 02:31:46 +00001098 getLocForEndOfToken(LParenLoc));
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001099
Douglas Gregorabd9e962010-04-20 15:39:42 +00001100 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001101}
1102
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001103static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
1104 SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001105 SourceLocation LParenLoc,
1106 SourceLocation RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001107 ObjCMethodDecl *Method,
1108 ObjCMethodList &MethList) {
1109 ObjCMethodList *M = &MethList;
1110 bool Warned = false;
1111 for (M = M->getNext(); M; M=M->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00001112 ObjCMethodDecl *MatchingMethodDecl = M->getMethod();
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001113 if (MatchingMethodDecl == Method ||
1114 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
1115 MatchingMethodDecl->getSelector() != Method->getSelector())
1116 continue;
1117 if (!S.MatchTwoMethodDeclarations(Method,
1118 MatchingMethodDecl, Sema::MMS_loose)) {
1119 if (!Warned) {
1120 Warned = true;
Richard Smith01d96982016-12-02 23:00:28 +00001121 S.Diag(AtLoc, diag::warn_multiple_selectors)
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001122 << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
1123 << FixItHint::CreateInsertion(RParenLoc, ")");
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001124 S.Diag(Method->getLocation(), diag::note_method_declared_at)
1125 << Method->getDeclName();
1126 }
1127 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
1128 << MatchingMethodDecl->getDeclName();
1129 }
1130 }
1131 return Warned;
1132}
1133
1134static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001135 ObjCMethodDecl *Method,
1136 SourceLocation LParenLoc,
1137 SourceLocation RParenLoc,
1138 bool WarnMultipleSelectors) {
1139 if (!WarnMultipleSelectors ||
Richard Smith01d96982016-12-02 23:00:28 +00001140 S.Diags.isIgnored(diag::warn_multiple_selectors, SourceLocation()))
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001141 return;
1142 bool Warned = false;
1143 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1144 e = S.MethodPool.end(); b != e; b++) {
1145 // first, instance methods
1146 ObjCMethodList &InstMethList = b->second.first;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001147 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001148 Method, InstMethList))
1149 Warned = true;
1150
1151 // second, class methods
1152 ObjCMethodList &ClsMethList = b->second.second;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001153 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1154 Method, ClsMethList) || Warned)
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001155 return;
1156 }
1157}
1158
John McCallfaf5fb42010-08-26 23:41:50 +00001159ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1160 SourceLocation AtLoc,
1161 SourceLocation SelLoc,
1162 SourceLocation LParenLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001163 SourceLocation RParenLoc,
1164 bool WarnMultipleSelectors) {
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001165 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian890803f2015-04-15 17:26:21 +00001166 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001167 if (!Method)
1168 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian0571d9b2009-06-16 16:25:00 +00001169 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00001170 if (!Method) {
1171 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1172 Selector MatchedSel = OM->getSelector();
1173 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1174 RParenLoc.getLocWithOffset(-1));
1175 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1176 << Sel << MatchedSel
1177 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1178
1179 } else
1180 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001181 } else
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001182 DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
1183 WarnMultipleSelectors);
Chandler Carruth12c8f652015-03-27 00:55:05 +00001184
Fariborz Jahanian65a78b52014-05-09 19:51:39 +00001185 if (Method &&
1186 Method->getImplementationControl() != ObjCMethodDecl::Optional &&
Chandler Carruth12c8f652015-03-27 00:55:05 +00001187 !getSourceManager().isInSystemHeader(Method->getLocation()))
1188 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00001189
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001190 // In ARC, forbid the user from using @selector for
John McCall31168b02011-06-15 23:02:42 +00001191 // retain/release/autorelease/dealloc/retainCount.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001192 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001193 switch (Sel.getMethodFamily()) {
1194 case OMF_retain:
1195 case OMF_release:
1196 case OMF_autorelease:
1197 case OMF_retainCount:
1198 case OMF_dealloc:
1199 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1200 Sel << SourceRange(LParenLoc, RParenLoc);
1201 break;
1202
1203 case OMF_None:
1204 case OMF_alloc:
1205 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00001206 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00001207 case OMF_init:
1208 case OMF_mutableCopy:
1209 case OMF_new:
1210 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00001211 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00001212 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00001213 break;
1214 }
1215 }
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001216 QualType Ty = Context.getObjCSelType();
Daniel Dunbar45858d22010-02-03 20:11:42 +00001217 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001218}
1219
John McCallfaf5fb42010-08-26 23:41:50 +00001220ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1221 SourceLocation AtLoc,
1222 SourceLocation ProtoLoc,
1223 SourceLocation LParenLoc,
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001224 SourceLocation ProtoIdLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00001225 SourceLocation RParenLoc) {
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001226 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001227 if (!PDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001228 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001229 return true;
1230 }
Fariborz Jahaniana57d91c22014-07-25 19:45:01 +00001231 if (PDecl->hasDefinition())
1232 PDecl = PDecl->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00001233
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001234 QualType Ty = Context.getObjCProtoType();
1235 if (Ty.isNull())
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001236 return true;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001237 Ty = Context.getObjCObjectPointerType(Ty);
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001238 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001239}
1240
John McCall5f2d5562011-02-03 09:00:02 +00001241/// Try to capture an implicit reference to 'self'.
Eli Friedman24af8502012-02-03 22:47:37 +00001242ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1243 DeclContext *DC = getFunctionLevelDeclContext();
John McCall5f2d5562011-02-03 09:00:02 +00001244
1245 // If we're not in an ObjC method, error out. Note that, unlike the
1246 // C++ case, we don't require an instance method --- class methods
1247 // still have a 'self', and we really do still need to capture it!
1248 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1249 if (!method)
Craig Topperc3ec1492014-05-26 06:22:03 +00001250 return nullptr;
John McCall5f2d5562011-02-03 09:00:02 +00001251
Douglas Gregorfdf598e2012-02-18 09:37:24 +00001252 tryCaptureVariable(method->getSelfDecl(), Loc);
John McCall5f2d5562011-02-03 09:00:02 +00001253
1254 return method;
1255}
1256
Douglas Gregor64910ca2011-09-09 20:05:21 +00001257static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
Douglas Gregor813a0662015-06-19 18:14:38 +00001258 QualType origType = T;
1259 if (auto nullability = AttributedType::stripOuterNullability(T)) {
1260 if (T == Context.getObjCInstanceType()) {
1261 return Context.getAttributedType(
1262 AttributedType::getNullabilityAttrKind(*nullability),
1263 Context.getObjCIdType(),
1264 Context.getObjCIdType());
1265 }
1266
1267 return origType;
1268 }
1269
Douglas Gregor64910ca2011-09-09 20:05:21 +00001270 if (T == Context.getObjCInstanceType())
1271 return Context.getObjCIdType();
1272
Douglas Gregor813a0662015-06-19 18:14:38 +00001273 return origType;
Douglas Gregor64910ca2011-09-09 20:05:21 +00001274}
1275
Douglas Gregor813a0662015-06-19 18:14:38 +00001276/// Determine the result type of a message send based on the receiver type,
1277/// method, and the kind of message send.
1278///
1279/// This is the "base" result type, which will still need to be adjusted
1280/// to account for nullability.
1281static QualType getBaseMessageSendResultType(Sema &S,
1282 QualType ReceiverType,
1283 ObjCMethodDecl *Method,
1284 bool isClassMessage,
1285 bool isSuperMessage) {
Douglas Gregor33823722011-06-11 01:09:30 +00001286 assert(Method && "Must have a method");
1287 if (!Method->hasRelatedResultType())
Douglas Gregore83b9562015-07-07 03:57:53 +00001288 return Method->getSendResultType(ReceiverType);
Douglas Gregor813a0662015-06-19 18:14:38 +00001289
1290 ASTContext &Context = S.Context;
1291
1292 // Local function that transfers the nullability of the method's
1293 // result type to the returned result.
1294 auto transferNullability = [&](QualType type) -> QualType {
1295 // If the method's result type has nullability, extract it.
Douglas Gregore83b9562015-07-07 03:57:53 +00001296 if (auto nullability = Method->getSendResultType(ReceiverType)
1297 ->getNullability(Context)){
Douglas Gregor813a0662015-06-19 18:14:38 +00001298 // Strip off any outer nullability sugar from the provided type.
1299 (void)AttributedType::stripOuterNullability(type);
1300
1301 // Form a new attributed type using the method result type's nullability.
1302 return Context.getAttributedType(
1303 AttributedType::getNullabilityAttrKind(*nullability),
1304 type,
1305 type);
1306 }
1307
1308 return type;
1309 };
1310
Douglas Gregor33823722011-06-11 01:09:30 +00001311 // If a method has a related return type:
1312 // - if the method found is an instance method, but the message send
1313 // was a class message send, T is the declared return type of the method
1314 // found
1315 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregore83b9562015-07-07 03:57:53 +00001316 return stripObjCInstanceType(Context,
1317 Method->getSendResultType(ReceiverType));
Douglas Gregor813a0662015-06-19 18:14:38 +00001318
1319 // - if the receiver is super, T is a pointer to the class of the
Douglas Gregor33823722011-06-11 01:09:30 +00001320 // enclosing method definition
1321 if (isSuperMessage) {
Douglas Gregor813a0662015-06-19 18:14:38 +00001322 if (ObjCMethodDecl *CurMethod = S.getCurMethodDecl())
1323 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) {
1324 return transferNullability(
1325 Context.getObjCObjectPointerType(
1326 Context.getObjCInterfaceType(Class)));
1327 }
Douglas Gregor33823722011-06-11 01:09:30 +00001328 }
Douglas Gregor813a0662015-06-19 18:14:38 +00001329
Douglas Gregor33823722011-06-11 01:09:30 +00001330 // - if the receiver is the name of a class U, T is a pointer to U
Douglas Gregore83b9562015-07-07 03:57:53 +00001331 if (ReceiverType->getAsObjCInterfaceType())
Douglas Gregor813a0662015-06-19 18:14:38 +00001332 return transferNullability(Context.getObjCObjectPointerType(ReceiverType));
1333 // - if the receiver is of type Class or qualified Class type,
Douglas Gregor33823722011-06-11 01:09:30 +00001334 // T is the declared return type of the method.
1335 if (ReceiverType->isObjCClassType() ||
1336 ReceiverType->isObjCQualifiedClassType())
Douglas Gregore83b9562015-07-07 03:57:53 +00001337 return stripObjCInstanceType(Context,
1338 Method->getSendResultType(ReceiverType));
Douglas Gregor813a0662015-06-19 18:14:38 +00001339
Douglas Gregor33823722011-06-11 01:09:30 +00001340 // - if the receiver is id, qualified id, Class, or qualified Class, T
1341 // is the receiver type, otherwise
1342 // - T is the type of the receiver expression.
Douglas Gregor813a0662015-06-19 18:14:38 +00001343 return transferNullability(ReceiverType);
1344}
1345
1346QualType Sema::getMessageSendResultType(QualType ReceiverType,
1347 ObjCMethodDecl *Method,
1348 bool isClassMessage,
1349 bool isSuperMessage) {
1350 // Produce the result type.
1351 QualType resultType = getBaseMessageSendResultType(*this, ReceiverType,
1352 Method,
1353 isClassMessage,
1354 isSuperMessage);
1355
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001356 // If this is a class message, ignore the nullability of the receiver.
1357 if (isClassMessage)
1358 return resultType;
1359
Douglas Gregor813a0662015-06-19 18:14:38 +00001360 // Map the nullability of the result into a table index.
1361 unsigned receiverNullabilityIdx = 0;
1362 if (auto nullability = ReceiverType->getNullability(Context))
1363 receiverNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1364
1365 unsigned resultNullabilityIdx = 0;
1366 if (auto nullability = resultType->getNullability(Context))
1367 resultNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1368
1369 // The table of nullability mappings, indexed by the receiver's nullability
1370 // and then the result type's nullability.
1371 static const uint8_t None = 0;
1372 static const uint8_t NonNull = 1;
1373 static const uint8_t Nullable = 2;
1374 static const uint8_t Unspecified = 3;
1375 static const uint8_t nullabilityMap[4][4] = {
1376 // None NonNull Nullable Unspecified
1377 /* None */ { None, None, Nullable, None },
1378 /* NonNull */ { None, NonNull, Nullable, Unspecified },
1379 /* Nullable */ { Nullable, Nullable, Nullable, Nullable },
1380 /* Unspecified */ { None, Unspecified, Nullable, Unspecified }
1381 };
1382
1383 unsigned newResultNullabilityIdx
1384 = nullabilityMap[receiverNullabilityIdx][resultNullabilityIdx];
1385 if (newResultNullabilityIdx == resultNullabilityIdx)
1386 return resultType;
1387
1388 // Strip off the existing nullability. This removes as little type sugar as
1389 // possible.
1390 do {
1391 if (auto attributed = dyn_cast<AttributedType>(resultType.getTypePtr())) {
1392 resultType = attributed->getModifiedType();
1393 } else {
1394 resultType = resultType.getDesugaredType(Context);
1395 }
1396 } while (resultType->getNullability(Context));
1397
1398 // Add nullability back if needed.
1399 if (newResultNullabilityIdx > 0) {
1400 auto newNullability
1401 = static_cast<NullabilityKind>(newResultNullabilityIdx-1);
1402 return Context.getAttributedType(
1403 AttributedType::getNullabilityAttrKind(newNullability),
1404 resultType, resultType);
1405 }
1406
1407 return resultType;
Douglas Gregor33823722011-06-11 01:09:30 +00001408}
John McCall5f2d5562011-02-03 09:00:02 +00001409
John McCall5ec7e7d2013-03-19 07:04:25 +00001410/// Look for an ObjC method whose result type exactly matches the given type.
1411static const ObjCMethodDecl *
1412findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1413 QualType instancetype) {
Alp Toker314cc812014-01-25 16:55:45 +00001414 if (MD->getReturnType() == instancetype)
1415 return MD;
John McCall5ec7e7d2013-03-19 07:04:25 +00001416
1417 // For these purposes, a method in an @implementation overrides a
1418 // declaration in the @interface.
1419 if (const ObjCImplDecl *impl =
1420 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1421 const ObjCContainerDecl *iface;
1422 if (const ObjCCategoryImplDecl *catImpl =
1423 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1424 iface = catImpl->getCategoryDecl();
1425 } else {
1426 iface = impl->getClassInterface();
1427 }
1428
1429 const ObjCMethodDecl *ifaceMD =
1430 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1431 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1432 }
1433
1434 SmallVector<const ObjCMethodDecl *, 4> overrides;
1435 MD->getOverriddenMethods(overrides);
1436 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1437 if (const ObjCMethodDecl *result =
1438 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1439 return result;
1440 }
1441
Craig Topperc3ec1492014-05-26 06:22:03 +00001442 return nullptr;
John McCall5ec7e7d2013-03-19 07:04:25 +00001443}
1444
1445void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1446 // Only complain if we're in an ObjC method and the required return
1447 // type doesn't match the method's declared return type.
1448 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1449 if (!MD || !MD->hasRelatedResultType() ||
Alp Toker314cc812014-01-25 16:55:45 +00001450 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
John McCall5ec7e7d2013-03-19 07:04:25 +00001451 return;
1452
1453 // Look for a method overridden by this method which explicitly uses
1454 // 'instancetype'.
1455 if (const ObjCMethodDecl *overridden =
1456 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
Aaron Ballman41b10ac2014-08-01 13:20:09 +00001457 SourceRange range = overridden->getReturnTypeSourceRange();
1458 SourceLocation loc = range.getBegin();
John McCall5ec7e7d2013-03-19 07:04:25 +00001459 if (loc.isInvalid())
1460 loc = overridden->getLocation();
1461 Diag(loc, diag::note_related_result_type_explicit)
1462 << /*current method*/ 1 << range;
1463 return;
1464 }
1465
1466 // Otherwise, if we have an interesting method family, note that.
1467 // This should always trigger if the above didn't.
1468 if (ObjCMethodFamily family = MD->getMethodFamily())
1469 Diag(MD->getLocation(), diag::note_related_result_type_family)
1470 << /*current method*/ 1
1471 << family;
1472}
1473
Douglas Gregor33823722011-06-11 01:09:30 +00001474void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1475 E = E->IgnoreParenImpCasts();
1476 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1477 if (!MsgSend)
1478 return;
1479
1480 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1481 if (!Method)
1482 return;
1483
1484 if (!Method->hasRelatedResultType())
1485 return;
Alp Toker314cc812014-01-25 16:55:45 +00001486
1487 if (Context.hasSameUnqualifiedType(
1488 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
Douglas Gregor33823722011-06-11 01:09:30 +00001489 return;
Alp Toker314cc812014-01-25 16:55:45 +00001490
1491 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
Douglas Gregorbab8a962011-09-08 01:46:34 +00001492 Context.getObjCInstanceType()))
1493 return;
1494
Douglas Gregor33823722011-06-11 01:09:30 +00001495 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1496 << Method->isInstanceMethod() << Method->getSelector()
1497 << MsgSend->getType();
1498}
1499
1500bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001501 MultiExprArg Args,
1502 Selector Sel,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001503 ArrayRef<SourceLocation> SelectorLocs,
1504 ObjCMethodDecl *Method,
Douglas Gregor33823722011-06-11 01:09:30 +00001505 bool isClassMessage, bool isSuperMessage,
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001506 SourceLocation lbrac, SourceLocation rbrac,
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00001507 SourceRange RecRange,
John McCall7decc9e2010-11-18 06:31:45 +00001508 QualType &ReturnType, ExprValueKind &VK) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001509 SourceLocation SelLoc;
1510 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1511 SelLoc = SelectorLocs.front();
1512 else
1513 SelLoc = lbrac;
1514
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001515 if (!Method) {
Daniel Dunbar83876b42008-09-11 00:04:36 +00001516 // Apply default argument promotion as for (C99 6.5.2.2p6).
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001517 for (unsigned i = 0, e = Args.size(); i != e; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001518 if (Args[i]->isTypeDependent())
1519 continue;
1520
John McCallcc5788c2013-03-04 07:34:02 +00001521 ExprResult result;
1522 if (getLangOpts().DebuggerSupport) {
1523 QualType paramTy; // ignored
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001524 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
John McCallcc5788c2013-03-04 07:34:02 +00001525 } else {
1526 result = DefaultArgumentPromotion(Args[i]);
1527 }
1528 if (result.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001529 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001530 Args[i] = result.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001531 }
Daniel Dunbar83876b42008-09-11 00:04:36 +00001532
John McCall31168b02011-06-15 23:02:42 +00001533 unsigned DiagID;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001534 if (getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00001535 DiagID = diag::err_arc_method_not_found;
1536 else
1537 DiagID = isClassMessage ? diag::warn_class_method_not_found
1538 : diag::warn_inst_method_not_found;
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001539 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001540 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
Fariborz Jahanian06499232013-06-18 17:10:58 +00001541 if (OMD && !OMD->isInvalidDecl()) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001542 if (getLangOpts().ObjCAutoRefCount)
Richard Smithf8812672016-12-02 22:38:31 +00001543 DiagID = diag::err_method_not_found_with_typo;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001544 else
1545 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1546 : diag::warn_instance_method_not_found_with_typo;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001547 Selector MatchedSel = OMD->getSelector();
1548 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
Fariborz Jahanian5ab87502014-08-12 22:16:41 +00001549 if (MatchedSel.isUnarySelector())
1550 Diag(SelLoc, DiagID)
1551 << Sel<< isClassMessage << MatchedSel
1552 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1553 else
1554 Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001555 }
1556 else
1557 Diag(SelLoc, DiagID)
1558 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001559 SelectorLocs.back());
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001560 // Find the class to which we are sending this message.
1561 if (ReceiverType->isObjCObjectPointerType()) {
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00001562 if (ObjCInterfaceDecl *ThisClass =
1563 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()) {
1564 Diag(ThisClass->getLocation(), diag::note_receiver_class_declared);
1565 if (!RecRange.isInvalid())
1566 if (ThisClass->lookupClassMethod(Sel))
1567 Diag(RecRange.getBegin(),diag::note_receiver_expr_here)
1568 << FixItHint::CreateReplacement(RecRange,
1569 ThisClass->getNameAsString());
1570 }
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001571 }
1572 }
John McCall3f4138c2011-07-13 17:56:40 +00001573
1574 // In debuggers, we want to use __unknown_anytype for these
1575 // results so that clients can cast them.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001576 if (getLangOpts().DebuggerSupport) {
John McCall3f4138c2011-07-13 17:56:40 +00001577 ReturnType = Context.UnknownAnyTy;
1578 } else {
1579 ReturnType = Context.getObjCIdType();
1580 }
John McCall7decc9e2010-11-18 06:31:45 +00001581 VK = VK_RValue;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001582 return false;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001583 }
Mike Stump11289f42009-09-09 15:08:12 +00001584
Douglas Gregor33823722011-06-11 01:09:30 +00001585 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1586 isSuperMessage);
Alp Toker314cc812014-01-25 16:55:45 +00001587 VK = Expr::getValueKindForType(Method->getReturnType());
Mike Stump11289f42009-09-09 15:08:12 +00001588
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001589 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian60462092010-04-08 00:30:06 +00001590 // Method might have more arguments than selector indicates. This is due
1591 // to addition of c-style arguments in method.
1592 if (Method->param_size() > Sel.getNumArgs())
1593 NumNamedArgs = Method->param_size();
1594 // FIXME. This need be cleaned up.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001595 if (Args.size() < NumNamedArgs) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001596 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001597 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
Fariborz Jahanian60462092010-04-08 00:30:06 +00001598 return false;
1599 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001600
Douglas Gregore83b9562015-07-07 03:57:53 +00001601 // Compute the set of type arguments to be substituted into each parameter
1602 // type.
1603 Optional<ArrayRef<QualType>> typeArgs
1604 = ReceiverType->getObjCSubstitutions(Method->getDeclContext());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001605 bool IsError = false;
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001606 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001607 // We can't do any type-checking on a type-dependent argument.
1608 if (Args[i]->isTypeDependent())
1609 continue;
1610
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001611 Expr *argExpr = Args[i];
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001612
Alp Toker03376dc2014-07-07 09:02:20 +00001613 ParmVarDecl *param = Method->parameters()[i];
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001614 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump11289f42009-09-09 15:08:12 +00001615
John McCall4124c492011-10-17 18:40:02 +00001616 // Strip the unbridged-cast placeholder expression off unless it's
1617 // a consumed argument.
1618 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1619 !param->hasAttr<CFConsumedAttr>())
1620 argExpr = stripARCUnbridgedCast(argExpr);
1621
John McCallea0a39e2012-11-14 00:49:39 +00001622 // If the parameter is __unknown_anytype, infer its type
1623 // from the argument.
1624 if (param->getType() == Context.UnknownAnyTy) {
John McCallcc5788c2013-03-04 07:34:02 +00001625 QualType paramType;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001626 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
John McCallcc5788c2013-03-04 07:34:02 +00001627 if (argE.isInvalid()) {
John McCallea0a39e2012-11-14 00:49:39 +00001628 IsError = true;
John McCallcc5788c2013-03-04 07:34:02 +00001629 } else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001630 Args[i] = argE.get();
John McCallea0a39e2012-11-14 00:49:39 +00001631
John McCallcc5788c2013-03-04 07:34:02 +00001632 // Update the parameter type in-place.
1633 param->setType(paramType);
1634 }
1635 continue;
John McCallea0a39e2012-11-14 00:49:39 +00001636 }
1637
Douglas Gregore83b9562015-07-07 03:57:53 +00001638 QualType origParamType = param->getType();
1639 QualType paramType = param->getType();
1640 if (typeArgs)
1641 paramType = paramType.substObjCTypeArgs(
1642 Context,
1643 *typeArgs,
1644 ObjCSubstitutionContext::Parameter);
1645
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001646 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
Douglas Gregore83b9562015-07-07 03:57:53 +00001647 paramType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001648 diag::err_call_incomplete_argument, argExpr))
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001649 return true;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001650
Douglas Gregore83b9562015-07-07 03:57:53 +00001651 InitializedEntity Entity
1652 = InitializedEntity::InitializeParameter(Context, param, paramType);
Fariborz Jahaniana1db7df2014-07-31 17:39:50 +00001653 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001654 if (ArgE.isInvalid())
1655 IsError = true;
Douglas Gregore83b9562015-07-07 03:57:53 +00001656 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001657 Args[i] = ArgE.getAs<Expr>();
Douglas Gregore83b9562015-07-07 03:57:53 +00001658
1659 // If we are type-erasing a block to a block-compatible
1660 // Objective-C pointer type, we may need to extend the lifetime
1661 // of the block object.
1662 if (typeArgs && Args[i]->isRValue() && paramType->isBlockPointerType() &&
Bob Wilson7e9fd562015-10-02 01:05:29 +00001663 Args[i]->getType()->isBlockPointerType() &&
1664 origParamType->isObjCObjectPointerType()) {
Douglas Gregore83b9562015-07-07 03:57:53 +00001665 ExprResult arg = Args[i];
1666 maybeExtendBlockObject(arg);
1667 Args[i] = arg.get();
1668 }
1669 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001670 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001671
1672 // Promote additional arguments to variadic methods.
1673 if (Method->isVariadic()) {
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001674 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001675 if (Args[i]->isTypeDependent())
1676 continue;
1677
Jordy Roseaca01f92012-05-12 17:32:52 +00001678 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
Craig Topperc3ec1492014-05-26 06:22:03 +00001679 nullptr);
John Wiegley01296292011-04-08 18:41:53 +00001680 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001681 Args[i] = Arg.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001682 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001683 } else {
1684 // Check for extra arguments to non-variadic methods.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001685 if (Args.size() != NumNamedArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00001686 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001687 diag::err_typecheck_call_too_many_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001688 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001689 << Method->getSourceRange()
Chris Lattner3b054132008-11-19 05:08:23 +00001690 << SourceRange(Args[NumNamedArgs]->getLocStart(),
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001691 Args.back()->getLocEnd());
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001692 }
1693 }
1694
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001695 DiagnoseSentinelCalls(Method, SelLoc, Args);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001696
1697 // Do additional checkings on method.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001698 IsError |= CheckObjCMethodCall(
Craig Topper8c2a2a02014-08-30 16:55:39 +00001699 Method, SelLoc, makeArrayRef(Args.data(), Args.size()));
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001700
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001701 return IsError;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001702}
1703
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001704bool Sema::isSelfExpr(Expr *RExpr) {
Fariborz Jahanianb3b1e172011-03-27 19:53:47 +00001705 // 'self' is objc 'self' in an objc method only.
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001706 ObjCMethodDecl *Method =
1707 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1708 return isSelfExpr(RExpr, Method);
1709}
1710
1711bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
John McCallfe96e0b2011-11-06 09:01:30 +00001712 if (!method) return false;
1713
John McCall31168b02011-06-15 23:02:42 +00001714 receiver = receiver->IgnoreParenLValueCasts();
1715 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCallfe96e0b2011-11-06 09:01:30 +00001716 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregor486b74e2011-09-27 16:10:05 +00001717 return true;
1718 return false;
Steve Naroff3f49fee2009-03-04 15:11:40 +00001719}
1720
John McCall526ab472011-10-25 17:37:35 +00001721/// LookupMethodInType - Look up a method in an ObjCObjectType.
1722ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1723 bool isInstance) {
1724 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1725 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1726 // Look it up in the main interface (and categories, etc.)
1727 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1728 return method;
1729
1730 // Okay, look for "private" methods declared in any
1731 // @implementations we've seen.
Anna Zaksc77a3b12012-07-27 19:07:44 +00001732 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1733 return method;
John McCall526ab472011-10-25 17:37:35 +00001734 }
1735
1736 // Check qualifiers.
Aaron Ballman1683f7b2014-03-17 15:55:30 +00001737 for (const auto *I : objType->quals())
1738 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
John McCall526ab472011-10-25 17:37:35 +00001739 return method;
1740
Craig Topperc3ec1492014-05-26 06:22:03 +00001741 return nullptr;
John McCall526ab472011-10-25 17:37:35 +00001742}
1743
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001744/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1745/// list of a qualified objective pointer type.
1746ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1747 const ObjCObjectPointerType *OPT,
1748 bool Instance)
1749{
Craig Topperc3ec1492014-05-26 06:22:03 +00001750 ObjCMethodDecl *MD = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +00001751 for (const auto *PROTO : OPT->quals()) {
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001752 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1753 return MD;
1754 }
1755 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001756 return nullptr;
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001757}
1758
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001759/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1760/// objective C interface. This is a property reference expression.
John McCalldadc5752010-08-24 06:29:42 +00001761ExprResult Sema::
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001762HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001763 Expr *BaseExpr, SourceLocation OpLoc,
1764 DeclarationName MemberName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001765 SourceLocation MemberLoc,
1766 SourceLocation SuperLoc, QualType SuperType,
1767 bool Super) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001768 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1769 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00001770
Benjamin Kramer365082d2012-05-19 16:34:46 +00001771 if (!MemberName.isIdentifier()) {
Douglas Gregord6459312011-04-20 18:19:55 +00001772 Diag(MemberLoc, diag::err_invalid_property_name)
1773 << MemberName << QualType(OPT, 0);
1774 return ExprError();
1775 }
Benjamin Kramer365082d2012-05-19 16:34:46 +00001776
1777 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregord6459312011-04-20 18:19:55 +00001778
Douglas Gregor4123a862011-11-14 22:10:01 +00001779 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1780 : BaseExpr->getSourceRange();
1781 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001782 diag::err_property_not_found_forward_class,
1783 MemberName, BaseRange))
Fariborz Jahanian7cabbe02010-12-16 00:56:28 +00001784 return ExprError();
Douglas Gregoracf4fd32015-11-03 01:15:46 +00001785
Manman Ren5b786402016-01-28 18:49:28 +00001786 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(
1787 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001788 // Check whether we can reference this property.
1789 if (DiagnoseUseOfDecl(PD, MemberLoc))
1790 return ExprError();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001791 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001792 return new (Context)
1793 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1794 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001795 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001796 return new (Context)
1797 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1798 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001799 }
1800 // Check protocols on qualified interfaces.
Aaron Ballman83731462014-03-17 16:14:00 +00001801 for (const auto *I : OPT->quals())
Manman Ren5b786402016-01-28 18:49:28 +00001802 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
1803 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001804 // Check whether we can reference this property.
1805 if (DiagnoseUseOfDecl(PD, MemberLoc))
1806 return ExprError();
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001807
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001808 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001809 return new (Context) ObjCPropertyRefExpr(
1810 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
1811 SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001812 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001813 return new (Context)
1814 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1815 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001816 }
1817 // If that failed, look for an "implicit" property by seeing if the nullary
1818 // selector is implemented.
1819
1820 // FIXME: The logic for looking up nullary and unary selectors should be
1821 // shared with the code in ActOnInstanceMessage.
1822
1823 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1824 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001825
Manman Ren2b2b1a92016-06-28 23:01:49 +00001826 // May be found in property's qualified list.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001827 if (!Getter)
1828 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001829
1830 // If this reference is in an @implementation, check for 'private' methods.
1831 if (!Getter)
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001832 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001833
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001834 if (Getter) {
1835 // Check if we can reference this property.
1836 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1837 return ExprError();
1838 }
1839 // If we found a getter then this may be a valid dot-reference, we
1840 // will look for the matching setter, in case it is needed.
1841 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001842 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1843 PP.getSelectorTable(), Member);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001844 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001845
Manman Ren2b2b1a92016-06-28 23:01:49 +00001846 // May be found in property's qualified list.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001847 if (!Setter)
1848 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1849
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001850 if (!Setter) {
1851 // If this reference is in an @implementation, also check for 'private'
1852 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001853 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001854 }
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001855
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001856 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1857 return ExprError();
1858
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001859 // Special warning if member name used in a property-dot for a setter accessor
1860 // does not use a property with same name; e.g. obj.X = ... for a property with
1861 // name 'x'.
Manman Ren5b786402016-01-28 18:49:28 +00001862 if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor() &&
1863 !IFace->FindPropertyDeclaration(
1864 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Fariborz Jahanian4eda2c02014-08-15 17:39:00 +00001865 if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) {
1866 // Do not warn if user is using property-dot syntax to make call to
1867 // user named setter.
1868 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter))
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001869 Diag(MemberLoc,
1870 diag::warn_property_access_suggest)
1871 << MemberName << QualType(OPT, 0) << PDecl->getName()
1872 << FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
Fariborz Jahanian4eda2c02014-08-15 17:39:00 +00001873 }
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001874 }
1875
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001876 if (Getter || Setter) {
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001877 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001878 return new (Context)
1879 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1880 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001881 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001882 return new (Context)
1883 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1884 OK_ObjCProperty, MemberLoc, BaseExpr);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001885
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001886 }
1887
1888 // Attempt to correct for typos in property names.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001889 if (TypoCorrection Corrected =
1890 CorrectTypo(DeclarationNameInfo(MemberName, MemberLoc),
1891 LookupOrdinaryName, nullptr, nullptr,
1892 llvm::make_unique<DeclFilterCCC<ObjCPropertyDecl>>(),
1893 CTK_ErrorRecovery, IFace, false, OPT)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001894 DeclarationName TypoResult = Corrected.getCorrection();
Manman Ren2b2b1a92016-06-28 23:01:49 +00001895 if (TypoResult.isIdentifier() &&
1896 TypoResult.getAsIdentifierInfo() == Member) {
1897 // There is no need to try the correction if it is the same.
1898 NamedDecl *ChosenDecl =
1899 Corrected.isKeyword() ? nullptr : Corrected.getFoundDecl();
1900 if (ChosenDecl && isa<ObjCPropertyDecl>(ChosenDecl))
1901 if (cast<ObjCPropertyDecl>(ChosenDecl)->isClassProperty()) {
1902 // This is a class property, we should not use the instance to
1903 // access it.
1904 Diag(MemberLoc, diag::err_class_property_found) << MemberName
1905 << OPT->getInterfaceDecl()->getName()
1906 << FixItHint::CreateReplacement(BaseExpr->getSourceRange(),
1907 OPT->getInterfaceDecl()->getName());
1908 return ExprError();
1909 }
1910 } else {
1911 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1912 << MemberName << QualType(OPT, 0));
1913 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1914 TypoResult, MemberLoc,
1915 SuperLoc, SuperType, Super);
1916 }
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001917 }
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001918 ObjCInterfaceDecl *ClassDeclared;
1919 if (ObjCIvarDecl *Ivar =
1920 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1921 QualType T = Ivar->getType();
1922 if (const ObjCObjectPointerType * OBJPT =
1923 T->getAsObjCInterfacePointerType()) {
Douglas Gregor4123a862011-11-14 22:10:01 +00001924 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001925 diag::err_property_not_as_forward_class,
1926 MemberName, BaseExpr))
Douglas Gregor4123a862011-11-14 22:10:01 +00001927 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001928 }
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001929 Diag(MemberLoc,
1930 diag::err_ivar_access_using_property_syntax_suggest)
1931 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1932 << FixItHint::CreateReplacement(OpLoc, "->");
1933 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001934 }
Chris Lattner90c58fa2010-04-11 07:51:10 +00001935
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001936 Diag(MemberLoc, diag::err_property_not_found)
1937 << MemberName << QualType(OPT, 0);
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001938 if (Setter)
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001939 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001940 << MemberName << BaseExpr->getSourceRange();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001941 return ExprError();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001942}
1943
John McCalldadc5752010-08-24 06:29:42 +00001944ExprResult Sema::
Chris Lattnera36ec422010-04-11 08:28:14 +00001945ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1946 IdentifierInfo &propertyName,
1947 SourceLocation receiverNameLoc,
1948 SourceLocation propertyNameLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00001949
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001950 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001951 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1952 receiverNameLoc);
Douglas Gregor33823722011-06-11 01:09:30 +00001953
Douglas Gregore83b9562015-07-07 03:57:53 +00001954 QualType SuperType;
Craig Topperc3ec1492014-05-26 06:22:03 +00001955 if (!IFace) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001956 // If the "receiver" is 'super' in a method, handle it as an expression-like
1957 // property reference.
John McCall5f2d5562011-02-03 09:00:02 +00001958 if (receiverNamePtr->isStr("super")) {
Eli Friedman24af8502012-02-03 22:47:37 +00001959 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Douglas Gregore83b9562015-07-07 03:57:53 +00001960 if (auto classDecl = CurMethod->getClassInterface()) {
1961 SuperType = QualType(classDecl->getSuperClassType(), 0);
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001962 if (CurMethod->isInstanceMethod()) {
Douglas Gregore83b9562015-07-07 03:57:53 +00001963 if (SuperType.isNull()) {
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001964 // The current class does not have a superclass.
Richard Smithf8812672016-12-02 22:38:31 +00001965 Diag(receiverNameLoc, diag::err_root_class_cannot_use_super)
Douglas Gregore83b9562015-07-07 03:57:53 +00001966 << CurMethod->getClassInterface()->getIdentifier();
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001967 return ExprError();
1968 }
Douglas Gregore83b9562015-07-07 03:57:53 +00001969 QualType T = Context.getObjCObjectPointerType(SuperType);
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001970
Douglas Gregore83b9562015-07-07 03:57:53 +00001971 return HandleExprPropertyRefExpr(T->castAs<ObjCObjectPointerType>(),
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001972 /*BaseExpr*/nullptr,
1973 SourceLocation()/*OpLoc*/,
1974 &propertyName,
1975 propertyNameLoc,
1976 receiverNameLoc, T, true);
Fariborz Jahanian05e2aaa2013-03-11 22:26:33 +00001977 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001978
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001979 // Otherwise, if this is a class method, try dispatching to our
1980 // superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00001981 IFace = CurMethod->getClassInterface()->getSuperClass();
Chris Lattnera36ec422010-04-11 08:28:14 +00001982 }
Chris Lattnera36ec422010-04-11 08:28:14 +00001983 }
John McCall5f2d5562011-02-03 09:00:02 +00001984 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001985
1986 if (!IFace) {
Alp Tokerec543272013-12-24 09:48:30 +00001987 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
1988 << tok::l_paren;
Chris Lattnera36ec422010-04-11 08:28:14 +00001989 return ExprError();
1990 }
1991 }
1992
Saleem Abdulrasoolb3a2d042017-02-20 23:45:49 +00001993 Selector GetterSel;
1994 Selector SetterSel;
1995 if (auto PD = IFace->FindPropertyDeclaration(
1996 &propertyName, ObjCPropertyQueryKind::OBJC_PR_query_class)) {
1997 GetterSel = PD->getGetterName();
1998 SetterSel = PD->getSetterName();
1999 } else {
2000 GetterSel = PP.getSelectorTable().getNullarySelector(&propertyName);
2001 SetterSel = SelectorTable::constructSetterSelector(
2002 PP.getIdentifierTable(), PP.getSelectorTable(), &propertyName);
2003 }
2004
Chris Lattnera36ec422010-04-11 08:28:14 +00002005 // Search for a declared property first.
Saleem Abdulrasoolb3a2d042017-02-20 23:45:49 +00002006 ObjCMethodDecl *Getter = IFace->lookupClassMethod(GetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002007
2008 // If this reference is in an @implementation, check for 'private' methods.
2009 if (!Getter)
Saleem Abdulrasoolb3a2d042017-02-20 23:45:49 +00002010 Getter = IFace->lookupPrivateClassMethod(GetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002011
2012 if (Getter) {
2013 // FIXME: refactor/share with ActOnMemberReference().
2014 // Check if we can reference this property.
2015 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
2016 return ExprError();
2017 }
Mike Stump11289f42009-09-09 15:08:12 +00002018
Steve Naroff9527bbf2009-03-09 21:12:44 +00002019 // Look for the matching setter, in case it is needed.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002020 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002021 if (!Setter) {
2022 // If this reference is in an @implementation, also check for 'private'
2023 // methods.
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00002024 Setter = IFace->lookupPrivateClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002025 }
2026 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00002027 if (!Setter)
2028 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002029
2030 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
2031 return ExprError();
2032
2033 if (Getter || Setter) {
Douglas Gregore83b9562015-07-07 03:57:53 +00002034 if (!SuperType.isNull())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002035 return new (Context)
2036 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
2037 OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
Douglas Gregore83b9562015-07-07 03:57:53 +00002038 SuperType);
Douglas Gregor33823722011-06-11 01:09:30 +00002039
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002040 return new (Context) ObjCPropertyRefExpr(
2041 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
2042 propertyNameLoc, receiverNameLoc, IFace);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002043 }
2044 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
2045 << &propertyName << Context.getObjCInterfaceType(IFace));
2046}
2047
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002048namespace {
2049
2050class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
2051 public:
2052 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
2053 // Determine whether "super" is acceptable in the current context.
2054 if (Method && Method->getClassInterface())
2055 WantObjCSuper = Method->getClassInterface()->getSuperClass();
2056 }
2057
Craig Toppere14c0f82014-03-12 04:55:44 +00002058 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002059 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
2060 candidate.isKeyword("super");
2061 }
2062};
2063
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002064} // end anonymous namespace
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002065
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002066Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregore5798dc2010-04-21 20:38:13 +00002067 IdentifierInfo *Name,
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002068 SourceLocation NameLoc,
2069 bool IsSuper,
Douglas Gregore5798dc2010-04-21 20:38:13 +00002070 bool HasTrailingDot,
John McCallba7bf592010-08-24 05:47:05 +00002071 ParsedType &ReceiverType) {
David Blaikieefdccaa2016-01-15 23:43:34 +00002072 ReceiverType = nullptr;
Douglas Gregore5798dc2010-04-21 20:38:13 +00002073
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002074 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor57756ea2010-10-14 22:11:03 +00002075 // messaging super. If the identifier is "super" and there is a
2076 // trailing dot, it's an instance message.
2077 if (IsSuper && S->isInObjcMethodScope())
2078 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002079
2080 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
2081 LookupName(Result, S);
2082
2083 switch (Result.getResultKind()) {
2084 case LookupResult::NotFound:
Douglas Gregorca7136b2010-04-19 20:09:36 +00002085 // Normal name lookup didn't find anything. If we're in an
2086 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor57756ea2010-10-14 22:11:03 +00002087 // FIXME: This is a hack. Ivar lookup should be part of normal
2088 // lookup.
Douglas Gregorca7136b2010-04-19 20:09:36 +00002089 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidis3a8de5b2011-11-09 00:22:48 +00002090 if (!Method->getClassInterface()) {
2091 // Fall back: let the parser try to parse it as an instance message.
2092 return ObjCInstanceMessage;
2093 }
2094
Douglas Gregorca7136b2010-04-19 20:09:36 +00002095 ObjCInterfaceDecl *ClassDeclared;
2096 if (Method->getClassInterface()->lookupInstanceVariable(Name,
2097 ClassDeclared))
2098 return ObjCInstanceMessage;
2099 }
Douglas Gregor57756ea2010-10-14 22:11:03 +00002100
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002101 // Break out; we'll perform typo correction below.
2102 break;
2103
2104 case LookupResult::NotFoundInCurrentInstantiation:
2105 case LookupResult::FoundOverloaded:
2106 case LookupResult::FoundUnresolvedValue:
2107 case LookupResult::Ambiguous:
2108 Result.suppressDiagnostics();
2109 return ObjCInstanceMessage;
2110
2111 case LookupResult::Found: {
Fariborz Jahanian14889fc2011-02-08 00:23:07 +00002112 // If the identifier is a class or not, and there is a trailing dot,
2113 // it's an instance message.
2114 if (HasTrailingDot)
2115 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002116 // We found something. If it's a type, then we have a class
2117 // message. Otherwise, it's an instance message.
2118 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregore5798dc2010-04-21 20:38:13 +00002119 QualType T;
2120 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
2121 T = Context.getObjCInterfaceType(Class);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00002122 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
Douglas Gregore5798dc2010-04-21 20:38:13 +00002123 T = Context.getTypeDeclType(Type);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00002124 DiagnoseUseOfDecl(Type, NameLoc);
2125 }
2126 else
Douglas Gregore5798dc2010-04-21 20:38:13 +00002127 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002128
Douglas Gregore5798dc2010-04-21 20:38:13 +00002129 // We have a class message, and T is the type we're
2130 // messaging. Build source-location information for it.
2131 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +00002132 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregore5798dc2010-04-21 20:38:13 +00002133 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002134 }
2135 }
2136
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002137 if (TypoCorrection Corrected = CorrectTypo(
2138 Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr,
2139 llvm::make_unique<ObjCInterfaceOrSuperCCC>(getCurMethodDecl()),
2140 CTK_ErrorRecovery, nullptr, false, nullptr, false)) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002141 if (Corrected.isKeyword()) {
2142 // If we've found the keyword "super" (the only keyword that would be
2143 // returned by CorrectTypo), this is a send to super.
Richard Smithf9b15102013-08-17 00:46:16 +00002144 diagnoseTypo(Corrected,
2145 PDiag(diag::err_unknown_receiver_suggest) << Name);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002146 return ObjCSuperMessage;
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002147 } else if (ObjCInterfaceDecl *Class =
Richard Smithf9b15102013-08-17 00:46:16 +00002148 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002149 // If we found a declaration, correct when it refers to an Objective-C
2150 // class.
Richard Smithf9b15102013-08-17 00:46:16 +00002151 diagnoseTypo(Corrected,
2152 PDiag(diag::err_unknown_receiver_suggest) << Name);
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002153 QualType T = Context.getObjCInterfaceType(Class);
2154 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2155 ReceiverType = CreateParsedType(T, TSInfo);
2156 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002157 }
2158 }
Richard Smithf9b15102013-08-17 00:46:16 +00002159
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002160 // Fall back: let the parser try to parse it as an instance message.
2161 return ObjCInstanceMessage;
2162}
Steve Naroff9527bbf2009-03-09 21:12:44 +00002163
John McCalldadc5752010-08-24 06:29:42 +00002164ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002165 SourceLocation SuperLoc,
2166 Selector Sel,
2167 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002168 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002169 SourceLocation RBracLoc,
2170 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002171 // Determine whether we are inside a method or not.
Eli Friedman24af8502012-02-03 22:47:37 +00002172 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregor4fdba132010-04-21 20:01:04 +00002173 if (!Method) {
2174 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
2175 return ExprError();
2176 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002177
Douglas Gregor4fdba132010-04-21 20:01:04 +00002178 ObjCInterfaceDecl *Class = Method->getClassInterface();
2179 if (!Class) {
Richard Smithf8812672016-12-02 22:38:31 +00002180 Diag(SuperLoc, diag::err_no_super_class_message)
Douglas Gregor4fdba132010-04-21 20:01:04 +00002181 << Method->getDeclName();
2182 return ExprError();
2183 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002184
Douglas Gregore83b9562015-07-07 03:57:53 +00002185 QualType SuperTy(Class->getSuperClassType(), 0);
2186 if (SuperTy.isNull()) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002187 // The current class does not have a superclass.
Richard Smithf8812672016-12-02 22:38:31 +00002188 Diag(SuperLoc, diag::err_root_class_cannot_use_super)
Ted Kremenek499897b2011-01-23 17:21:34 +00002189 << Class->getIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002190 return ExprError();
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002191 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002192
Douglas Gregor4fdba132010-04-21 20:01:04 +00002193 // We are in a method whose class has a superclass, so 'super'
2194 // is acting as a keyword.
Jordan Rose2afd6612012-10-19 16:05:26 +00002195 if (Method->getSelector() == Sel)
2196 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber715abaf2011-08-22 17:25:57 +00002197
Jordan Rose2afd6612012-10-19 16:05:26 +00002198 if (Method->isInstanceMethod()) {
Douglas Gregor4fdba132010-04-21 20:01:04 +00002199 // Since we are in an instance method, this is an instance
2200 // message to the superclass instance.
Douglas Gregor4fdba132010-04-21 20:01:04 +00002201 SuperTy = Context.getObjCObjectPointerType(SuperTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00002202 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
2203 Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002204 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002205 }
Douglas Gregor4fdba132010-04-21 20:01:04 +00002206
2207 // Since we are in a class method, this is a class message to
2208 // the superclass.
Craig Topperc3ec1492014-05-26 06:22:03 +00002209 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
Douglas Gregore83b9562015-07-07 03:57:53 +00002210 SuperTy,
Craig Topperc3ec1492014-05-26 06:22:03 +00002211 SuperLoc, Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002212 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002213}
2214
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002215ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
2216 bool isSuperReceiver,
2217 SourceLocation Loc,
2218 Selector Sel,
2219 ObjCMethodDecl *Method,
2220 MultiExprArg Args) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002221 TypeSourceInfo *receiverTypeInfo = nullptr;
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002222 if (!ReceiverType.isNull())
2223 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
2224
2225 return BuildClassMessage(receiverTypeInfo, ReceiverType,
2226 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
2227 Sel, Method, Loc, Loc, Loc, Args,
2228 /*isImplicit=*/true);
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002229}
2230
Ted Kremeneke65b0862012-03-06 20:05:56 +00002231static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2232 unsigned DiagID,
2233 bool (*refactor)(const ObjCMessageExpr *,
2234 const NSAPI &, edit::Commit &)) {
2235 SourceLocation MsgLoc = Msg->getExprLoc();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002236 if (S.Diags.isIgnored(DiagID, MsgLoc))
Ted Kremeneke65b0862012-03-06 20:05:56 +00002237 return;
2238
2239 SourceManager &SM = S.SourceMgr;
2240 edit::Commit ECommit(SM, S.LangOpts);
2241 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2242 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2243 << Msg->getSelector() << Msg->getSourceRange();
2244 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2245 if (!ECommit.isCommitable())
2246 return;
2247 for (edit::Commit::edit_iterator
2248 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2249 const edit::Commit::Edit &Edit = *I;
2250 switch (Edit.Kind) {
2251 case edit::Commit::Act_Insert:
2252 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2253 Edit.Text,
2254 Edit.BeforePrev));
2255 break;
2256 case edit::Commit::Act_InsertFromRange:
2257 Builder.AddFixItHint(
2258 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2259 Edit.getInsertFromRange(SM),
2260 Edit.BeforePrev));
2261 break;
2262 case edit::Commit::Act_Remove:
2263 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2264 break;
2265 }
2266 }
2267 }
2268}
2269
2270static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2271 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2272 edit::rewriteObjCRedundantCallWithLiteral);
2273}
2274
Alex Lorenz0e23c612017-03-06 15:58:34 +00002275static void checkFoundationAPI(Sema &S, SourceLocation Loc,
2276 const ObjCMethodDecl *Method,
2277 ArrayRef<Expr *> Args, QualType ReceiverType,
2278 bool IsClassObjectCall) {
2279 // Check if this is a performSelector method that uses a selector that returns
2280 // a record or a vector type.
Alex Lorenz5ffe4e12017-03-23 10:46:05 +00002281 if (Method->getSelector().getMethodFamily() != OMF_performSelector ||
2282 Args.empty())
Alex Lorenz0e23c612017-03-06 15:58:34 +00002283 return;
2284 const auto *SE = dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens());
2285 if (!SE)
2286 return;
2287 ObjCMethodDecl *ImpliedMethod;
2288 if (!IsClassObjectCall) {
2289 const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>();
2290 if (!OPT || !OPT->getInterfaceDecl())
2291 return;
2292 ImpliedMethod =
2293 OPT->getInterfaceDecl()->lookupInstanceMethod(SE->getSelector());
2294 if (!ImpliedMethod)
2295 ImpliedMethod =
2296 OPT->getInterfaceDecl()->lookupPrivateMethod(SE->getSelector());
2297 } else {
2298 const auto *IT = ReceiverType->getAs<ObjCInterfaceType>();
2299 if (!IT)
2300 return;
2301 ImpliedMethod = IT->getDecl()->lookupClassMethod(SE->getSelector());
2302 if (!ImpliedMethod)
2303 ImpliedMethod =
2304 IT->getDecl()->lookupPrivateClassMethod(SE->getSelector());
2305 }
2306 if (!ImpliedMethod)
2307 return;
2308 QualType Ret = ImpliedMethod->getReturnType();
2309 if (Ret->isRecordType() || Ret->isVectorType() || Ret->isExtVectorType()) {
2310 QualType Ret = ImpliedMethod->getReturnType();
2311 S.Diag(Loc, diag::warn_objc_unsafe_perform_selector)
2312 << Method->getSelector()
2313 << (!Ret->isRecordType()
2314 ? /*Vector*/ 2
2315 : Ret->isUnionType() ? /*Union*/ 1 : /*Struct*/ 0);
2316 S.Diag(ImpliedMethod->getLocStart(),
2317 diag::note_objc_unsafe_perform_selector_method_declared_here)
2318 << ImpliedMethod->getSelector() << Ret;
2319 }
2320}
2321
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002322/// \brief Diagnose use of %s directive in an NSString which is being passed
2323/// as formatting string to formatting method.
2324static void
2325DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S,
2326 ObjCMethodDecl *Method,
2327 Selector Sel,
2328 Expr **Args, unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002329 unsigned Idx = 0;
2330 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002331 ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily();
2332 if (SFFamily == ObjCStringFormatFamily::SFF_NSString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002333 Idx = 0;
2334 Format = true;
2335 }
2336 else if (Method) {
2337 for (const auto *I : Method->specific_attrs<FormatAttr>()) {
2338 if (S.GetFormatNSStringIdx(I, Idx)) {
2339 Format = true;
2340 break;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002341 }
2342 }
2343 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002344 if (!Format || NumArgs <= Idx)
2345 return;
2346
2347 Expr *FormatExpr = Args[Idx];
2348 if (ObjCStringLiteral *OSL =
2349 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) {
2350 StringLiteral *FormatString = OSL->getString();
2351 if (S.FormatStringHasSArg(FormatString)) {
2352 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2353 << "%s" << 0 << 0;
2354 if (Method)
2355 S.Diag(Method->getLocation(), diag::note_method_declared_at)
2356 << Method->getDeclName();
2357 }
2358 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002359}
2360
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002361/// \brief Build an Objective-C class message expression.
2362///
2363/// This routine takes care of both normal class messages and
2364/// class messages to the superclass.
2365///
2366/// \param ReceiverTypeInfo Type source information that describes the
2367/// receiver of this message. This may be NULL, in which case we are
2368/// sending to the superclass and \p SuperLoc must be a valid source
2369/// location.
2370
2371/// \param ReceiverType The type of the object receiving the
2372/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2373/// type as that refers to. For a superclass send, this is the type of
2374/// the superclass.
2375///
2376/// \param SuperLoc The location of the "super" keyword in a
2377/// superclass message.
2378///
2379/// \param Sel The selector to which the message is being sent.
2380///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002381/// \param Method The method that this class message is invoking, if
2382/// already known.
2383///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002384/// \param LBracLoc The location of the opening square bracket ']'.
2385///
James Dennettffad8b72012-06-22 08:10:18 +00002386/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002387///
James Dennettffad8b72012-06-22 08:10:18 +00002388/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002389ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002390 QualType ReceiverType,
2391 SourceLocation SuperLoc,
2392 Selector Sel,
2393 ObjCMethodDecl *Method,
2394 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002395 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002396 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002397 MultiExprArg ArgsIn,
2398 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002399 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00002400 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002401 if (LBracLoc.isInvalid()) {
2402 Diag(Loc, diag::err_missing_open_square_message_send)
2403 << FixItHint::CreateInsertion(Loc, "[");
2404 LBracLoc = Loc;
2405 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002406 SourceLocation SelLoc;
2407 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2408 SelLoc = SelectorLocs.front();
2409 else
2410 SelLoc = Loc;
2411
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002412 if (ReceiverType->isDependentType()) {
2413 // If the receiver type is dependent, we can't type-check anything
2414 // at this point. Build a dependent expression.
2415 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002416 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002417 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002418 return ObjCMessageExpr::Create(
2419 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
2420 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2421 isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002422 }
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002423
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002424 // Find the class to which we are sending this message.
Craig Topperc3ec1492014-05-26 06:22:03 +00002425 ObjCInterfaceDecl *Class = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00002426 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2427 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002428 Diag(Loc, diag::err_invalid_receiver_class_message)
2429 << ReceiverType;
2430 return ExprError();
Steve Naroffe2177fb2008-07-25 19:39:00 +00002431 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002432 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanianc27cd1b2011-10-15 19:18:36 +00002433 // objc++ diagnoses during typename annotation.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002434 if (!getLangOpts().CPlusPlus)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002435 (void)DiagnoseUseOfDecl(Class, SelLoc);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002436 // Find the method we are messaging.
Douglas Gregorb5186b12010-04-22 17:01:48 +00002437 if (!Method) {
Douglas Gregor4123a862011-11-14 22:10:01 +00002438 SourceRange TypeRange
2439 = SuperLoc.isValid()? SourceRange(SuperLoc)
2440 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002441 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002442 (getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002443 ? diag::err_arc_receiver_forward_class
2444 : diag::warn_receiver_forward_class),
2445 TypeRange)) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002446 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorb5186b12010-04-22 17:01:48 +00002447 Method = LookupFactoryMethodInGlobalPool(Sel,
2448 SourceRange(LBracLoc, RBracLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00002449 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002450 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2451 << Method->getDeclName();
2452 }
2453 if (!Method)
2454 Method = Class->lookupClassMethod(Sel);
2455
2456 // If we have an implementation in scope, check "private" methods.
2457 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002458 Method = Class->lookupPrivateClassMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002459
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002460 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002461 return ExprError();
Fariborz Jahanian1bd844d2009-05-08 23:02:36 +00002462 }
Mike Stump11289f42009-09-09 15:08:12 +00002463
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002464 // Check the argument types and determine the result type.
2465 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002466 ExprValueKind VK = VK_RValue;
2467
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002468 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002469 Expr **Args = ArgsIn.data();
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002470 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2471 Sel, SelectorLocs,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00002472 Method, true,
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00002473 SuperLoc.isValid(), LBracLoc, RBracLoc,
2474 SourceRange(),
Douglas Gregor33823722011-06-11 01:09:30 +00002475 ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002476 return ExprError();
Ted Kremeneka3a37ae2008-06-24 15:50:53 +00002477
Alp Toker314cc812014-01-25 16:55:45 +00002478 if (Method && !Method->getReturnType()->isVoidType() &&
2479 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002480 diag::err_illegal_message_expr_incomplete_type))
2481 return ExprError();
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002482
Fariborz Jahaniane8b45502014-08-22 19:52:49 +00002483 // Warn about explicit call of +initialize on its own class. But not on 'super'.
Fariborz Jahanian42292282014-08-25 21:27:38 +00002484 if (Method && Method->getMethodFamily() == OMF_initialize) {
2485 if (!SuperLoc.isValid()) {
2486 const ObjCInterfaceDecl *ID =
2487 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext());
2488 if (ID == Class) {
2489 Diag(Loc, diag::warn_direct_initialize_call);
2490 Diag(Method->getLocation(), diag::note_method_declared_at)
2491 << Method->getDeclName();
2492 }
2493 }
2494 else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2495 // [super initialize] is allowed only within an +initialize implementation
2496 if (CurMeth->getMethodFamily() != OMF_initialize) {
2497 Diag(Loc, diag::warn_direct_super_initialize_call);
2498 Diag(Method->getLocation(), diag::note_method_declared_at)
2499 << Method->getDeclName();
2500 Diag(CurMeth->getLocation(), diag::note_method_declared_at)
2501 << CurMeth->getDeclName();
2502 }
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002503 }
2504 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002505
2506 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2507
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002508 // Construct the appropriate ObjCMessageExpr.
Ted Kremeneke65b0862012-03-06 20:05:56 +00002509 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002510 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002511 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002512 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002513 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002514 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002515 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002516 else {
John McCall7decc9e2010-11-18 06:31:45 +00002517 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002518 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002519 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002520 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002521 if (!isImplicit)
2522 checkCocoaAPI(*this, Result);
2523 }
Alex Lorenz0e23c612017-03-06 15:58:34 +00002524 if (Method)
2525 checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
2526 ReceiverType, /*IsClassObjectCall=*/true);
Douglas Gregoraae38d62010-05-22 05:17:18 +00002527 return MaybeBindToTemporary(Result);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002528}
2529
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002530// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002531// ArgExprs is optional - if it is present, the number of expressions
2532// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002533ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor3e972002010-09-15 23:19:31 +00002534 ParsedType Receiver,
2535 Selector Sel,
2536 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002537 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor3e972002010-09-15 23:19:31 +00002538 SourceLocation RBracLoc,
2539 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002540 TypeSourceInfo *ReceiverTypeInfo;
2541 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2542 if (ReceiverType.isNull())
2543 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002544
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002545 if (!ReceiverTypeInfo)
2546 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2547
2548 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002549 /*SuperLoc=*/SourceLocation(), Sel,
2550 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2551 Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002552}
2553
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002554ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2555 QualType ReceiverType,
2556 SourceLocation Loc,
2557 Selector Sel,
2558 ObjCMethodDecl *Method,
2559 MultiExprArg Args) {
2560 return BuildInstanceMessage(Receiver, ReceiverType,
2561 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2562 Sel, Method, Loc, Loc, Loc, Args,
2563 /*isImplicit=*/true);
2564}
2565
Alex Lorenz5e895cf2017-03-15 17:16:41 +00002566static bool isMethodDeclaredInRootProtocol(Sema &S, const ObjCMethodDecl *M) {
2567 if (!S.NSAPIObj)
2568 return false;
2569 const auto *Protocol = dyn_cast<ObjCProtocolDecl>(M->getDeclContext());
2570 if (!Protocol)
2571 return false;
2572 const IdentifierInfo *II = S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
2573 if (const auto *RootClass = dyn_cast_or_null<ObjCInterfaceDecl>(
2574 S.LookupSingleName(S.TUScope, II, Protocol->getLocStart(),
2575 Sema::LookupOrdinaryName))) {
2576 for (const ObjCProtocolDecl *P : RootClass->all_referenced_protocols()) {
2577 if (P->getCanonicalDecl() == Protocol->getCanonicalDecl())
2578 return true;
2579 }
2580 }
2581 return false;
2582}
2583
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002584/// \brief Build an Objective-C instance message expression.
2585///
2586/// This routine takes care of both normal instance messages and
2587/// instance messages to the superclass instance.
2588///
2589/// \param Receiver The expression that computes the object that will
2590/// receive this message. This may be empty, in which case we are
2591/// sending to the superclass instance and \p SuperLoc must be a valid
2592/// source location.
2593///
2594/// \param ReceiverType The (static) type of the object receiving the
2595/// message. When a \p Receiver expression is provided, this is the
2596/// same type as that expression. For a superclass instance send, this
2597/// is a pointer to the type of the superclass.
2598///
2599/// \param SuperLoc The location of the "super" keyword in a
2600/// superclass instance message.
2601///
2602/// \param Sel The selector to which the message is being sent.
2603///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002604/// \param Method The method that this instance message is invoking, if
2605/// already known.
2606///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002607/// \param LBracLoc The location of the opening square bracket ']'.
2608///
James Dennettffad8b72012-06-22 08:10:18 +00002609/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002610///
James Dennettffad8b72012-06-22 08:10:18 +00002611/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002612ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002613 QualType ReceiverType,
2614 SourceLocation SuperLoc,
2615 Selector Sel,
2616 ObjCMethodDecl *Method,
2617 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002618 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002619 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002620 MultiExprArg ArgsIn,
2621 bool isImplicit) {
Chandler Carruth3d402842016-11-04 06:11:54 +00002622 assert((Receiver || SuperLoc.isValid()) && "If the Receiver is null, the "
2623 "SuperLoc must be valid so we can "
2624 "use it instead.");
2625
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002626 // The location of the receiver.
2627 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002628 SourceRange RecRange =
2629 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2630 SourceLocation SelLoc;
2631 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2632 SelLoc = SelectorLocs.front();
2633 else
2634 SelLoc = Loc;
2635
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002636 if (LBracLoc.isInvalid()) {
2637 Diag(Loc, diag::err_missing_open_square_message_send)
2638 << FixItHint::CreateInsertion(Loc, "[");
2639 LBracLoc = Loc;
2640 }
2641
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002642 // If we have a receiver expression, perform appropriate promotions
2643 // and determine receiver type.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002644 if (Receiver) {
John McCall4124c492011-10-17 18:40:02 +00002645 if (Receiver->hasPlaceholderType()) {
Douglas Gregord8fb1e32011-12-01 01:37:36 +00002646 ExprResult Result;
2647 if (Receiver->getType() == Context.UnknownAnyTy)
2648 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2649 else
2650 Result = CheckPlaceholderExpr(Receiver);
2651 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002652 Receiver = Result.get();
John McCall4124c492011-10-17 18:40:02 +00002653 }
2654
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002655 if (Receiver->isTypeDependent()) {
2656 // If the receiver is type-dependent, we can't type-check anything
2657 // at this point. Build a dependent expression.
2658 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002659 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002660 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002661 return ObjCMessageExpr::Create(
2662 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
2663 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2664 RBracLoc, isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002665 }
2666
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002667 // If necessary, apply function/array conversion to the receiver.
2668 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00002669 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2670 if (Result.isInvalid())
2671 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002672 Receiver = Result.get();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002673 ReceiverType = Receiver->getType();
John McCall80c93a02013-03-01 09:20:14 +00002674
2675 // If the receiver is an ObjC pointer, a block pointer, or an
2676 // __attribute__((NSObject)) pointer, we don't need to do any
2677 // special conversion in order to look up a receiver.
2678 if (ReceiverType->isObjCRetainableType()) {
2679 // do nothing
2680 } else if (!getLangOpts().ObjCAutoRefCount &&
2681 !Context.getObjCIdType().isNull() &&
2682 (ReceiverType->isPointerType() ||
2683 ReceiverType->isIntegerType())) {
2684 // Implicitly convert integers and pointers to 'id' but emit a warning.
2685 // But not in ARC.
2686 Diag(Loc, diag::warn_bad_receiver_type)
2687 << ReceiverType
2688 << Receiver->getSourceRange();
2689 if (ReceiverType->isPointerType()) {
2690 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002691 CK_CPointerToObjCPointerCast).get();
John McCall80c93a02013-03-01 09:20:14 +00002692 } else {
2693 // TODO: specialized warning on null receivers?
2694 bool IsNull = Receiver->isNullPointerConstant(Context,
2695 Expr::NPC_ValueDependentIsNull);
2696 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2697 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002698 Kind).get();
John McCall80c93a02013-03-01 09:20:14 +00002699 }
2700 ReceiverType = Receiver->getType();
2701 } else if (getLangOpts().CPlusPlus) {
Douglas Gregor4b60a152013-11-07 22:34:54 +00002702 // The receiver must be a complete type.
2703 if (RequireCompleteType(Loc, Receiver->getType(),
2704 diag::err_incomplete_receiver_type))
2705 return ExprError();
2706
John McCall80c93a02013-03-01 09:20:14 +00002707 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2708 if (result.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002709 Receiver = result.get();
John McCall80c93a02013-03-01 09:20:14 +00002710 ReceiverType = Receiver->getType();
2711 }
2712 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002713 }
2714
Alex Lorenzd9f12842017-08-25 16:12:17 +00002715 if (ReceiverType->isObjCIdType() && !isImplicit)
2716 Diag(Receiver->getExprLoc(), diag::warn_messaging_unqualified_id);
2717
John McCall80c93a02013-03-01 09:20:14 +00002718 // There's a somewhat weird interaction here where we assume that we
2719 // won't actually have a method unless we also don't need to do some
2720 // of the more detailed type-checking on the receiver.
2721
Douglas Gregorb5186b12010-04-22 17:01:48 +00002722 if (!Method) {
Douglas Gregorab209d82015-07-07 03:58:42 +00002723 // Handle messages to id and __kindof types (where we use the
2724 // global method pool).
Douglas Gregorab209d82015-07-07 03:58:42 +00002725 const ObjCObjectType *typeBound = nullptr;
2726 bool receiverIsIdLike = ReceiverType->isObjCIdOrObjectKindOfType(Context,
2727 typeBound);
2728 if (receiverIsIdLike || ReceiverType->isBlockPointerType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002729 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
Manman Rend2a3cd72016-04-07 19:30:20 +00002730 SmallVector<ObjCMethodDecl*, 4> Methods;
Manman Ren7ed4f982016-04-07 19:32:24 +00002731 // If we have a type bound, further filter the methods.
Manman Rend2a3cd72016-04-07 19:30:20 +00002732 CollectMultipleMethodsInGlobalPool(Sel, Methods, true/*InstanceFirst*/,
Manman Ren7ed4f982016-04-07 19:32:24 +00002733 true/*CheckTheOther*/, typeBound);
Manman Rend2a3cd72016-04-07 19:30:20 +00002734 if (!Methods.empty()) {
George Burgess IV52d07de2016-09-01 01:26:58 +00002735 // We choose the first method as the initial candidate, then try to
Manman Rend2a3cd72016-04-07 19:30:20 +00002736 // select a better one.
2737 Method = Methods[0];
2738
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00002739 if (ObjCMethodDecl *BestMethod =
Manman Rend2a3cd72016-04-07 19:30:20 +00002740 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(), Methods))
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00002741 Method = BestMethod;
Manman Rend2a3cd72016-04-07 19:30:20 +00002742
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002743 if (!AreMultipleMethodsInGlobalPool(Sel, Method,
2744 SourceRange(LBracLoc, RBracLoc),
Manman Rend2a3cd72016-04-07 19:30:20 +00002745 receiverIsIdLike, Methods))
2746 DiagnoseUseOfDecl(Method, SelLoc);
Fariborz Jahanian05e77f82014-11-07 23:51:15 +00002747 }
Douglas Gregorab209d82015-07-07 03:58:42 +00002748 } else if (ReceiverType->isObjCClassOrClassKindOfType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002749 ReceiverType->isObjCQualifiedClassType()) {
2750 // Handle messages to Class.
Nico Weber2e0c8f72014-12-27 03:58:08 +00002751 // We allow sending a message to a qualified Class ("Class<foo>"), which
2752 // is ok as long as one of the protocols implements the selector (if not,
2753 // warn).
Douglas Gregorab209d82015-07-07 03:58:42 +00002754 if (!ReceiverType->isObjCClassOrClassKindOfType()) {
2755 const ObjCObjectPointerType *QClassTy
2756 = ReceiverType->getAsObjCQualifiedClassType();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002757 // Search protocols for class methods.
2758 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2759 if (!Method) {
2760 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2761 // warn if instance method found for a Class message.
Alex Lorenz5e895cf2017-03-15 17:16:41 +00002762 if (Method && !isMethodDeclaredInRootProtocol(*this, Method)) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002763 Diag(SelLoc, diag::warn_instance_method_on_class_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002764 << Method->getSelector() << Sel;
Ted Kremenek59b10db2012-02-27 22:55:11 +00002765 Diag(Method->getLocation(), diag::note_method_declared_at)
2766 << Method->getDeclName();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002767 }
Steve Naroff3f49fee2009-03-04 15:11:40 +00002768 }
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002769 } else {
2770 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2771 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2772 // First check the public methods in the class interface.
2773 Method = ClassDecl->lookupClassMethod(Sel);
2774
2775 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002776 Method = ClassDecl->lookupPrivateClassMethod(Sel);
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002777 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002778 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002779 return ExprError();
2780 }
2781 if (!Method) {
2782 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregor486b74e2011-09-27 16:10:05 +00002783 if (!Receiver || !isSelfExpr(Receiver)) {
Manman Rend2a3cd72016-04-07 19:30:20 +00002784 // If no class (factory) method was found, check if an _instance_
2785 // method of the same name exists in the root class only.
2786 SmallVector<ObjCMethodDecl*, 4> Methods;
2787 CollectMultipleMethodsInGlobalPool(Sel, Methods,
2788 false/*InstanceFirst*/,
2789 true/*CheckTheOther*/);
2790 if (!Methods.empty()) {
George Burgess IV52d07de2016-09-01 01:26:58 +00002791 // We choose the first method as the initial candidate, then try
Manman Rend2a3cd72016-04-07 19:30:20 +00002792 // to select a better one.
2793 Method = Methods[0];
2794
2795 // If we find an instance method, emit waring.
2796 if (Method->isInstanceMethod()) {
2797 if (const ObjCInterfaceDecl *ID =
2798 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2799 if (ID->getSuperClass())
2800 Diag(SelLoc, diag::warn_root_inst_method_not_found)
2801 << Sel << SourceRange(LBracLoc, RBracLoc);
2802 }
2803 }
2804
2805 if (ObjCMethodDecl *BestMethod =
2806 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
2807 Methods))
2808 Method = BestMethod;
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002809 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002810 }
2811 }
2812 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002813 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00002814 ObjCInterfaceDecl *ClassDecl = nullptr;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002815
2816 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2817 // long as one of the protocols implements the selector (if not, warn).
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002818 // And as long as message is not deprecated/unavailable (warn if it is).
Douglas Gregorb5186b12010-04-22 17:01:48 +00002819 if (const ObjCObjectPointerType *QIdTy
2820 = ReceiverType->getAsObjCQualifiedIdType()) {
2821 // Search protocols for instance methods.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002822 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2823 if (!Method)
2824 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002825 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002826 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002827 } else if (const ObjCObjectPointerType *OCIType
2828 = ReceiverType->getAsObjCInterfacePointerType()) {
2829 // We allow sending a message to a pointer to an interface (an object).
2830 ClassDecl = OCIType->getInterfaceDecl();
John McCall31168b02011-06-15 23:02:42 +00002831
Douglas Gregor4123a862011-11-14 22:10:01 +00002832 // Try to complete the type. Under ARC, this is a hard error from which
2833 // we don't try to recover.
Richard Smithdb0ac552015-12-18 22:40:25 +00002834 // FIXME: In the non-ARC case, this will still be a hard error if the
2835 // definition is found in a module that's not visible.
Craig Topperc3ec1492014-05-26 06:22:03 +00002836 const ObjCInterfaceDecl *forwardClass = nullptr;
Douglas Gregor4123a862011-11-14 22:10:01 +00002837 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002838 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002839 ? diag::err_arc_receiver_forward_instance
2840 : diag::warn_receiver_forward_instance,
2841 Receiver? Receiver->getSourceRange()
2842 : SourceRange(SuperLoc))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002843 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregor4123a862011-11-14 22:10:01 +00002844 return ExprError();
2845
2846 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanianc934de62012-02-03 01:02:44 +00002847 Diag(Receiver ? Receiver->getLocStart()
2848 : SuperLoc, diag::note_receiver_is_id);
Craig Topperc3ec1492014-05-26 06:22:03 +00002849 Method = nullptr;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002850 } else {
2851 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCall31168b02011-06-15 23:02:42 +00002852 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002853
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002854 if (!Method)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002855 // Search protocol qualifiers.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002856 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2857
Douglas Gregorb5186b12010-04-22 17:01:48 +00002858 if (!Method) {
2859 // If we have implementations in scope, check "private" methods.
Anna Zaksc77a3b12012-07-27 19:07:44 +00002860 Method = ClassDecl->lookupPrivateMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002861
David Blaikiebbafb8a2012-03-11 07:00:24 +00002862 if (!Method && getLangOpts().ObjCAutoRefCount) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002863 Diag(SelLoc, diag::err_arc_may_not_respond)
2864 << OCIType->getPointeeType() << Sel << RecRange
Fariborz Jahanian32c13502012-11-28 01:27:44 +00002865 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
John McCall31168b02011-06-15 23:02:42 +00002866 return ExprError();
2867 }
2868
Douglas Gregor486b74e2011-09-27 16:10:05 +00002869 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002870 // If we still haven't found a method, look in the global pool. This
2871 // behavior isn't very desirable, however we need it for GCC
2872 // compatibility. FIXME: should we deviate??
2873 if (OCIType->qual_empty()) {
Manman Rend2a3cd72016-04-07 19:30:20 +00002874 SmallVector<ObjCMethodDecl*, 4> Methods;
2875 CollectMultipleMethodsInGlobalPool(Sel, Methods,
2876 true/*InstanceFirst*/,
2877 false/*CheckTheOther*/);
2878 if (!Methods.empty()) {
George Burgess IV52d07de2016-09-01 01:26:58 +00002879 // We choose the first method as the initial candidate, then try
Manman Rend2a3cd72016-04-07 19:30:20 +00002880 // to select a better one.
2881 Method = Methods[0];
2882
2883 if (ObjCMethodDecl *BestMethod =
2884 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
2885 Methods))
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002886 Method = BestMethod;
Manman Rend2a3cd72016-04-07 19:30:20 +00002887
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002888 AreMultipleMethodsInGlobalPool(Sel, Method,
2889 SourceRange(LBracLoc, RBracLoc),
Manman Rend2a3cd72016-04-07 19:30:20 +00002890 true/*receiverIdOrClass*/,
2891 Methods);
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002892 }
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +00002893 if (Method && !forwardClass)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002894 Diag(SelLoc, diag::warn_maynot_respond)
2895 << OCIType->getInterfaceDecl()->getIdentifier()
2896 << Sel << RecRange;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002897 }
2898 }
2899 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002900 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002901 return ExprError();
John McCallfec112d2011-09-09 06:11:02 +00002902 } else {
John McCall80c93a02013-03-01 09:20:14 +00002903 // Reject other random receiver types (e.g. structs).
2904 Diag(Loc, diag::err_bad_receiver_type)
2905 << ReceiverType << Receiver->getSourceRange();
2906 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002907 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002908 }
Chris Lattner6b946cc2008-07-21 05:57:44 +00002909 }
Mike Stump11289f42009-09-09 15:08:12 +00002910
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002911 FunctionScopeInfo *DIFunctionScopeInfo =
2912 (Method && Method->getMethodFamily() == OMF_init)
Craig Topperc3ec1492014-05-26 06:22:03 +00002913 ? getEnclosingFunction() : nullptr;
2914
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002915 if (DIFunctionScopeInfo &&
2916 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002917 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2918 bool isDesignatedInitChain = false;
2919 if (SuperLoc.isValid()) {
2920 if (const ObjCObjectPointerType *
2921 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2922 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
Argyrios Kyrtzidisd664a342013-12-13 03:48:17 +00002923 // Either we know this is a designated initializer or we
2924 // conservatively assume it because we don't know for sure.
2925 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2926 ID->isDesignatedInitializer(Sel)) {
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002927 isDesignatedInitChain = true;
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002928 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002929 }
2930 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002931 }
2932 }
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002933 if (!isDesignatedInitChain) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002934 const ObjCMethodDecl *InitMethod = nullptr;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002935 bool isDesignated =
2936 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2937 assert(isDesignated && InitMethod);
2938 (void)isDesignated;
2939 Diag(SelLoc, SuperLoc.isValid() ?
2940 diag::warn_objc_designated_init_non_designated_init_call :
2941 diag::warn_objc_designated_init_non_super_designated_init_call);
2942 Diag(InitMethod->getLocation(),
2943 diag::note_objc_designated_init_marked_here);
2944 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002945 }
2946
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002947 if (DIFunctionScopeInfo &&
2948 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002949 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2950 if (SuperLoc.isValid()) {
2951 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2952 } else {
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002953 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002954 }
2955 }
2956
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002957 // Check the message arguments.
2958 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002959 Expr **Args = ArgsIn.data();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002960 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002961 ExprValueKind VK = VK_RValue;
Fariborz Jahanian68500912010-12-01 01:07:24 +00002962 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2963 ReceiverType->isObjCQualifiedClassType());
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002964 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2965 Sel, SelectorLocs, Method,
Douglas Gregor33823722011-06-11 01:09:30 +00002966 ClassMessage, SuperLoc.isValid(),
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00002967 LBracLoc, RBracLoc, RecRange, ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002968 return ExprError();
Alp Toker314cc812014-01-25 16:55:45 +00002969
2970 if (Method && !Method->getReturnType()->isVoidType() &&
2971 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002972 diag::err_illegal_message_expr_incomplete_type))
2973 return ExprError();
Douglas Gregor9a129192010-04-21 00:45:42 +00002974
John McCall31168b02011-06-15 23:02:42 +00002975 // In ARC, forbid the user from sending messages to
2976 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002977 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002978 ObjCMethodFamily family =
2979 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2980 switch (family) {
2981 case OMF_init:
2982 if (Method)
2983 checkInitMethod(Method, ReceiverType);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00002984 break;
John McCall31168b02011-06-15 23:02:42 +00002985
2986 case OMF_None:
2987 case OMF_alloc:
2988 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00002989 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002990 case OMF_mutableCopy:
2991 case OMF_new:
2992 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002993 case OMF_initialize:
John McCall31168b02011-06-15 23:02:42 +00002994 break;
2995
2996 case OMF_dealloc:
2997 case OMF_retain:
2998 case OMF_release:
2999 case OMF_autorelease:
3000 case OMF_retainCount:
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00003001 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
3002 << Sel << RecRange;
John McCall31168b02011-06-15 23:02:42 +00003003 break;
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003004
3005 case OMF_performSelector:
3006 if (Method && NumArgs >= 1) {
Alex Lorenz51c01282017-02-20 17:55:15 +00003007 if (const auto *SelExp =
3008 dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens())) {
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003009 Selector ArgSel = SelExp->getSelector();
3010 ObjCMethodDecl *SelMethod =
3011 LookupInstanceMethodInGlobalPool(ArgSel,
3012 SelExp->getSourceRange());
3013 if (!SelMethod)
3014 SelMethod =
3015 LookupFactoryMethodInGlobalPool(ArgSel,
3016 SelExp->getSourceRange());
3017 if (SelMethod) {
3018 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
3019 switch (SelFamily) {
3020 case OMF_alloc:
3021 case OMF_copy:
3022 case OMF_mutableCopy:
3023 case OMF_new:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003024 case OMF_init:
3025 // Issue error, unless ns_returns_not_retained.
3026 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
3027 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00003028 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003029 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00003030 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
3031 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003032 }
3033 break;
3034 default:
3035 // +0 call. OK. unless ns_returns_retained.
3036 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
3037 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00003038 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003039 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00003040 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
3041 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003042 }
3043 break;
3044 }
3045 }
3046 } else {
3047 // error (may leak).
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00003048 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003049 Diag(Args[0]->getExprLoc(), diag::note_used_here);
3050 }
3051 }
3052 break;
John McCall31168b02011-06-15 23:02:42 +00003053 }
3054 }
3055
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003056 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
3057
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003058 // Construct the appropriate ObjCMessageExpr instance.
John McCall31168b02011-06-15 23:02:42 +00003059 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003060 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00003061 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00003062 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00003063 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00003064 makeArrayRef(Args, NumArgs), RBracLoc,
3065 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00003066 else {
John McCall7decc9e2010-11-18 06:31:45 +00003067 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00003068 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00003069 makeArrayRef(Args, NumArgs), RBracLoc,
3070 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00003071 if (!isImplicit)
3072 checkCocoaAPI(*this, Result);
3073 }
Alex Lorenz0e23c612017-03-06 15:58:34 +00003074 if (Method) {
3075 bool IsClassObjectCall = ClassMessage;
3076 // 'self' message receivers in class methods should be treated as message
3077 // sends to the class object in order for the semantic checks to be
3078 // performed correctly. Messages to 'super' already count as class messages,
3079 // so they don't need to be handled here.
3080 if (Receiver && isSelfExpr(Receiver)) {
3081 if (const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>()) {
3082 if (OPT->getObjectType()->isObjCClass()) {
3083 if (const auto *CurMeth = getCurMethodDecl()) {
3084 IsClassObjectCall = true;
3085 ReceiverType =
3086 Context.getObjCInterfaceType(CurMeth->getClassInterface());
3087 }
3088 }
3089 }
3090 }
3091 checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
3092 ReceiverType, IsClassObjectCall);
3093 }
John McCall31168b02011-06-15 23:02:42 +00003094
David Blaikiebbafb8a2012-03-11 07:00:24 +00003095 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00003096 // In ARC, annotate delegate init calls.
3097 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregor486b74e2011-09-27 16:10:05 +00003098 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCall31168b02011-06-15 23:02:42 +00003099 // Only consider init calls *directly* in init implementations,
3100 // not within blocks.
3101 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
3102 if (method && method->getMethodFamily() == OMF_init) {
3103 // The implicit assignment to self means we also don't want to
3104 // consume the result.
3105 Result->setDelegateInitCall(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003106 return Result;
John McCall31168b02011-06-15 23:02:42 +00003107 }
3108 }
3109
3110 // In ARC, check for message sends which are likely to introduce
3111 // retain cycles.
3112 checkRetainCycles(Result);
Brian Kelleycafd9122017-03-29 17:55:11 +00003113 }
Jordan Rose22487652012-10-11 16:06:21 +00003114
Brian Kelleycafd9122017-03-29 17:55:11 +00003115 if (getLangOpts().ObjCWeak) {
Jordan Rose22487652012-10-11 16:06:21 +00003116 if (!isImplicit && Method) {
3117 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
3118 bool IsWeak =
3119 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
3120 if (!IsWeak && Sel.isUnarySelector())
3121 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003122 if (IsWeak &&
3123 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
3124 getCurFunction()->recordUseOfWeak(Result, Prop);
Jordan Rose22487652012-10-11 16:06:21 +00003125 }
3126 }
John McCall31168b02011-06-15 23:02:42 +00003127 }
Alex Denisove1d882c2015-03-04 17:55:52 +00003128
3129 CheckObjCCircularContainer(Result);
3130
Douglas Gregoraae38d62010-05-22 05:17:18 +00003131 return MaybeBindToTemporary(Result);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003132}
3133
Fariborz Jahanian02447d82013-01-22 18:35:43 +00003134static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
3135 if (ObjCSelectorExpr *OSE =
3136 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
3137 Selector Sel = OSE->getSelector();
3138 SourceLocation Loc = OSE->getAtLoc();
Chandler Carruth12c8f652015-03-27 00:55:05 +00003139 auto Pos = S.ReferencedSelectors.find(Sel);
Fariborz Jahanian02447d82013-01-22 18:35:43 +00003140 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
3141 S.ReferencedSelectors.erase(Pos);
3142 }
3143}
3144
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003145// ActOnInstanceMessage - used for both unary and keyword messages.
3146// ArgExprs is optional - if it is present, the number of expressions
3147// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00003148ExprResult Sema::ActOnInstanceMessage(Scope *S,
3149 Expr *Receiver,
3150 Selector Sel,
3151 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00003152 ArrayRef<SourceLocation> SelectorLocs,
John McCalldadc5752010-08-24 06:29:42 +00003153 SourceLocation RBracLoc,
3154 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003155 if (!Receiver)
3156 return ExprError();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00003157
3158 // A ParenListExpr can show up while doing error recovery with invalid code.
3159 if (isa<ParenListExpr>(Receiver)) {
3160 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
3161 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003162 Receiver = Result.get();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00003163 }
Fariborz Jahanian17748062013-01-22 19:05:17 +00003164
3165 if (RespondsToSelectorSel.isNull()) {
3166 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
3167 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
3168 }
3169 if (Sel == RespondsToSelectorSel)
Fariborz Jahanian02447d82013-01-22 18:35:43 +00003170 RemoveSelectorFromWarningCache(*this, Args[0]);
Craig Topperc3ec1492014-05-26 06:22:03 +00003171
John McCallb268a282010-08-23 23:25:46 +00003172 return BuildInstanceMessage(Receiver, Receiver->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003173 /*SuperLoc=*/SourceLocation(), Sel,
3174 /*Method=*/nullptr, LBracLoc, SelectorLocs,
3175 RBracLoc, Args);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00003176}
Chris Lattner2a3569b2008-04-07 05:30:13 +00003177
John McCall31168b02011-06-15 23:02:42 +00003178enum ARCConversionTypeClass {
John McCalle4fe2452011-10-01 01:01:08 +00003179 /// int, void, struct A
John McCall31168b02011-06-15 23:02:42 +00003180 ACTC_none,
John McCalle4fe2452011-10-01 01:01:08 +00003181
3182 /// id, void (^)()
John McCall31168b02011-06-15 23:02:42 +00003183 ACTC_retainable,
John McCalle4fe2452011-10-01 01:01:08 +00003184
3185 /// id*, id***, void (^*)(),
3186 ACTC_indirectRetainable,
3187
3188 /// void* might be a normal C type, or it might a CF type.
3189 ACTC_voidPtr,
3190
3191 /// struct A*
3192 ACTC_coreFoundation
John McCall31168b02011-06-15 23:02:42 +00003193};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003194
John McCalle4fe2452011-10-01 01:01:08 +00003195static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
3196 return (ACTC == ACTC_retainable ||
3197 ACTC == ACTC_coreFoundation ||
3198 ACTC == ACTC_voidPtr);
3199}
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003200
John McCalle4fe2452011-10-01 01:01:08 +00003201static bool isAnyCLike(ARCConversionTypeClass ACTC) {
3202 return ACTC == ACTC_none ||
3203 ACTC == ACTC_voidPtr ||
3204 ACTC == ACTC_coreFoundation;
3205}
3206
John McCall31168b02011-06-15 23:02:42 +00003207static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCalle4fe2452011-10-01 01:01:08 +00003208 bool isIndirect = false;
John McCall31168b02011-06-15 23:02:42 +00003209
3210 // Ignore an outermost reference type.
John McCalle4fe2452011-10-01 01:01:08 +00003211 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall31168b02011-06-15 23:02:42 +00003212 type = ref->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00003213 isIndirect = true;
3214 }
John McCall31168b02011-06-15 23:02:42 +00003215
3216 // Drill through pointers and arrays recursively.
3217 while (true) {
3218 if (const PointerType *ptr = type->getAs<PointerType>()) {
3219 type = ptr->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00003220
3221 // The first level of pointer may be the innermost pointer on a CF type.
3222 if (!isIndirect) {
3223 if (type->isVoidType()) return ACTC_voidPtr;
3224 if (type->isRecordType()) return ACTC_coreFoundation;
3225 }
John McCall31168b02011-06-15 23:02:42 +00003226 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
3227 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
3228 } else {
3229 break;
3230 }
John McCalle4fe2452011-10-01 01:01:08 +00003231 isIndirect = true;
John McCall31168b02011-06-15 23:02:42 +00003232 }
3233
John McCalle4fe2452011-10-01 01:01:08 +00003234 if (isIndirect) {
3235 if (type->isObjCARCBridgableType())
3236 return ACTC_indirectRetainable;
3237 return ACTC_none;
3238 }
3239
3240 if (type->isObjCARCBridgableType())
3241 return ACTC_retainable;
3242
3243 return ACTC_none;
John McCall31168b02011-06-15 23:02:42 +00003244}
3245
3246namespace {
John McCalle4fe2452011-10-01 01:01:08 +00003247 /// A result from the cast checker.
3248 enum ACCResult {
3249 /// Cannot be casted.
3250 ACC_invalid,
3251
3252 /// Can be safely retained or not retained.
3253 ACC_bottom,
3254
3255 /// Can be casted at +0.
3256 ACC_plusZero,
3257
3258 /// Can be casted at +1.
3259 ACC_plusOne
3260 };
3261 ACCResult merge(ACCResult left, ACCResult right) {
3262 if (left == right) return left;
3263 if (left == ACC_bottom) return right;
3264 if (right == ACC_bottom) return left;
3265 return ACC_invalid;
3266 }
3267
3268 /// A checker which white-lists certain expressions whose conversion
3269 /// to or from retainable type would otherwise be forbidden in ARC.
3270 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
3271 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
3272
John McCall31168b02011-06-15 23:02:42 +00003273 ASTContext &Context;
John McCalle4fe2452011-10-01 01:01:08 +00003274 ARCConversionTypeClass SourceClass;
3275 ARCConversionTypeClass TargetClass;
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003276 bool Diagnose;
John McCalle4fe2452011-10-01 01:01:08 +00003277
3278 static bool isCFType(QualType type) {
3279 // Someday this can use ns_bridged. For now, it has to do this.
3280 return type->isCARCBridgableType();
John McCall31168b02011-06-15 23:02:42 +00003281 }
John McCalle4fe2452011-10-01 01:01:08 +00003282
3283 public:
3284 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003285 ARCConversionTypeClass target, bool diagnose)
3286 : Context(Context), SourceClass(source), TargetClass(target),
3287 Diagnose(diagnose) {}
John McCalle4fe2452011-10-01 01:01:08 +00003288
3289 using super::Visit;
3290 ACCResult Visit(Expr *e) {
3291 return super::Visit(e->IgnoreParens());
3292 }
3293
3294 ACCResult VisitStmt(Stmt *s) {
3295 return ACC_invalid;
3296 }
3297
3298 /// Null pointer constants can be casted however you please.
3299 ACCResult VisitExpr(Expr *e) {
3300 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
3301 return ACC_bottom;
3302 return ACC_invalid;
3303 }
3304
3305 /// Objective-C string literals can be safely casted.
3306 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
3307 // If we're casting to any retainable type, go ahead. Global
3308 // strings are immune to retains, so this is bottom.
3309 if (isAnyRetainable(TargetClass)) return ACC_bottom;
3310
3311 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00003312 }
3313
John McCalle4fe2452011-10-01 01:01:08 +00003314 /// Look through certain implicit and explicit casts.
3315 ACCResult VisitCastExpr(CastExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00003316 switch (e->getCastKind()) {
3317 case CK_NullToPointer:
John McCalle4fe2452011-10-01 01:01:08 +00003318 return ACC_bottom;
3319
John McCall31168b02011-06-15 23:02:42 +00003320 case CK_NoOp:
3321 case CK_LValueToRValue:
3322 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00003323 case CK_CPointerToObjCPointerCast:
3324 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00003325 case CK_AnyPointerToBlockPointerCast:
3326 return Visit(e->getSubExpr());
John McCalle4fe2452011-10-01 01:01:08 +00003327
John McCall31168b02011-06-15 23:02:42 +00003328 default:
John McCalle4fe2452011-10-01 01:01:08 +00003329 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00003330 }
3331 }
John McCalle4fe2452011-10-01 01:01:08 +00003332
3333 /// Look through unary extension.
3334 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00003335 return Visit(e->getSubExpr());
3336 }
John McCalle4fe2452011-10-01 01:01:08 +00003337
3338 /// Ignore the LHS of a comma operator.
3339 ACCResult VisitBinComma(BinaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00003340 return Visit(e->getRHS());
3341 }
John McCalle4fe2452011-10-01 01:01:08 +00003342
3343 /// Conditional operators are okay if both sides are okay.
3344 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
3345 ACCResult left = Visit(e->getTrueExpr());
3346 if (left == ACC_invalid) return ACC_invalid;
3347 return merge(left, Visit(e->getFalseExpr()));
John McCall31168b02011-06-15 23:02:42 +00003348 }
John McCalle4fe2452011-10-01 01:01:08 +00003349
John McCallfe96e0b2011-11-06 09:01:30 +00003350 /// Look through pseudo-objects.
3351 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
3352 // If we're getting here, we should always have a result.
3353 return Visit(e->getResultExpr());
3354 }
3355
John McCalle4fe2452011-10-01 01:01:08 +00003356 /// Statement expressions are okay if their result expression is okay.
3357 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00003358 return Visit(e->getSubStmt()->body_back());
3359 }
John McCall31168b02011-06-15 23:02:42 +00003360
John McCalle4fe2452011-10-01 01:01:08 +00003361 /// Some declaration references are okay.
3362 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
John McCalle4fe2452011-10-01 01:01:08 +00003363 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
Ben Langmuir443aa4b2015-02-25 20:09:06 +00003364 // References to global constants are okay.
John McCalle4fe2452011-10-01 01:01:08 +00003365 if (isAnyRetainable(TargetClass) &&
3366 isAnyRetainable(SourceClass) &&
3367 var &&
Akira Hatanakaad515392017-04-11 22:01:33 +00003368 !var->hasDefinition(Context) &&
Ben Langmuir443aa4b2015-02-25 20:09:06 +00003369 var->getType().isConstQualified()) {
3370
3371 // In system headers, they can also be assumed to be immune to retains.
3372 // These are things like 'kCFStringTransformToLatin'.
3373 if (Context.getSourceManager().isInSystemHeader(var->getLocation()))
3374 return ACC_bottom;
3375
3376 return ACC_plusZero;
John McCalle4fe2452011-10-01 01:01:08 +00003377 }
3378
3379 // Nothing else.
3380 return ACC_invalid;
Fariborz Jahanian78876372011-06-21 17:38:29 +00003381 }
John McCalle4fe2452011-10-01 01:01:08 +00003382
3383 /// Some calls are okay.
3384 ACCResult VisitCallExpr(CallExpr *e) {
3385 if (FunctionDecl *fn = e->getDirectCallee())
3386 if (ACCResult result = checkCallToFunction(fn))
3387 return result;
3388
3389 return super::VisitCallExpr(e);
3390 }
3391
3392 ACCResult checkCallToFunction(FunctionDecl *fn) {
3393 // Require a CF*Ref return type.
Alp Toker314cc812014-01-25 16:55:45 +00003394 if (!isCFType(fn->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003395 return ACC_invalid;
3396
3397 if (!isAnyRetainable(TargetClass))
3398 return ACC_invalid;
3399
3400 // Honor an explicit 'not retained' attribute.
3401 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3402 return ACC_plusZero;
3403
3404 // Honor an explicit 'retained' attribute, except that for
3405 // now we're not going to permit implicit handling of +1 results,
3406 // because it's a bit frightening.
3407 if (fn->hasAttr<CFReturnsRetainedAttr>())
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003408 return Diagnose ? ACC_plusOne
3409 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003410
3411 // Recognize this specific builtin function, which is used by CFSTR.
3412 unsigned builtinID = fn->getBuiltinID();
3413 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3414 return ACC_bottom;
3415
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003416 // Otherwise, don't do anything implicit with an unaudited function.
3417 if (!fn->hasAttr<CFAuditedTransferAttr>())
3418 return ACC_invalid;
3419
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003420 // Otherwise, it's +0 unless it follows the create convention.
3421 if (ento::coreFoundation::followsCreateRule(fn))
3422 return Diagnose ? ACC_plusOne
3423 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003424
John McCalle4fe2452011-10-01 01:01:08 +00003425 return ACC_plusZero;
3426 }
3427
3428 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3429 return checkCallToMethod(e->getMethodDecl());
3430 }
3431
3432 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3433 ObjCMethodDecl *method;
3434 if (e->isExplicitProperty())
3435 method = e->getExplicitProperty()->getGetterMethodDecl();
3436 else
3437 method = e->getImplicitPropertyGetter();
3438 return checkCallToMethod(method);
3439 }
3440
3441 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3442 if (!method) return ACC_invalid;
3443
3444 // Check for message sends to functions returning CF types. We
3445 // just obey the Cocoa conventions with these, even though the
3446 // return type is CF.
Alp Toker314cc812014-01-25 16:55:45 +00003447 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003448 return ACC_invalid;
3449
3450 // If the method is explicitly marked not-retained, it's +0.
3451 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3452 return ACC_plusZero;
3453
3454 // If the method is explicitly marked as returning retained, or its
3455 // selector follows a +1 Cocoa convention, treat it as +1.
3456 if (method->hasAttr<CFReturnsRetainedAttr>())
3457 return ACC_plusOne;
3458
3459 switch (method->getSelector().getMethodFamily()) {
3460 case OMF_alloc:
3461 case OMF_copy:
3462 case OMF_mutableCopy:
3463 case OMF_new:
3464 return ACC_plusOne;
3465
3466 default:
3467 // Otherwise, treat it as +0.
3468 return ACC_plusZero;
Fariborz Jahanian9b83be82011-06-21 19:42:38 +00003469 }
3470 }
John McCalle4fe2452011-10-01 01:01:08 +00003471 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003472} // end anonymous namespace
Fariborz Jahanian4ad56862011-06-20 20:54:42 +00003473
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003474bool Sema::isKnownName(StringRef name) {
3475 if (name.empty())
3476 return false;
3477 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003478 Sema::LookupOrdinaryName);
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003479 return LookupName(R, TUScope, false);
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003480}
3481
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003482static void addFixitForObjCARCConversion(Sema &S,
3483 DiagnosticBuilder &DiagB,
3484 Sema::CheckedConversionKind CCK,
3485 SourceLocation afterLParen,
3486 QualType castType,
3487 Expr *castExpr,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003488 Expr *realCast,
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003489 const char *bridgeKeyword,
3490 const char *CFBridgeName) {
3491 // We handle C-style and implicit casts here.
3492 switch (CCK) {
3493 case Sema::CCK_ImplicitConversion:
3494 case Sema::CCK_CStyleCast:
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003495 case Sema::CCK_OtherCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003496 break;
3497 case Sema::CCK_FunctionalCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003498 return;
3499 }
3500
3501 if (CFBridgeName) {
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003502 if (CCK == Sema::CCK_OtherCast) {
3503 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3504 SourceRange range(NCE->getOperatorLoc(),
3505 NCE->getAngleBrackets().getEnd());
3506 SmallString<32> BridgeCall;
3507
3508 SourceManager &SM = S.getSourceManager();
3509 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3510 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3511 BridgeCall += ' ';
3512
3513 BridgeCall += CFBridgeName;
3514 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3515 }
3516 return;
3517 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003518 Expr *castedE = castExpr;
3519 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3520 castedE = CCE->getSubExpr();
3521 castedE = castedE->IgnoreImpCasts();
3522 SourceRange range = castedE->getSourceRange();
Jordan Rose288c4212012-06-07 01:10:31 +00003523
3524 SmallString<32> BridgeCall;
3525
3526 SourceManager &SM = S.getSourceManager();
3527 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3528 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3529 BridgeCall += ' ';
3530
3531 BridgeCall += CFBridgeName;
3532
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003533 if (isa<ParenExpr>(castedE)) {
3534 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003535 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003536 } else {
Jordan Rose288c4212012-06-07 01:10:31 +00003537 BridgeCall += '(';
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003538 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003539 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003540 DiagB.AddFixItHint(FixItHint::CreateInsertion(
Craig Topper07fa1762015-11-15 02:31:46 +00003541 S.getLocForEndOfToken(range.getEnd()),
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003542 ")"));
3543 }
3544 return;
3545 }
3546
3547 if (CCK == Sema::CCK_CStyleCast) {
3548 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003549 } else if (CCK == Sema::CCK_OtherCast) {
3550 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3551 std::string castCode = "(";
3552 castCode += bridgeKeyword;
3553 castCode += castType.getAsString();
3554 castCode += ")";
3555 SourceRange Range(NCE->getOperatorLoc(),
3556 NCE->getAngleBrackets().getEnd());
3557 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3558 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003559 } else {
3560 std::string castCode = "(";
3561 castCode += bridgeKeyword;
3562 castCode += castType.getAsString();
3563 castCode += ")";
3564 Expr *castedE = castExpr->IgnoreImpCasts();
3565 SourceRange range = castedE->getSourceRange();
3566 if (isa<ParenExpr>(castedE)) {
3567 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3568 castCode));
3569 } else {
3570 castCode += "(";
3571 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3572 castCode));
3573 DiagB.AddFixItHint(FixItHint::CreateInsertion(
Craig Topper07fa1762015-11-15 02:31:46 +00003574 S.getLocForEndOfToken(range.getEnd()),
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003575 ")"));
3576 }
3577 }
3578}
3579
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003580template <typename T>
3581static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3582 TypedefNameDecl *TDNDecl = TD->getDecl();
3583 QualType QT = TDNDecl->getUnderlyingType();
3584 if (QT->isPointerType()) {
3585 QT = QT->getPointeeType();
3586 if (const RecordType *RT = QT->getAs<RecordType>())
Fariborz Jahanian9af6a782014-06-11 19:10:46 +00003587 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
Aaron Ballman2084f8f2013-12-19 13:20:36 +00003588 return RD->getAttr<T>();
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003589 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003590 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003591}
3592
3593static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3594 TypedefNameDecl *&TDNDecl) {
3595 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3596 TDNDecl = TD->getDecl();
3597 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3598 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3599 return ObjCBAttr;
3600 T = TDNDecl->getUnderlyingType();
3601 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003602 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003603}
3604
John McCall4124c492011-10-17 18:40:02 +00003605static void
3606diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3607 QualType castType, ARCConversionTypeClass castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003608 Expr *castExpr, Expr *realCast,
3609 ARCConversionTypeClass exprACTC,
John McCall4124c492011-10-17 18:40:02 +00003610 Sema::CheckedConversionKind CCK) {
John McCall31168b02011-06-15 23:02:42 +00003611 SourceLocation loc =
John McCalle4fe2452011-10-01 01:01:08 +00003612 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCall31168b02011-06-15 23:02:42 +00003613
John McCall4124c492011-10-17 18:40:02 +00003614 if (S.makeUnavailableInSystemHeader(loc,
John McCallc6af8c62015-10-28 05:03:19 +00003615 UnavailableAttr::IR_ARCForbiddenConversion))
John McCall31168b02011-06-15 23:02:42 +00003616 return;
John McCall4124c492011-10-17 18:40:02 +00003617
3618 QualType castExprType = castExpr->getType();
Bob Wilsonf5c53b82016-02-13 01:41:41 +00003619 // Defer emitting a diagnostic for bridge-related casts; that will be
3620 // handled by CheckObjCBridgeRelatedConversions.
Craig Topperc3ec1492014-05-26 06:22:03 +00003621 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003622 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3623 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3624 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
Fariborz Jahanian1ad83a32014-06-18 23:22:38 +00003625 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003626 return;
John McCall31168b02011-06-15 23:02:42 +00003627
John McCall640767f2011-06-17 06:50:50 +00003628 unsigned srcKind = 0;
John McCall31168b02011-06-15 23:02:42 +00003629 switch (exprACTC) {
John McCalle4fe2452011-10-01 01:01:08 +00003630 case ACTC_none:
3631 case ACTC_coreFoundation:
3632 case ACTC_voidPtr:
3633 srcKind = (castExprType->isPointerType() ? 1 : 0);
3634 break;
3635 case ACTC_retainable:
3636 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3637 break;
3638 case ACTC_indirectRetainable:
3639 srcKind = 4;
3640 break;
John McCall31168b02011-06-15 23:02:42 +00003641 }
3642
John McCall4124c492011-10-17 18:40:02 +00003643 // Check whether this could be fixed with a bridge cast.
Craig Topper07fa1762015-11-15 02:31:46 +00003644 SourceLocation afterLParen = S.getLocForEndOfToken(castRange.getBegin());
John McCall4124c492011-10-17 18:40:02 +00003645 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCall31168b02011-06-15 23:02:42 +00003646
John McCall4124c492011-10-17 18:40:02 +00003647 // Bridge from an ARC type to a CF type.
3648 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003649
John McCall4124c492011-10-17 18:40:02 +00003650 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3651 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3652 << 2 // of C pointer type
3653 << castExprType
3654 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3655 << castType
3656 << castRange
3657 << castExpr->getSourceRange();
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003658 bool br = S.isKnownName("CFBridgingRelease");
Jordan Rose4502b532012-07-31 01:07:43 +00003659 ACCResult CreateRule =
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003660 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003661 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003662 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003663 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003664 DiagnosticBuilder DiagB =
3665 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3666 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Craig Topperc3ec1492014-05-26 06:22:03 +00003667
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003668 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003669 castType, castExpr, realCast, "__bridge ",
3670 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003671 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003672 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003673 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003674 DiagnosticBuilder DiagB =
3675 (CCK == Sema::CCK_OtherCast && !br) ?
3676 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3677 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3678 diag::note_arc_bridge_transfer)
3679 << castExprType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003680
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003681 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003682 castType, castExpr, realCast, "__bridge_transfer ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003683 br ? "CFBridgingRelease" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003684 }
John McCall4124c492011-10-17 18:40:02 +00003685
3686 return;
3687 }
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003688
John McCall4124c492011-10-17 18:40:02 +00003689 // Bridge from a CF type to an ARC type.
3690 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003691 bool br = S.isKnownName("CFBridgingRetain");
John McCall4124c492011-10-17 18:40:02 +00003692 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3693 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3694 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3695 << castExprType
3696 << 2 // to C pointer type
3697 << castType
3698 << castRange
3699 << castExpr->getSourceRange();
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003700 ACCResult CreateRule =
3701 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003702 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003703 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003704 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003705 DiagnosticBuilder DiagB =
3706 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3707 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003708 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003709 castType, castExpr, realCast, "__bridge ",
3710 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003711 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003712 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003713 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003714 DiagnosticBuilder DiagB =
3715 (CCK == Sema::CCK_OtherCast && !br) ?
3716 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3717 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3718 diag::note_arc_bridge_retained)
3719 << castType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003720
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003721 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003722 castType, castExpr, realCast, "__bridge_retained ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003723 br ? "CFBridgingRetain" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003724 }
John McCall4124c492011-10-17 18:40:02 +00003725
3726 return;
John McCall31168b02011-06-15 23:02:42 +00003727 }
3728
John McCall4124c492011-10-17 18:40:02 +00003729 S.Diag(loc, diag::err_arc_mismatched_cast)
3730 << (CCK != Sema::CCK_ImplicitConversion)
3731 << srcKind << castExprType << castType
John McCall31168b02011-06-15 23:02:42 +00003732 << castRange << castExpr->getSourceRange();
3733}
3734
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003735template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003736static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3737 bool &HadTheAttribute, bool warn) {
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003738 QualType T = castExpr->getType();
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003739 HadTheAttribute = false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003740 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3741 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003742 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003743 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003744 HadTheAttribute = true;
Fariborz Jahanianc9e266b2014-12-11 22:56:26 +00003745 if (Parm->isStr("id"))
3746 return true;
3747
Craig Topperc3ec1492014-05-26 06:22:03 +00003748 NamedDecl *Target = nullptr;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003749 // Check for an existing type with this name.
3750 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3751 Sema::LookupOrdinaryName);
3752 if (S.LookupName(R, S.TUScope)) {
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003753 Target = R.getFoundDecl();
3754 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3755 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3756 if (const ObjCObjectPointerType *InterfacePointerType =
3757 castType->getAsObjCInterfacePointerType()) {
3758 ObjCInterfaceDecl *CastClass
3759 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003760 if ((CastClass == ExprClass) ||
Fariborz Jahanian27aa9b42015-04-10 22:07:47 +00003761 (CastClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003762 return true;
3763 if (warn)
3764 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3765 << T << Target->getName() << castType->getPointeeType();
3766 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003767 } else if (castType->isObjCIdType() ||
3768 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3769 castType, ExprClass)))
3770 // ok to cast to 'id'.
3771 // casting to id<p-list> is ok if bridge type adopts all of
3772 // p-list protocols.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003773 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003774 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003775 if (warn) {
3776 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3777 << T << Target->getName() << castType;
3778 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3779 S.Diag(Target->getLocStart(), diag::note_declared_at);
3780 }
3781 return false;
Fariborz Jahanian2c312122013-11-16 23:22:37 +00003782 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003783 }
Fariborz Jahanian696c8872015-04-09 23:39:53 +00003784 } else if (!castType->isObjCIdType()) {
3785 S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface)
3786 << castExpr->getType() << Parm;
3787 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3788 if (Target)
3789 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003790 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003791 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003792 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003793 return false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003794 }
3795 T = TDNDecl->getUnderlyingType();
3796 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003797 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003798}
3799
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003800template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003801static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
3802 bool &HadTheAttribute, bool warn) {
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003803 QualType T = castType;
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003804 HadTheAttribute = false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003805 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3806 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003807 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003808 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003809 HadTheAttribute = true;
John McCallaf6b3f82015-03-10 18:41:23 +00003810 if (Parm->isStr("id"))
3811 return true;
3812
Craig Topperc3ec1492014-05-26 06:22:03 +00003813 NamedDecl *Target = nullptr;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003814 // Check for an existing type with this name.
3815 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3816 Sema::LookupOrdinaryName);
3817 if (S.LookupName(R, S.TUScope)) {
3818 Target = R.getFoundDecl();
3819 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3820 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3821 if (const ObjCObjectPointerType *InterfacePointerType =
3822 castExpr->getType()->getAsObjCInterfacePointerType()) {
3823 ObjCInterfaceDecl *ExprClass
3824 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003825 if ((CastClass == ExprClass) ||
3826 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003827 return true;
3828 if (warn) {
3829 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3830 << castExpr->getType()->getPointeeType() << T;
3831 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3832 }
3833 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003834 } else if (castExpr->getType()->isObjCIdType() ||
3835 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3836 castExpr->getType(), CastClass)))
3837 // ok to cast an 'id' expression to a CFtype.
3838 // ok to cast an 'id<plist>' expression to CFtype provided plist
3839 // adopts all of CFtype's ObjetiveC's class plist.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003840 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003841 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003842 if (warn) {
3843 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3844 << castExpr->getType() << castType;
3845 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3846 S.Diag(Target->getLocStart(), diag::note_declared_at);
3847 }
3848 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003849 }
3850 }
3851 }
3852 S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject)
3853 << castExpr->getType() << castType;
3854 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3855 if (Target)
3856 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003857 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003858 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003859 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003860 }
3861 T = TDNDecl->getUnderlyingType();
3862 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003863 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003864}
3865
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003866void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003867 if (!getLangOpts().ObjC1)
3868 return;
Alp Tokerf6a24ce2013-12-05 16:25:25 +00003869 // warn in presence of __bridge casting to or from a toll free bridge cast.
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003870 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3871 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003872 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003873 bool HasObjCBridgeAttr;
3874 bool ObjCBridgeAttrWillNotWarn =
3875 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3876 false);
3877 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3878 return;
3879 bool HasObjCBridgeMutableAttr;
3880 bool ObjCBridgeMutableAttrWillNotWarn =
3881 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3882 HasObjCBridgeMutableAttr, false);
3883 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3884 return;
3885
3886 if (HasObjCBridgeAttr)
3887 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3888 true);
3889 else if (HasObjCBridgeMutableAttr)
3890 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3891 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003892 }
3893 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003894 bool HasObjCBridgeAttr;
3895 bool ObjCBridgeAttrWillNotWarn =
3896 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3897 false);
3898 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3899 return;
3900 bool HasObjCBridgeMutableAttr;
3901 bool ObjCBridgeMutableAttrWillNotWarn =
3902 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3903 HasObjCBridgeMutableAttr, false);
3904 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3905 return;
3906
3907 if (HasObjCBridgeAttr)
3908 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3909 true);
3910 else if (HasObjCBridgeMutableAttr)
3911 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3912 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003913 }
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003914}
3915
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003916void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
3917 QualType SrcType = castExpr->getType();
3918 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
3919 if (PRE->isExplicitProperty()) {
3920 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
3921 SrcType = PDecl->getType();
3922 }
3923 else if (PRE->isImplicitProperty()) {
3924 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
3925 SrcType = Getter->getReturnType();
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003926 }
3927 }
3928
3929 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
3930 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
3931 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
3932 return;
3933 CheckObjCBridgeRelatedConversions(castExpr->getLocStart(),
3934 castType, SrcType, castExpr);
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003935}
3936
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00003937bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
3938 CastKind &Kind) {
3939 if (!getLangOpts().ObjC1)
3940 return false;
3941 ARCConversionTypeClass exprACTC =
3942 classifyTypeForARCConversion(castExpr->getType());
3943 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3944 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
3945 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
3946 CheckTollFreeBridgeCast(castType, castExpr);
3947 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
3948 : CK_CPointerToObjCPointerCast;
3949 return true;
3950 }
3951 return false;
3952}
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003953
3954bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
3955 QualType DestType, QualType SrcType,
3956 ObjCInterfaceDecl *&RelatedClass,
3957 ObjCMethodDecl *&ClassMethod,
3958 ObjCMethodDecl *&InstanceMethod,
3959 TypedefNameDecl *&TDNDecl,
George Burgess IV60bc9722016-01-13 23:36:34 +00003960 bool CfToNs, bool Diagnose) {
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003961 QualType T = CfToNs ? SrcType : DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003962 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
3963 if (!ObjCBAttr)
3964 return false;
3965
3966 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
3967 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
3968 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
3969 if (!RCId)
3970 return false;
Craig Topperc3ec1492014-05-26 06:22:03 +00003971 NamedDecl *Target = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003972 // Check for an existing type with this name.
3973 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
3974 Sema::LookupOrdinaryName);
3975 if (!LookupName(R, TUScope)) {
George Burgess IV60bc9722016-01-13 23:36:34 +00003976 if (Diagnose) {
3977 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
3978 << SrcType << DestType;
3979 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3980 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003981 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003982 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003983 Target = R.getFoundDecl();
3984 if (Target && isa<ObjCInterfaceDecl>(Target))
3985 RelatedClass = cast<ObjCInterfaceDecl>(Target);
3986 else {
George Burgess IV60bc9722016-01-13 23:36:34 +00003987 if (Diagnose) {
3988 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
3989 << SrcType << DestType;
3990 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3991 if (Target)
3992 Diag(Target->getLocStart(), diag::note_declared_at);
3993 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003994 return false;
3995 }
3996
3997 // Check for an existing class method with the given selector name.
3998 if (CfToNs && CMId) {
3999 Selector Sel = Context.Selectors.getUnarySelector(CMId);
4000 ClassMethod = RelatedClass->lookupMethod(Sel, false);
4001 if (!ClassMethod) {
George Burgess IV60bc9722016-01-13 23:36:34 +00004002 if (Diagnose) {
4003 Diag(Loc, diag::err_objc_bridged_related_known_method)
4004 << SrcType << DestType << Sel << false;
4005 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
4006 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00004007 return false;
4008 }
4009 }
4010
4011 // Check for an existing instance method with the given selector name.
4012 if (!CfToNs && IMId) {
4013 Selector Sel = Context.Selectors.getNullarySelector(IMId);
4014 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
4015 if (!InstanceMethod) {
George Burgess IV60bc9722016-01-13 23:36:34 +00004016 if (Diagnose) {
4017 Diag(Loc, diag::err_objc_bridged_related_known_method)
4018 << SrcType << DestType << Sel << true;
4019 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
4020 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00004021 return false;
4022 }
4023 }
4024 return true;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004025}
4026
4027bool
4028Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
Fariborz Jahaniandb765772013-12-10 17:08:13 +00004029 QualType DestType, QualType SrcType,
George Burgess IV60bc9722016-01-13 23:36:34 +00004030 Expr *&SrcExpr, bool Diagnose) {
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004031 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
4032 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
4033 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
4034 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
4035 if (!CfToNs && !NsToCf)
4036 return false;
4037
4038 ObjCInterfaceDecl *RelatedClass;
Craig Topperc3ec1492014-05-26 06:22:03 +00004039 ObjCMethodDecl *ClassMethod = nullptr;
4040 ObjCMethodDecl *InstanceMethod = nullptr;
4041 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004042 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
George Burgess IV60bc9722016-01-13 23:36:34 +00004043 ClassMethod, InstanceMethod, TDNDecl,
4044 CfToNs, Diagnose))
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004045 return false;
4046
4047 if (CfToNs) {
4048 // Implicit conversion from CF to ObjC object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00004049 if (ClassMethod) {
George Burgess IV60bc9722016-01-13 23:36:34 +00004050 if (Diagnose) {
4051 std::string ExpressionString = "[";
4052 ExpressionString += RelatedClass->getNameAsString();
4053 ExpressionString += " ";
4054 ExpressionString += ClassMethod->getSelector().getAsString();
4055 SourceLocation SrcExprEndLoc = getLocForEndOfToken(SrcExpr->getLocEnd());
4056 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
4057 Diag(Loc, diag::err_objc_bridged_related_known_method)
4058 << SrcType << DestType << ClassMethod->getSelector() << false
4059 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString)
4060 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
4061 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
4062 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00004063
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004064 QualType receiverType = Context.getObjCInterfaceType(RelatedClass);
4065 // Argument.
4066 Expr *args[] = { SrcExpr };
4067 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
Fariborz Jahanian381edf52013-12-16 22:54:37 +00004068 ClassMethod->getLocation(),
4069 ClassMethod->getSelector(), ClassMethod,
4070 MultiExprArg(args, 1));
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004071 SrcExpr = msg.get();
4072 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00004073 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00004074 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004075 }
4076 else {
4077 // Implicit conversion from ObjC type to CF object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00004078 if (InstanceMethod) {
George Burgess IV60bc9722016-01-13 23:36:34 +00004079 if (Diagnose) {
4080 std::string ExpressionString;
4081 SourceLocation SrcExprEndLoc =
4082 getLocForEndOfToken(SrcExpr->getLocEnd());
4083 if (InstanceMethod->isPropertyAccessor())
4084 if (const ObjCPropertyDecl *PDecl =
4085 InstanceMethod->findPropertyDecl()) {
4086 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
4087 ExpressionString = ".";
4088 ExpressionString += PDecl->getNameAsString();
4089 Diag(Loc, diag::err_objc_bridged_related_known_method)
4090 << SrcType << DestType << InstanceMethod->getSelector() << true
4091 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
4092 }
4093 if (ExpressionString.empty()) {
4094 // Provide a fixit: [ObjectExpr InstanceMethod]
4095 ExpressionString = " ";
4096 ExpressionString += InstanceMethod->getSelector().getAsString();
4097 ExpressionString += "]";
4098
Fariborz Jahanian88b68982013-12-10 23:18:06 +00004099 Diag(Loc, diag::err_objc_bridged_related_known_method)
George Burgess IV60bc9722016-01-13 23:36:34 +00004100 << SrcType << DestType << InstanceMethod->getSelector() << true
4101 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[")
4102 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
Fariborz Jahanian88b68982013-12-10 23:18:06 +00004103 }
George Burgess IV60bc9722016-01-13 23:36:34 +00004104 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
4105 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00004106
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004107 ExprResult msg =
4108 BuildInstanceMessageImplicit(SrcExpr, SrcType,
4109 InstanceMethod->getLocation(),
4110 InstanceMethod->getSelector(),
4111 InstanceMethod, None);
4112 SrcExpr = msg.get();
4113 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00004114 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00004115 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004116 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00004117 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004118}
4119
John McCall4124c492011-10-17 18:40:02 +00004120Sema::ARCConversionResult
Brian Kelley11352a82017-03-29 18:09:02 +00004121Sema::CheckObjCConversion(SourceRange castRange, QualType castType,
4122 Expr *&castExpr, CheckedConversionKind CCK,
4123 bool Diagnose, bool DiagnoseCFAudited,
4124 BinaryOperatorKind Opc) {
John McCall4124c492011-10-17 18:40:02 +00004125 QualType castExprType = castExpr->getType();
4126
4127 // For the purposes of the classification, we assume reference types
4128 // will bind to temporaries.
4129 QualType effCastType = castType;
4130 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
4131 effCastType = ref->getPointeeType();
4132
4133 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
4134 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00004135 if (exprACTC == castACTC) {
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004136 // Check for viability and report error if casting an rvalue to a
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00004137 // life-time qualifier.
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004138 if (castACTC == ACTC_retainable &&
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00004139 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
George Burgess IV60bc9722016-01-13 23:36:34 +00004140 castType != castExprType) {
Fariborz Jahanian244b1872011-10-29 00:06:10 +00004141 const Type *DT = castType.getTypePtr();
4142 QualType QDT = castType;
4143 // We desugar some types but not others. We ignore those
4144 // that cannot happen in a cast; i.e. auto, and those which
4145 // should not be de-sugared; i.e typedef.
4146 if (const ParenType *PT = dyn_cast<ParenType>(DT))
4147 QDT = PT->desugar();
4148 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
4149 QDT = TP->desugar();
4150 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
4151 QDT = AT->desugar();
4152 if (QDT != castType &&
4153 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004154 if (Diagnose) {
4155 SourceLocation loc = (castRange.isValid() ? castRange.getBegin()
4156 : castExpr->getExprLoc());
4157 Diag(loc, diag::err_arc_nolifetime_behavior);
4158 }
4159 return ACR_error;
Fariborz Jahanian244b1872011-10-29 00:06:10 +00004160 }
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00004161 }
4162 return ACR_okay;
4163 }
Brian Kelley11352a82017-03-29 18:09:02 +00004164
4165 // The life-time qualifier cast check above is all we need for ObjCWeak.
4166 // ObjCAutoRefCount has more restrictions on what is legal.
4167 if (!getLangOpts().ObjCAutoRefCount)
4168 return ACR_okay;
4169
John McCall4124c492011-10-17 18:40:02 +00004170 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
4171
4172 // Allow all of these types to be cast to integer types (but not
4173 // vice-versa).
4174 if (castACTC == ACTC_none && castType->isIntegralType(Context))
4175 return ACR_okay;
4176
4177 // Allow casts between pointers to lifetime types (e.g., __strong id*)
4178 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
4179 // must be explicit.
4180 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
4181 return ACR_okay;
4182 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
4183 CCK != CCK_ImplicitConversion)
4184 return ACR_okay;
4185
Fariborz Jahanian36986c62012-07-27 22:37:07 +00004186 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
John McCall4124c492011-10-17 18:40:02 +00004187 // For invalid casts, fall through.
4188 case ACC_invalid:
4189 break;
4190
4191 // Do nothing for both bottom and +0.
4192 case ACC_bottom:
4193 case ACC_plusZero:
4194 return ACR_okay;
4195
4196 // If the result is +1, consume it here.
4197 case ACC_plusOne:
4198 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
4199 CK_ARCConsumeObject, castExpr,
Craig Topperc3ec1492014-05-26 06:22:03 +00004200 nullptr, VK_RValue);
Tim Shen4a05bb82016-06-21 20:29:17 +00004201 Cleanup.setExprNeedsCleanups(true);
John McCall4124c492011-10-17 18:40:02 +00004202 return ACR_okay;
4203 }
4204
4205 // If this is a non-implicit cast from id or block type to a
4206 // CoreFoundation type, delay complaining in case the cast is used
4207 // in an acceptable context.
4208 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
4209 CCK != CCK_ImplicitConversion)
4210 return ACR_unbridged;
4211
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004212 // Issue a diagnostic about a missing @-sign when implicit casting a cstring
4213 // to 'NSString *', instead of falling through to report a "bridge cast"
4214 // diagnostic.
Fariborz Jahanian283bf892013-12-18 21:04:43 +00004215 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
George Burgess IV60bc9722016-01-13 23:36:34 +00004216 ConversionToObjCStringLiteralCheck(castType, castExpr, Diagnose))
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004217 return ACR_error;
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00004218
Fariborz Jahanian25eef192013-07-31 21:40:51 +00004219 // Do not issue "bridge cast" diagnostic when implicit casting
4220 // a retainable object to a CF type parameter belonging to an audited
4221 // CF API function. Let caller issue a normal type mismatched diagnostic
4222 // instead.
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004223 if ((!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
4224 castACTC != ACTC_coreFoundation) &&
4225 !(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
4226 (Opc == BO_NE || Opc == BO_EQ))) {
4227 if (Diagnose)
George Burgess IV60bc9722016-01-13 23:36:34 +00004228 diagnoseObjCARCConversion(*this, castRange, castType, castACTC, castExpr,
4229 castExpr, exprACTC, CCK);
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004230 return ACR_error;
4231 }
John McCall4124c492011-10-17 18:40:02 +00004232 return ACR_okay;
4233}
4234
4235/// Given that we saw an expression with the ARCUnbridgedCastTy
4236/// placeholder type, complain bitterly.
4237void Sema::diagnoseARCUnbridgedCast(Expr *e) {
4238 // We expect the spurious ImplicitCastExpr to already have been stripped.
4239 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4240 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
4241
4242 SourceRange castRange;
4243 QualType castType;
4244 CheckedConversionKind CCK;
4245
4246 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
4247 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
4248 castType = cast->getTypeAsWritten();
4249 CCK = CCK_CStyleCast;
4250 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
4251 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
4252 castType = cast->getTypeAsWritten();
4253 CCK = CCK_OtherCast;
4254 } else {
Akira Hatanaka2cd7e862017-05-09 01:54:51 +00004255 llvm_unreachable("Unexpected ImplicitCastExpr");
John McCall4124c492011-10-17 18:40:02 +00004256 }
4257
4258 ARCConversionTypeClass castACTC =
4259 classifyTypeForARCConversion(castType.getNonReferenceType());
4260
4261 Expr *castExpr = realCast->getSubExpr();
4262 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
4263
4264 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00004265 castExpr, realCast, ACTC_retainable, CCK);
John McCall4124c492011-10-17 18:40:02 +00004266}
4267
4268/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
4269/// type, remove the placeholder cast.
4270Expr *Sema::stripARCUnbridgedCast(Expr *e) {
4271 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4272
4273 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
4274 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
4275 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
4276 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
4277 assert(uo->getOpcode() == UO_Extension);
4278 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
Aaron Ballmana5038552018-01-09 13:07:03 +00004279 return new (Context)
4280 UnaryOperator(sub, UO_Extension, sub->getType(), sub->getValueKind(),
4281 sub->getObjectKind(), uo->getOperatorLoc(), false);
John McCall4124c492011-10-17 18:40:02 +00004282 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
4283 assert(!gse->isResultDependent());
4284
4285 unsigned n = gse->getNumAssocs();
4286 SmallVector<Expr*, 4> subExprs(n);
4287 SmallVector<TypeSourceInfo*, 4> subTypes(n);
4288 for (unsigned i = 0; i != n; ++i) {
4289 subTypes[i] = gse->getAssocTypeSourceInfo(i);
4290 Expr *sub = gse->getAssocExpr(i);
4291 if (i == gse->getResultIndex())
4292 sub = stripARCUnbridgedCast(sub);
4293 subExprs[i] = sub;
4294 }
4295
4296 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
4297 gse->getControllingExpr(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00004298 subTypes, subExprs,
4299 gse->getDefaultLoc(),
John McCall4124c492011-10-17 18:40:02 +00004300 gse->getRParenLoc(),
4301 gse->containsUnexpandedParameterPack(),
4302 gse->getResultIndex());
4303 } else {
4304 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
4305 return cast<ImplicitCastExpr>(e)->getSubExpr();
4306 }
4307}
4308
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004309bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
4310 QualType exprType) {
4311 QualType canCastType =
4312 Context.getCanonicalType(castType).getUnqualifiedType();
4313 QualType canExprType =
4314 Context.getCanonicalType(exprType).getUnqualifiedType();
4315 if (isa<ObjCObjectPointerType>(canCastType) &&
4316 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
4317 canExprType->isObjCObjectPointerType()) {
4318 if (const ObjCObjectPointerType *ObjT =
4319 canExprType->getAs<ObjCObjectPointerType>())
Richard Smith802c4b72012-08-23 06:16:52 +00004320 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
4321 return !ObjI->isArcWeakrefUnavailable();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004322 }
4323 return true;
4324}
4325
John McCall4db5c3c2011-07-07 06:58:02 +00004326/// Look for an ObjCReclaimReturnedObject cast and destroy it.
4327static Expr *maybeUndoReclaimObject(Expr *e) {
Akira Hatanakacc7171a2017-10-10 01:24:33 +00004328 Expr *curExpr = e, *prevExpr = nullptr;
4329
4330 // Walk down the expression until we hit an implicit cast of kind
4331 // ARCReclaimReturnedObject or an Expr that is neither a Paren nor a Cast.
4332 while (true) {
4333 if (auto *pe = dyn_cast<ParenExpr>(curExpr)) {
4334 prevExpr = curExpr;
4335 curExpr = pe->getSubExpr();
4336 continue;
4337 }
4338
4339 if (auto *ce = dyn_cast<CastExpr>(curExpr)) {
4340 if (auto *ice = dyn_cast<ImplicitCastExpr>(ce))
4341 if (ice->getCastKind() == CK_ARCReclaimReturnedObject) {
4342 if (!prevExpr)
4343 return ice->getSubExpr();
4344 if (auto *pe = dyn_cast<ParenExpr>(prevExpr))
4345 pe->setSubExpr(ice->getSubExpr());
4346 else
4347 cast<CastExpr>(prevExpr)->setSubExpr(ice->getSubExpr());
4348 return e;
4349 }
4350
4351 prevExpr = curExpr;
4352 curExpr = ce->getSubExpr();
4353 continue;
4354 }
4355
4356 // Break out of the loop if curExpr is neither a Paren nor a Cast.
4357 break;
4358 }
John McCall4db5c3c2011-07-07 06:58:02 +00004359
4360 return e;
4361}
4362
John McCall31168b02011-06-15 23:02:42 +00004363ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
4364 ObjCBridgeCastKind Kind,
4365 SourceLocation BridgeKeywordLoc,
4366 TypeSourceInfo *TSInfo,
4367 Expr *SubExpr) {
John McCalleb075542011-08-26 00:48:42 +00004368 ExprResult SubResult = UsualUnaryConversions(SubExpr);
4369 if (SubResult.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004370 SubExpr = SubResult.get();
John McCalleb075542011-08-26 00:48:42 +00004371
John McCall31168b02011-06-15 23:02:42 +00004372 QualType T = TSInfo->getType();
4373 QualType FromType = SubExpr->getType();
4374
John McCall9320b872011-09-09 05:25:32 +00004375 CastKind CK;
4376
John McCall31168b02011-06-15 23:02:42 +00004377 bool MustConsume = false;
4378 if (T->isDependentType() || SubExpr->isTypeDependent()) {
4379 // Okay: we'll build a dependent expression type.
John McCall9320b872011-09-09 05:25:32 +00004380 CK = CK_Dependent;
John McCall31168b02011-06-15 23:02:42 +00004381 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
4382 // Casting CF -> id
John McCall9320b872011-09-09 05:25:32 +00004383 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
4384 : CK_CPointerToObjCPointerCast);
John McCall31168b02011-06-15 23:02:42 +00004385 switch (Kind) {
4386 case OBC_Bridge:
4387 break;
4388
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004389 case OBC_BridgeRetained: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00004390 bool br = isKnownName("CFBridgingRelease");
John McCall31168b02011-06-15 23:02:42 +00004391 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4392 << 2
4393 << FromType
4394 << (T->isBlockPointerType()? 1 : 0)
4395 << T
4396 << SubExpr->getSourceRange()
4397 << Kind;
4398 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4399 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
4400 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004401 << FromType << br
John McCall31168b02011-06-15 23:02:42 +00004402 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004403 br ? "CFBridgingRelease "
4404 : "__bridge_transfer ");
John McCall31168b02011-06-15 23:02:42 +00004405
4406 Kind = OBC_Bridge;
4407 break;
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004408 }
John McCall31168b02011-06-15 23:02:42 +00004409
4410 case OBC_BridgeTransfer:
4411 // We must consume the Objective-C object produced by the cast.
4412 MustConsume = true;
4413 break;
4414 }
4415 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
4416 // Okay: id -> CF
John McCall9320b872011-09-09 05:25:32 +00004417 CK = CK_BitCast;
John McCall31168b02011-06-15 23:02:42 +00004418 switch (Kind) {
Fariborz Jahanian214567c2014-10-28 17:26:21 +00004419 case OBC_Bridge:
4420 // Reclaiming a value that's going to be __bridge-casted to CF
4421 // is very dangerous, so we don't do it.
4422 SubExpr = maybeUndoReclaimObject(SubExpr);
4423 break;
John McCall31168b02011-06-15 23:02:42 +00004424
4425 case OBC_BridgeRetained:
4426 // Produce the object before casting it.
4427 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall2d637d22011-09-10 06:18:15 +00004428 CK_ARCProduceObject,
Craig Topperc3ec1492014-05-26 06:22:03 +00004429 SubExpr, nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004430 break;
4431
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004432 case OBC_BridgeTransfer: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00004433 bool br = isKnownName("CFBridgingRetain");
John McCall31168b02011-06-15 23:02:42 +00004434 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4435 << (FromType->isBlockPointerType()? 1 : 0)
4436 << FromType
4437 << 2
4438 << T
4439 << SubExpr->getSourceRange()
4440 << Kind;
4441
4442 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4443 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
4444 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004445 << T << br
4446 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4447 br ? "CFBridgingRetain " : "__bridge_retained");
John McCall31168b02011-06-15 23:02:42 +00004448
4449 Kind = OBC_Bridge;
4450 break;
4451 }
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004452 }
John McCall31168b02011-06-15 23:02:42 +00004453 } else {
4454 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
4455 << FromType << T << Kind
4456 << SubExpr->getSourceRange()
4457 << TSInfo->getTypeLoc().getSourceRange();
4458 return ExprError();
4459 }
4460
John McCall9320b872011-09-09 05:25:32 +00004461 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCall31168b02011-06-15 23:02:42 +00004462 BridgeKeywordLoc,
4463 TSInfo, SubExpr);
4464
4465 if (MustConsume) {
Tim Shen4a05bb82016-06-21 20:29:17 +00004466 Cleanup.setExprNeedsCleanups(true);
John McCall2d637d22011-09-10 06:18:15 +00004467 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
Craig Topperc3ec1492014-05-26 06:22:03 +00004468 nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004469 }
4470
4471 return Result;
4472}
4473
4474ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
4475 SourceLocation LParenLoc,
4476 ObjCBridgeCastKind Kind,
4477 SourceLocation BridgeKeywordLoc,
4478 ParsedType Type,
4479 SourceLocation RParenLoc,
4480 Expr *SubExpr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004481 TypeSourceInfo *TSInfo = nullptr;
John McCall31168b02011-06-15 23:02:42 +00004482 QualType T = GetTypeFromParser(Type, &TSInfo);
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00004483 if (Kind == OBC_Bridge)
4484 CheckTollFreeBridgeCast(T, SubExpr);
John McCall31168b02011-06-15 23:02:42 +00004485 if (!TSInfo)
4486 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
4487 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
4488 SubExpr);
4489}