blob: 9947fad70dd3cbc1bd71b33c10ebc9c7034a0845 [file] [log] [blame]
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001//===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for Objective-C expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Chris Lattnera3fc41d2008-01-04 22:32:30 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclObjC.h"
Steve Naroff021ca182008-05-29 21:12:08 +000017#include "clang/AST/ExprObjC.h"
John McCall31168b02011-06-15 23:02:42 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor0c78ad92010-04-21 19:57:20 +000019#include "clang/AST/TypeLoc.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
21#include "clang/Edit/Commit.h"
22#include "clang/Edit/Rewriters.h"
Steve Naroff9527bbf2009-03-09 21:12:44 +000023#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Sema/Initialization.h"
25#include "clang/Sema/Lookup.h"
26#include "clang/Sema/Scope.h"
27#include "clang/Sema/ScopeInfo.h"
28#include "llvm/ADT/SmallString.h"
Steve Naroff9527bbf2009-03-09 21:12:44 +000029
Chris Lattnera3fc41d2008-01-04 22:32:30 +000030using namespace clang;
John McCall5f2d5562011-02-03 09:00:02 +000031using namespace sema;
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +000032using llvm::makeArrayRef;
Chris Lattnera3fc41d2008-01-04 22:32:30 +000033
John McCallfaf5fb42010-08-26 23:41:50 +000034ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
35 Expr **strings,
36 unsigned NumStrings) {
Chris Lattner163ffd22009-02-18 06:48:40 +000037 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
38
Chris Lattnerd7670d92009-02-18 06:13:04 +000039 // Most ObjC strings are formed out of a single piece. However, we *can*
40 // have strings formed out of multiple @ strings with multiple pptokens in
41 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
42 // StringLiteral for ObjCStringLiteral to hold onto.
Chris Lattner163ffd22009-02-18 06:48:40 +000043 StringLiteral *S = Strings[0];
Mike Stump11289f42009-09-09 15:08:12 +000044
Chris Lattnerd7670d92009-02-18 06:13:04 +000045 // If we have a multi-part string, merge it all together.
46 if (NumStrings != 1) {
Chris Lattnera3fc41d2008-01-04 22:32:30 +000047 // Concatenate objc strings.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000048 SmallString<128> StrBuf;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000049 SmallVector<SourceLocation, 8> StrLocs;
Mike Stump11289f42009-09-09 15:08:12 +000050
Chris Lattner630970d2009-02-18 05:49:11 +000051 for (unsigned i = 0; i != NumStrings; ++i) {
Chris Lattner163ffd22009-02-18 06:48:40 +000052 S = Strings[i];
Mike Stump11289f42009-09-09 15:08:12 +000053
Douglas Gregorfb65e592011-07-27 05:40:30 +000054 // ObjC strings can't be wide or UTF.
55 if (!S->isAscii()) {
Chris Lattnerd7670d92009-02-18 06:13:04 +000056 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
57 << S->getSourceRange();
58 return true;
59 }
Mike Stump11289f42009-09-09 15:08:12 +000060
Benjamin Kramer35b077e2010-08-17 12:54:38 +000061 // Append the string.
62 StrBuf += S->getString();
Mike Stump11289f42009-09-09 15:08:12 +000063
Chris Lattner163ffd22009-02-18 06:48:40 +000064 // Get the locations of the string tokens.
65 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Chris Lattnera3fc41d2008-01-04 22:32:30 +000066 }
Mike Stump11289f42009-09-09 15:08:12 +000067
Chris Lattner163ffd22009-02-18 06:48:40 +000068 // Create the aggregate string with the appropriate content and location
69 // information.
Benjamin Kramercdac7612014-02-25 12:26:20 +000070 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
71 assert(CAT && "String literal not of constant array type!");
72 QualType StrTy = Context.getConstantArrayType(
73 CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1),
74 CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers());
75 S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii,
76 /*Pascal=*/false, StrTy, &StrLocs[0],
77 StrLocs.size());
Chris Lattnera3fc41d2008-01-04 22:32:30 +000078 }
Ted Kremeneke65b0862012-03-06 20:05:56 +000079
80 return BuildObjCStringLiteral(AtLocs[0], S);
81}
Mike Stump11289f42009-09-09 15:08:12 +000082
Ted Kremeneke65b0862012-03-06 20:05:56 +000083ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
Chris Lattner6436fb62009-02-18 06:01:06 +000084 // Verify that this composite string is acceptable for ObjC strings.
85 if (CheckObjCString(S))
Chris Lattnera3fc41d2008-01-04 22:32:30 +000086 return true;
Chris Lattnerfffd6a72009-02-18 06:06:56 +000087
88 // Initialize the constant string interface lazily. This assumes
Steve Naroff54e59452009-04-07 14:18:33 +000089 // the NSString interface is seen in this translation unit. Note: We
90 // don't use NSConstantString, since the runtime team considers this
91 // interface private (even though it appears in the header files).
Chris Lattnerfffd6a72009-02-18 06:06:56 +000092 QualType Ty = Context.getObjCConstantStringInterface();
93 if (!Ty.isNull()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +000094 Ty = Context.getObjCObjectPointerType(Ty);
David Blaikiebbafb8a2012-03-11 07:00:24 +000095 } else if (getLangOpts().NoConstantCFStrings) {
Craig Topperc3ec1492014-05-26 06:22:03 +000096 IdentifierInfo *NSIdent=nullptr;
David Blaikiebbafb8a2012-03-11 07:00:24 +000097 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Fariborz Jahanian50c925f2010-10-19 17:19:29 +000098
99 if (StringClass.empty())
100 NSIdent = &Context.Idents.get("NSConstantString");
101 else
102 NSIdent = &Context.Idents.get(StringClass);
103
Ted Kremeneke65b0862012-03-06 20:05:56 +0000104 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Fariborz Jahanian07317632010-04-23 23:19:04 +0000105 LookupOrdinaryName);
106 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
107 Context.setObjCConstantStringInterface(StrIF);
108 Ty = Context.getObjCConstantStringInterface();
109 Ty = Context.getObjCObjectPointerType(Ty);
110 } else {
111 // If there is no NSConstantString interface defined then treat this
112 // as error and recover from it.
113 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
114 << S->getSourceRange();
115 Ty = Context.getObjCIdType();
116 }
Chris Lattner091f6982008-06-21 21:44:18 +0000117 } else {
Patrick Beard0caa3942012-04-19 00:25:12 +0000118 IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000119 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000120 LookupOrdinaryName);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000121 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
122 Context.setObjCConstantStringInterface(StrIF);
123 Ty = Context.getObjCConstantStringInterface();
Steve Naroff7cae42b2009-07-10 23:34:53 +0000124 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000125 } else {
Fariborz Jahanian86f82662012-02-23 22:51:36 +0000126 // If there is no NSString interface defined, implicitly declare
127 // a @class NSString; and use that instead. This is to make sure
128 // type of an NSString literal is represented correctly, instead of
129 // being an 'id' type.
130 Ty = Context.getObjCNSStringType();
131 if (Ty.isNull()) {
132 ObjCInterfaceDecl *NSStringIDecl =
133 ObjCInterfaceDecl::Create (Context,
134 Context.getTranslationUnitDecl(),
135 SourceLocation(), NSIdent,
Craig Topperc3ec1492014-05-26 06:22:03 +0000136 nullptr, SourceLocation());
Fariborz Jahanian86f82662012-02-23 22:51:36 +0000137 Ty = Context.getObjCInterfaceType(NSStringIDecl);
138 Context.setObjCNSStringType(Ty);
139 }
140 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000141 }
Chris Lattner091f6982008-06-21 21:44:18 +0000142 }
Mike Stump11289f42009-09-09 15:08:12 +0000143
Ted Kremeneke65b0862012-03-06 20:05:56 +0000144 return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
145}
146
Jordy Rose08e500c2012-05-12 17:32:44 +0000147/// \brief Emits an error if the given method does not exist, or if the return
148/// type is not an Objective-C object.
149static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
150 const ObjCInterfaceDecl *Class,
151 Selector Sel, const ObjCMethodDecl *Method) {
152 if (!Method) {
153 // FIXME: Is there a better way to avoid quotes than using getName()?
154 S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
155 return false;
156 }
157
158 // Make sure the return type is reasonable.
Alp Toker314cc812014-01-25 16:55:45 +0000159 QualType ReturnType = Method->getReturnType();
Jordy Rose08e500c2012-05-12 17:32:44 +0000160 if (!ReturnType->isObjCObjectPointerType()) {
161 S.Diag(Loc, diag::err_objc_literal_method_sig)
162 << Sel;
163 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
164 << ReturnType;
165 return false;
166 }
167
168 return true;
169}
170
Ted Kremeneke65b0862012-03-06 20:05:56 +0000171/// \brief Retrieve the NSNumber factory method that should be used to create
172/// an Objective-C literal for the given type.
173static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
Patrick Beard0caa3942012-04-19 00:25:12 +0000174 QualType NumberType,
175 bool isLiteral = false,
176 SourceRange R = SourceRange()) {
David Blaikie05785d12013-02-20 22:23:23 +0000177 Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
178 S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
179
Ted Kremeneke65b0862012-03-06 20:05:56 +0000180 if (!Kind) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000181 if (isLiteral) {
182 S.Diag(Loc, diag::err_invalid_nsnumber_type)
183 << NumberType << R;
184 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000185 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000186 }
Patrick Beard0caa3942012-04-19 00:25:12 +0000187
Ted Kremeneke65b0862012-03-06 20:05:56 +0000188 // If we already looked up this method, we're done.
189 if (S.NSNumberLiteralMethods[*Kind])
190 return S.NSNumberLiteralMethods[*Kind];
191
192 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
193 /*Instance=*/false);
194
Patrick Beard0caa3942012-04-19 00:25:12 +0000195 ASTContext &CX = S.Context;
196
197 // Look up the NSNumber class, if we haven't done so already. It's cached
198 // in the Sema instance.
199 if (!S.NSNumberDecl) {
Jordy Roseaca01f92012-05-12 17:32:52 +0000200 IdentifierInfo *NSNumberId =
201 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber);
Patrick Beard0caa3942012-04-19 00:25:12 +0000202 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSNumberId,
203 Loc, Sema::LookupOrdinaryName);
204 S.NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
205 if (!S.NSNumberDecl) {
206 if (S.getLangOpts().DebuggerObjCLiteral) {
207 // Create a stub definition of NSNumber.
Jordy Roseaca01f92012-05-12 17:32:52 +0000208 S.NSNumberDecl = ObjCInterfaceDecl::Create(CX,
209 CX.getTranslationUnitDecl(),
210 SourceLocation(), NSNumberId,
Craig Topperc3ec1492014-05-26 06:22:03 +0000211 nullptr, SourceLocation());
Patrick Beard0caa3942012-04-19 00:25:12 +0000212 } else {
213 // Otherwise, require a declaration of NSNumber.
214 S.Diag(Loc, diag::err_undeclared_nsnumber);
Craig Topperc3ec1492014-05-26 06:22:03 +0000215 return nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000216 }
217 } else if (!S.NSNumberDecl->hasDefinition()) {
218 S.Diag(Loc, diag::err_undeclared_nsnumber);
Craig Topperc3ec1492014-05-26 06:22:03 +0000219 return nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000220 }
Alex Denisove36748a2015-02-16 16:17:05 +0000221 }
222
223 if (S.NSNumberPointer.isNull()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000224 // generate the pointer to NSNumber type.
Jordy Roseaca01f92012-05-12 17:32:52 +0000225 QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
226 S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000227 }
228
Ted Kremeneke65b0862012-03-06 20:05:56 +0000229 // Look for the appropriate method within NSNumber.
Jordy Roseaca01f92012-05-12 17:32:52 +0000230 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000231 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000232 // create a stub definition this NSNumber factory method.
Craig Topperc3ec1492014-05-26 06:22:03 +0000233 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000234 Method =
235 ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
236 S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
237 /*isInstance=*/false, /*isVariadic=*/false,
238 /*isPropertyAccessor=*/false,
239 /*isImplicitlyDeclared=*/true,
240 /*isDefined=*/false, ObjCMethodDecl::Required,
241 /*HasRelatedResultType=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000242 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
243 SourceLocation(), SourceLocation(),
Patrick Beard0caa3942012-04-19 00:25:12 +0000244 &CX.Idents.get("value"),
Craig Topperc3ec1492014-05-26 06:22:03 +0000245 NumberType, /*TInfo=*/nullptr,
246 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000247 Method->setMethodParams(S.Context, value, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000248 }
249
Jordy Rose08e500c2012-05-12 17:32:44 +0000250 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
Craig Topperc3ec1492014-05-26 06:22:03 +0000251 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000252
253 // Note: if the parameter type is out-of-line, we'll catch it later in the
254 // implicit conversion.
255
256 S.NSNumberLiteralMethods[*Kind] = Method;
257 return Method;
258}
259
Patrick Beard0caa3942012-04-19 00:25:12 +0000260/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
261/// numeric literal expression. Type of the expression will be "NSNumber *".
Ted Kremeneke65b0862012-03-06 20:05:56 +0000262ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000263 // Determine the type of the literal.
264 QualType NumberType = Number->getType();
265 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
266 // In C, character literals have type 'int'. That's not the type we want
267 // to use to determine the Objective-c literal kind.
268 switch (Char->getKind()) {
269 case CharacterLiteral::Ascii:
270 NumberType = Context.CharTy;
271 break;
272
273 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000274 NumberType = Context.getWideCharType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000275 break;
276
277 case CharacterLiteral::UTF16:
278 NumberType = Context.Char16Ty;
279 break;
280
281 case CharacterLiteral::UTF32:
282 NumberType = Context.Char32Ty;
283 break;
284 }
285 }
286
Ted Kremeneke65b0862012-03-06 20:05:56 +0000287 // Look for the appropriate method within NSNumber.
288 // Construct the literal.
Patrick Beard2565c592012-05-01 21:47:19 +0000289 SourceRange NR(Number->getSourceRange());
Patrick Beard0caa3942012-04-19 00:25:12 +0000290 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
Patrick Beard2565c592012-05-01 21:47:19 +0000291 true, NR);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000292 if (!Method)
293 return ExprError();
294
295 // Convert the number to the type that the parameter expects.
Alp Toker03376dc2014-07-07 09:02:20 +0000296 ParmVarDecl *ParamDecl = Method->parameters()[0];
Patrick Beard2565c592012-05-01 21:47:19 +0000297 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
298 ParamDecl);
299 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
300 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000301 Number);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000302 if (ConvertedNumber.isInvalid())
303 return ExprError();
304 Number = ConvertedNumber.get();
305
Patrick Beard2565c592012-05-01 21:47:19 +0000306 // Use the effective source range of the literal, including the leading '@'.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000307 return MaybeBindToTemporary(
Patrick Beard2565c592012-05-01 21:47:19 +0000308 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
309 SourceRange(AtLoc, NR.getEnd())));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000310}
311
312ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
313 SourceLocation ValueLoc,
314 bool Value) {
315 ExprResult Inner;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000316 if (getLangOpts().CPlusPlus) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000317 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
318 } else {
319 // C doesn't actually have a way to represent literal values of type
320 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
321 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
322 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
323 CK_IntegralToBoolean);
324 }
325
326 return BuildObjCNumericLiteral(AtLoc, Inner.get());
327}
328
329/// \brief Check that the given expression is a valid element of an Objective-C
330/// collection literal.
331static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000332 QualType T,
333 bool ArrayLiteral = false) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000334 // If the expression is type-dependent, there's nothing for us to do.
335 if (Element->isTypeDependent())
336 return Element;
337
338 ExprResult Result = S.CheckPlaceholderExpr(Element);
339 if (Result.isInvalid())
340 return ExprError();
341 Element = Result.get();
342
343 // In C++, check for an implicit conversion to an Objective-C object pointer
344 // type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000345 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000346 InitializedEntity Entity
Jordy Roseaca01f92012-05-12 17:32:52 +0000347 = InitializedEntity::InitializeParameter(S.Context, T,
348 /*Consumed=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000349 InitializationKind Kind
Jordy Roseaca01f92012-05-12 17:32:52 +0000350 = InitializationKind::CreateCopy(Element->getLocStart(),
351 SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000352 InitializationSequence Seq(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000353 if (!Seq.Failed())
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000354 return Seq.Perform(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000355 }
356
357 Expr *OrigElement = Element;
358
359 // Perform lvalue-to-rvalue conversion.
360 Result = S.DefaultLvalueConversion(Element);
361 if (Result.isInvalid())
362 return ExprError();
363 Element = Result.get();
364
365 // Make sure that we have an Objective-C pointer type or block.
366 if (!Element->getType()->isObjCObjectPointerType() &&
367 !Element->getType()->isBlockPointerType()) {
368 bool Recovered = false;
369
370 // If this is potentially an Objective-C numeric literal, add the '@'.
371 if (isa<IntegerLiteral>(OrigElement) ||
372 isa<CharacterLiteral>(OrigElement) ||
373 isa<FloatingLiteral>(OrigElement) ||
374 isa<ObjCBoolLiteralExpr>(OrigElement) ||
375 isa<CXXBoolLiteralExpr>(OrigElement)) {
376 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
377 int Which = isa<CharacterLiteral>(OrigElement) ? 1
378 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
379 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
380 : 3;
381
382 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
383 << Which << OrigElement->getSourceRange()
384 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
385
386 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
387 OrigElement);
388 if (Result.isInvalid())
389 return ExprError();
390
391 Element = Result.get();
392 Recovered = true;
393 }
394 }
395 // If this is potentially an Objective-C string literal, add the '@'.
396 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
397 if (String->isAscii()) {
398 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
399 << 0 << OrigElement->getSourceRange()
400 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
401
402 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
403 if (Result.isInvalid())
404 return ExprError();
405
406 Element = Result.get();
407 Recovered = true;
408 }
409 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000410
Ted Kremeneke65b0862012-03-06 20:05:56 +0000411 if (!Recovered) {
412 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
413 << Element->getType();
414 return ExprError();
415 }
416 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000417 if (ArrayLiteral)
Ted Kremenek197fee42013-10-09 22:34:33 +0000418 if (ObjCStringLiteral *getString =
419 dyn_cast<ObjCStringLiteral>(OrigElement)) {
420 if (StringLiteral *SL = getString->getString()) {
421 unsigned numConcat = SL->getNumConcatenated();
422 if (numConcat > 1) {
423 // Only warn if the concatenated string doesn't come from a macro.
424 bool hasMacro = false;
425 for (unsigned i = 0; i < numConcat ; ++i)
426 if (SL->getStrTokenLoc(i).isMacroID()) {
427 hasMacro = true;
428 break;
429 }
430 if (!hasMacro)
431 S.Diag(Element->getLocStart(),
432 diag::warn_concatenated_nsarray_literal)
433 << Element->getType();
434 }
435 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000436 }
437
Ted Kremeneke65b0862012-03-06 20:05:56 +0000438 // Make sure that the element has the type that the container factory
439 // function expects.
440 return S.PerformCopyInitialization(
441 InitializedEntity::InitializeParameter(S.Context, T,
442 /*Consumed=*/false),
443 Element->getLocStart(), Element);
444}
445
Patrick Beard0caa3942012-04-19 00:25:12 +0000446ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
447 if (ValueExpr->isTypeDependent()) {
448 ObjCBoxedExpr *BoxedExpr =
Craig Topperc3ec1492014-05-26 06:22:03 +0000449 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000450 return BoxedExpr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000451 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000452 ObjCMethodDecl *BoxingMethod = nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000453 QualType BoxedType;
454 // Convert the expression to an RValue, so we can check for pointer types...
455 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
456 if (RValue.isInvalid()) {
457 return ExprError();
458 }
459 ValueExpr = RValue.get();
Patrick Beard2565c592012-05-01 21:47:19 +0000460 QualType ValueType(ValueExpr->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +0000461 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
462 QualType PointeeType = PT->getPointeeType();
463 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
464
465 if (!NSStringDecl) {
466 IdentifierInfo *NSStringId =
467 NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
468 NamedDecl *Decl = LookupSingleName(TUScope, NSStringId,
469 SR.getBegin(), LookupOrdinaryName);
470 NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl);
471 if (!NSStringDecl) {
472 if (getLangOpts().DebuggerObjCLiteral) {
473 // Support boxed expressions in the debugger w/o NSString declaration.
Jordy Roseaca01f92012-05-12 17:32:52 +0000474 DeclContext *TU = Context.getTranslationUnitDecl();
475 NSStringDecl = ObjCInterfaceDecl::Create(Context, TU,
476 SourceLocation(),
477 NSStringId,
Craig Topperc3ec1492014-05-26 06:22:03 +0000478 nullptr, SourceLocation());
Patrick Beard0caa3942012-04-19 00:25:12 +0000479 } else {
480 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
481 return ExprError();
482 }
483 } else if (!NSStringDecl->hasDefinition()) {
484 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
485 return ExprError();
486 }
487 assert(NSStringDecl && "NSStringDecl should not be NULL");
Jordy Roseaca01f92012-05-12 17:32:52 +0000488 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
489 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000490 }
491
492 if (!StringWithUTF8StringMethod) {
493 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
494 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
495
496 // Look for the appropriate method within NSString.
Jordy Rose08e500c2012-05-12 17:32:44 +0000497 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
498 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000499 // Debugger needs to work even if NSString hasn't been defined.
Craig Topperc3ec1492014-05-26 06:22:03 +0000500 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000501 ObjCMethodDecl *M = ObjCMethodDecl::Create(
502 Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
503 NSStringPointer, ReturnTInfo, NSStringDecl,
504 /*isInstance=*/false, /*isVariadic=*/false,
505 /*isPropertyAccessor=*/false,
506 /*isImplicitlyDeclared=*/true,
507 /*isDefined=*/false, ObjCMethodDecl::Required,
508 /*HasRelatedResultType=*/false);
Jordy Roseaca01f92012-05-12 17:32:52 +0000509 QualType ConstCharType = Context.CharTy.withConst();
Patrick Beard0caa3942012-04-19 00:25:12 +0000510 ParmVarDecl *value =
511 ParmVarDecl::Create(Context, M,
512 SourceLocation(), SourceLocation(),
513 &Context.Idents.get("value"),
Jordy Roseaca01f92012-05-12 17:32:52 +0000514 Context.getPointerType(ConstCharType),
Craig Topperc3ec1492014-05-26 06:22:03 +0000515 /*TInfo=*/nullptr,
516 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000517 M->setMethodParams(Context, value, None);
Jordy Rose08e500c2012-05-12 17:32:44 +0000518 BoxingMethod = M;
Patrick Beard0caa3942012-04-19 00:25:12 +0000519 }
Jordy Rose890f4572012-05-12 15:53:41 +0000520
Jordy Rose08e500c2012-05-12 17:32:44 +0000521 if (!validateBoxingMethod(*this, SR.getBegin(), NSStringDecl,
522 stringWithUTF8String, BoxingMethod))
523 return ExprError();
524
525 StringWithUTF8StringMethod = BoxingMethod;
Patrick Beard0caa3942012-04-19 00:25:12 +0000526 }
527
528 BoxingMethod = StringWithUTF8StringMethod;
529 BoxedType = NSStringPointer;
530 }
Patrick Beard2565c592012-05-01 21:47:19 +0000531 } else if (ValueType->isBuiltinType()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000532 // The other types we support are numeric, char and BOOL/bool. We could also
533 // provide limited support for structure types, such as NSRange, NSRect, and
534 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
535 // for more details.
536
537 // Check for a top-level character literal.
538 if (const CharacterLiteral *Char =
539 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
540 // In C, character literals have type 'int'. That's not the type we want
541 // to use to determine the Objective-c literal kind.
542 switch (Char->getKind()) {
543 case CharacterLiteral::Ascii:
544 ValueType = Context.CharTy;
545 break;
546
547 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000548 ValueType = Context.getWideCharType();
Patrick Beard0caa3942012-04-19 00:25:12 +0000549 break;
550
551 case CharacterLiteral::UTF16:
552 ValueType = Context.Char16Ty;
553 break;
554
555 case CharacterLiteral::UTF32:
556 ValueType = Context.Char32Ty;
557 break;
558 }
559 }
Fariborz Jahanian5d64abb2014-06-18 20:49:02 +0000560 CheckForIntOverflow(ValueExpr);
Patrick Beard0caa3942012-04-19 00:25:12 +0000561 // FIXME: Do I need to do anything special with BoolTy expressions?
562
563 // Look for the appropriate method within NSNumber.
564 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType);
565 BoxedType = NSNumberPointer;
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000566
567 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
568 if (!ET->getDecl()->isComplete()) {
569 Diag(SR.getBegin(), diag::err_objc_incomplete_boxed_expression_type)
570 << ValueType << ValueExpr->getSourceRange();
571 return ExprError();
572 }
573
574 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(),
575 ET->getDecl()->getIntegerType());
576 BoxedType = NSNumberPointer;
Patrick Beard0caa3942012-04-19 00:25:12 +0000577 }
578
579 if (!BoxingMethod) {
580 Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type)
581 << ValueType << ValueExpr->getSourceRange();
582 return ExprError();
583 }
584
585 // Convert the expression to the type that the parameter requires.
Alp Toker03376dc2014-07-07 09:02:20 +0000586 ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
Patrick Beard2565c592012-05-01 21:47:19 +0000587 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
588 ParamDecl);
589 ExprResult ConvertedValueExpr = PerformCopyInitialization(Entity,
590 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000591 ValueExpr);
Patrick Beard0caa3942012-04-19 00:25:12 +0000592 if (ConvertedValueExpr.isInvalid())
593 return ExprError();
594 ValueExpr = ConvertedValueExpr.get();
595
596 ObjCBoxedExpr *BoxedExpr =
597 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
598 BoxingMethod, SR);
599 return MaybeBindToTemporary(BoxedExpr);
600}
601
John McCallf2538342012-07-31 05:14:30 +0000602/// Build an ObjC subscript pseudo-object expression, given that
603/// that's supported by the runtime.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000604ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
605 Expr *IndexExpr,
606 ObjCMethodDecl *getterMethod,
607 ObjCMethodDecl *setterMethod) {
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +0000608 assert(!LangOpts.isSubscriptPointerArithmetic());
John McCall5fb5df92012-06-20 06:18:46 +0000609
John McCallf2538342012-07-31 05:14:30 +0000610 // We can't get dependent types here; our callers should have
611 // filtered them out.
612 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
613 "base or index cannot have dependent type here");
614
615 // Filter out placeholders in the index. In theory, overloads could
616 // be preserved here, although that might not actually work correctly.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000617 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
618 if (Result.isInvalid())
619 return ExprError();
620 IndexExpr = Result.get();
621
John McCallf2538342012-07-31 05:14:30 +0000622 // Perform lvalue-to-rvalue conversion on the base.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000623 Result = DefaultLvalueConversion(BaseExpr);
624 if (Result.isInvalid())
625 return ExprError();
626 BaseExpr = Result.get();
John McCallf2538342012-07-31 05:14:30 +0000627
628 // Build the pseudo-object expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000629 return ObjCSubscriptRefExpr::Create(Context, BaseExpr, IndexExpr,
630 Context.PseudoObjectTy, getterMethod,
631 setterMethod, RB);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000632}
633
634ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
635 // Look up the NSArray class, if we haven't done so already.
636 if (!NSArrayDecl) {
637 NamedDecl *IF = LookupSingleName(TUScope,
638 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
639 SR.getBegin(),
640 LookupOrdinaryName);
641 NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000642 if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000643 NSArrayDecl = ObjCInterfaceDecl::Create (Context,
644 Context.getTranslationUnitDecl(),
645 SourceLocation(),
646 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
Craig Topperc3ec1492014-05-26 06:22:03 +0000647 nullptr, SourceLocation());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000648
649 if (!NSArrayDecl) {
650 Diag(SR.getBegin(), diag::err_undeclared_nsarray);
651 return ExprError();
652 }
653 }
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000654
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000655 // Find the arrayWithObjects:count: method, if we haven't done so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000656 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000657 if (!ArrayWithObjectsMethod) {
658 Selector
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000659 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
660 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000661 if (!Method && getLangOpts().DebuggerObjCLiteral) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000662 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000663 Method = ObjCMethodDecl::Create(
664 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000665 Context.getTranslationUnitDecl(), false /*Instance*/,
Alp Toker314cc812014-01-25 16:55:45 +0000666 false /*isVariadic*/,
667 /*isPropertyAccessor=*/false,
668 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
669 ObjCMethodDecl::Required, false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000670 SmallVector<ParmVarDecl *, 2> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000671 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000672 SourceLocation(),
673 SourceLocation(),
674 &Context.Idents.get("objects"),
675 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000676 /*TInfo=*/nullptr,
677 SC_None, nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000678 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000679 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000680 SourceLocation(),
681 SourceLocation(),
682 &Context.Idents.get("cnt"),
683 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000684 /*TInfo=*/nullptr, SC_None,
685 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000686 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000687 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000688 }
689
Jordy Rose08e500c2012-05-12 17:32:44 +0000690 if (!validateBoxingMethod(*this, SR.getBegin(), NSArrayDecl, Sel, Method))
Ted Kremeneke65b0862012-03-06 20:05:56 +0000691 return ExprError();
Jordy Rose08e500c2012-05-12 17:32:44 +0000692
Jordy Rose4af44872012-05-12 17:32:56 +0000693 // Dig out the type that all elements should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000694 QualType T = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000695 const PointerType *PtrT = T->getAs<PointerType>();
696 if (!PtrT ||
697 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
698 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
699 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000700 Diag(Method->parameters()[0]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000701 diag::note_objc_literal_method_param)
702 << 0 << T
703 << Context.getPointerType(IdT.withConst());
704 return ExprError();
705 }
706
707 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000708 if (!Method->parameters()[1]->getType()->isIntegerType()) {
Jordy Rose4af44872012-05-12 17:32:56 +0000709 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
710 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000711 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000712 diag::note_objc_literal_method_param)
713 << 1
Alp Toker03376dc2014-07-07 09:02:20 +0000714 << Method->parameters()[1]->getType()
Jordy Rose4af44872012-05-12 17:32:56 +0000715 << "integral";
716 return ExprError();
717 }
718
719 // We've found a good +arrayWithObjects:count: method. Save it!
Jordy Rose08e500c2012-05-12 17:32:44 +0000720 ArrayWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000721 }
722
Alp Toker03376dc2014-07-07 09:02:20 +0000723 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000724 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000725
726 // Check that each of the elements provided is valid in a collection literal,
727 // performing conversions as necessary.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000728 Expr **ElementsBuffer = Elements.data();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000729 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
730 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
731 ElementsBuffer[I],
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000732 RequiredType, true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000733 if (Converted.isInvalid())
734 return ExprError();
735
736 ElementsBuffer[I] = Converted.get();
737 }
738
739 QualType Ty
740 = Context.getObjCObjectPointerType(
741 Context.getObjCInterfaceType(NSArrayDecl));
742
743 return MaybeBindToTemporary(
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000744 ObjCArrayLiteral::Create(Context, Elements, Ty,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000745 ArrayWithObjectsMethod, SR));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000746}
747
748ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
749 ObjCDictionaryElement *Elements,
750 unsigned NumElements) {
751 // Look up the NSDictionary class, if we haven't done so already.
752 if (!NSDictionaryDecl) {
753 NamedDecl *IF = LookupSingleName(TUScope,
754 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
755 SR.getBegin(), LookupOrdinaryName);
756 NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000757 if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000758 NSDictionaryDecl = ObjCInterfaceDecl::Create (Context,
759 Context.getTranslationUnitDecl(),
760 SourceLocation(),
761 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
Craig Topperc3ec1492014-05-26 06:22:03 +0000762 nullptr, SourceLocation());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000763
764 if (!NSDictionaryDecl) {
765 Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
766 return ExprError();
767 }
768 }
769
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000770 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
771 // so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000772 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000773 if (!DictionaryWithObjectsMethod) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000774 Selector Sel = NSAPIObj->getNSDictionarySelector(
775 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
776 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000777 if (!Method && getLangOpts().DebuggerObjCLiteral) {
778 Method = ObjCMethodDecl::Create(Context,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000779 SourceLocation(), SourceLocation(), Sel,
780 IdT,
Craig Topperc3ec1492014-05-26 06:22:03 +0000781 nullptr /*TypeSourceInfo */,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000782 Context.getTranslationUnitDecl(),
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000783 false /*Instance*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000784 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000785 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
786 ObjCMethodDecl::Required,
787 false);
788 SmallVector<ParmVarDecl *, 3> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000789 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000790 SourceLocation(),
791 SourceLocation(),
792 &Context.Idents.get("objects"),
793 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000794 /*TInfo=*/nullptr, SC_None,
795 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000796 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000797 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000798 SourceLocation(),
799 SourceLocation(),
800 &Context.Idents.get("keys"),
801 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000802 /*TInfo=*/nullptr, SC_None,
803 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000804 Params.push_back(keys);
Jordy Rose08e500c2012-05-12 17:32:44 +0000805 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000806 SourceLocation(),
807 SourceLocation(),
808 &Context.Idents.get("cnt"),
809 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000810 /*TInfo=*/nullptr, SC_None,
811 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000812 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000813 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000814 }
815
Jordy Rose08e500c2012-05-12 17:32:44 +0000816 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
817 Method))
818 return ExprError();
819
Jordy Rose4af44872012-05-12 17:32:56 +0000820 // Dig out the type that all values should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000821 QualType ValueT = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000822 const PointerType *PtrValue = ValueT->getAs<PointerType>();
823 if (!PtrValue ||
824 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000825 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
Jordy Rose4af44872012-05-12 17:32:56 +0000826 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000827 Diag(Method->parameters()[0]->getLocation(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000828 diag::note_objc_literal_method_param)
Jordy Rose4af44872012-05-12 17:32:56 +0000829 << 0 << ValueT
Ted Kremeneke65b0862012-03-06 20:05:56 +0000830 << Context.getPointerType(IdT.withConst());
831 return ExprError();
832 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000833
Jordy Rose4af44872012-05-12 17:32:56 +0000834 // Dig out the type that all keys should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000835 QualType KeyT = Method->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000836 const PointerType *PtrKey = KeyT->getAs<PointerType>();
837 if (!PtrKey ||
838 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
839 IdT)) {
840 bool err = true;
841 if (PtrKey) {
842 if (QIDNSCopying.isNull()) {
843 // key argument of selector is id<NSCopying>?
844 if (ObjCProtocolDecl *NSCopyingPDecl =
845 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
846 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
847 QIDNSCopying =
848 Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
849 (ObjCProtocolDecl**) PQ,1);
850 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
851 }
852 }
853 if (!QIDNSCopying.isNull())
854 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
855 QIDNSCopying);
856 }
857
858 if (err) {
859 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
860 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000861 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000862 diag::note_objc_literal_method_param)
863 << 1 << KeyT
864 << Context.getPointerType(IdT.withConst());
865 return ExprError();
866 }
867 }
868
869 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000870 QualType CountType = Method->parameters()[2]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000871 if (!CountType->isIntegerType()) {
872 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
873 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000874 Diag(Method->parameters()[2]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000875 diag::note_objc_literal_method_param)
876 << 2 << CountType
877 << "integral";
878 return ExprError();
879 }
880
881 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
882 DictionaryWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000883 }
884
Alp Toker03376dc2014-07-07 09:02:20 +0000885 QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000886 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
Alp Toker03376dc2014-07-07 09:02:20 +0000887 QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000888 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
889
Ted Kremeneke65b0862012-03-06 20:05:56 +0000890 // Check that each of the keys and values provided is valid in a collection
891 // literal, performing conversions as necessary.
892 bool HasPackExpansions = false;
893 for (unsigned I = 0, N = NumElements; I != N; ++I) {
894 // Check the key.
895 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
896 KeyT);
897 if (Key.isInvalid())
898 return ExprError();
899
900 // Check the value.
901 ExprResult Value
902 = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
903 if (Value.isInvalid())
904 return ExprError();
905
906 Elements[I].Key = Key.get();
907 Elements[I].Value = Value.get();
908
909 if (Elements[I].EllipsisLoc.isInvalid())
910 continue;
911
912 if (!Elements[I].Key->containsUnexpandedParameterPack() &&
913 !Elements[I].Value->containsUnexpandedParameterPack()) {
914 Diag(Elements[I].EllipsisLoc,
915 diag::err_pack_expansion_without_parameter_packs)
916 << SourceRange(Elements[I].Key->getLocStart(),
917 Elements[I].Value->getLocEnd());
918 return ExprError();
919 }
920
921 HasPackExpansions = true;
922 }
923
924
925 QualType Ty
926 = Context.getObjCObjectPointerType(
Robert Wilhelm88e02492013-08-19 07:57:02 +0000927 Context.getObjCInterfaceType(NSDictionaryDecl));
928 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
929 Context, makeArrayRef(Elements, NumElements), HasPackExpansions, Ty,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000930 DictionaryWithObjectsMethod, SR));
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000931}
932
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000933ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregorabd9e962010-04-20 15:39:42 +0000934 TypeSourceInfo *EncodedTypeInfo,
Anders Carlsson315d2292009-06-07 18:45:35 +0000935 SourceLocation RParenLoc) {
Douglas Gregorabd9e962010-04-20 15:39:42 +0000936 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlsson315d2292009-06-07 18:45:35 +0000937 QualType StrTy;
Mike Stump11289f42009-09-09 15:08:12 +0000938 if (EncodedType->isDependentType())
Anders Carlsson315d2292009-06-07 18:45:35 +0000939 StrTy = Context.DependentTy;
940 else {
Fariborz Jahaniand9bc6c32011-06-16 22:34:44 +0000941 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
942 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000943 if (RequireCompleteType(AtLoc, EncodedType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000944 diag::err_incomplete_type_objc_at_encode,
945 EncodedTypeInfo->getTypeLoc()))
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000946 return ExprError();
947
Anders Carlsson315d2292009-06-07 18:45:35 +0000948 std::string Str;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +0000949 QualType NotEncodedT;
950 Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT);
951 if (!NotEncodedT.isNull())
952 Diag(AtLoc, diag::warn_incomplete_encoded_type)
953 << EncodedType << NotEncodedT;
Anders Carlsson315d2292009-06-07 18:45:35 +0000954
955 // The type of @encode is the same as the type of the corresponding string,
956 // which is an array type.
957 StrTy = Context.CharTy;
958 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +0000959 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Anders Carlsson315d2292009-06-07 18:45:35 +0000960 StrTy.addConst();
961 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
962 ArrayType::Normal, 0);
963 }
Mike Stump11289f42009-09-09 15:08:12 +0000964
Douglas Gregorabd9e962010-04-20 15:39:42 +0000965 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlsson315d2292009-06-07 18:45:35 +0000966}
967
John McCallfaf5fb42010-08-26 23:41:50 +0000968ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
969 SourceLocation EncodeLoc,
970 SourceLocation LParenLoc,
971 ParsedType ty,
972 SourceLocation RParenLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000973 // FIXME: Preserve type source info ?
Douglas Gregorabd9e962010-04-20 15:39:42 +0000974 TypeSourceInfo *TInfo;
975 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
976 if (!TInfo)
977 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
978 PP.getLocForEndOfToken(LParenLoc));
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000979
Douglas Gregorabd9e962010-04-20 15:39:42 +0000980 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000981}
982
Fariborz Jahanian44be1542014-03-12 18:34:01 +0000983static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
984 SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +0000985 SourceLocation LParenLoc,
986 SourceLocation RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +0000987 ObjCMethodDecl *Method,
988 ObjCMethodList &MethList) {
989 ObjCMethodList *M = &MethList;
990 bool Warned = false;
991 for (M = M->getNext(); M; M=M->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +0000992 ObjCMethodDecl *MatchingMethodDecl = M->getMethod();
Fariborz Jahanian44be1542014-03-12 18:34:01 +0000993 if (MatchingMethodDecl == Method ||
994 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
995 MatchingMethodDecl->getSelector() != Method->getSelector())
996 continue;
997 if (!S.MatchTwoMethodDeclarations(Method,
998 MatchingMethodDecl, Sema::MMS_loose)) {
999 if (!Warned) {
1000 Warned = true;
1001 S.Diag(AtLoc, diag::warning_multiple_selectors)
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001002 << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
1003 << FixItHint::CreateInsertion(RParenLoc, ")");
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001004 S.Diag(Method->getLocation(), diag::note_method_declared_at)
1005 << Method->getDeclName();
1006 }
1007 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
1008 << MatchingMethodDecl->getDeclName();
1009 }
1010 }
1011 return Warned;
1012}
1013
1014static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001015 ObjCMethodDecl *Method,
1016 SourceLocation LParenLoc,
1017 SourceLocation RParenLoc,
1018 bool WarnMultipleSelectors) {
1019 if (!WarnMultipleSelectors ||
1020 S.Diags.isIgnored(diag::warning_multiple_selectors, SourceLocation()))
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001021 return;
1022 bool Warned = false;
1023 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1024 e = S.MethodPool.end(); b != e; b++) {
1025 // first, instance methods
1026 ObjCMethodList &InstMethList = b->second.first;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001027 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001028 Method, InstMethList))
1029 Warned = true;
1030
1031 // second, class methods
1032 ObjCMethodList &ClsMethList = b->second.second;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001033 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1034 Method, ClsMethList) || Warned)
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001035 return;
1036 }
1037}
1038
John McCallfaf5fb42010-08-26 23:41:50 +00001039ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1040 SourceLocation AtLoc,
1041 SourceLocation SelLoc,
1042 SourceLocation LParenLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001043 SourceLocation RParenLoc,
1044 bool WarnMultipleSelectors) {
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001045 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian890803f2015-04-15 17:26:21 +00001046 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001047 if (!Method)
1048 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian0571d9b2009-06-16 16:25:00 +00001049 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00001050 if (!Method) {
1051 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1052 Selector MatchedSel = OM->getSelector();
1053 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1054 RParenLoc.getLocWithOffset(-1));
1055 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1056 << Sel << MatchedSel
1057 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1058
1059 } else
1060 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001061 } else
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001062 DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
1063 WarnMultipleSelectors);
Chandler Carruth12c8f652015-03-27 00:55:05 +00001064
Fariborz Jahanian65a78b52014-05-09 19:51:39 +00001065 if (Method &&
1066 Method->getImplementationControl() != ObjCMethodDecl::Optional &&
Chandler Carruth12c8f652015-03-27 00:55:05 +00001067 !getSourceManager().isInSystemHeader(Method->getLocation()))
1068 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00001069
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001070 // In ARC, forbid the user from using @selector for
John McCall31168b02011-06-15 23:02:42 +00001071 // retain/release/autorelease/dealloc/retainCount.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001072 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001073 switch (Sel.getMethodFamily()) {
1074 case OMF_retain:
1075 case OMF_release:
1076 case OMF_autorelease:
1077 case OMF_retainCount:
1078 case OMF_dealloc:
1079 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1080 Sel << SourceRange(LParenLoc, RParenLoc);
1081 break;
1082
1083 case OMF_None:
1084 case OMF_alloc:
1085 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00001086 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00001087 case OMF_init:
1088 case OMF_mutableCopy:
1089 case OMF_new:
1090 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00001091 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00001092 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00001093 break;
1094 }
1095 }
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001096 QualType Ty = Context.getObjCSelType();
Daniel Dunbar45858d22010-02-03 20:11:42 +00001097 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001098}
1099
John McCallfaf5fb42010-08-26 23:41:50 +00001100ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1101 SourceLocation AtLoc,
1102 SourceLocation ProtoLoc,
1103 SourceLocation LParenLoc,
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001104 SourceLocation ProtoIdLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00001105 SourceLocation RParenLoc) {
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001106 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001107 if (!PDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001108 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001109 return true;
1110 }
Fariborz Jahaniana57d91c22014-07-25 19:45:01 +00001111 if (PDecl->hasDefinition())
1112 PDecl = PDecl->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00001113
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001114 QualType Ty = Context.getObjCProtoType();
1115 if (Ty.isNull())
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001116 return true;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001117 Ty = Context.getObjCObjectPointerType(Ty);
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001118 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001119}
1120
John McCall5f2d5562011-02-03 09:00:02 +00001121/// Try to capture an implicit reference to 'self'.
Eli Friedman24af8502012-02-03 22:47:37 +00001122ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1123 DeclContext *DC = getFunctionLevelDeclContext();
John McCall5f2d5562011-02-03 09:00:02 +00001124
1125 // If we're not in an ObjC method, error out. Note that, unlike the
1126 // C++ case, we don't require an instance method --- class methods
1127 // still have a 'self', and we really do still need to capture it!
1128 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1129 if (!method)
Craig Topperc3ec1492014-05-26 06:22:03 +00001130 return nullptr;
John McCall5f2d5562011-02-03 09:00:02 +00001131
Douglas Gregorfdf598e2012-02-18 09:37:24 +00001132 tryCaptureVariable(method->getSelfDecl(), Loc);
John McCall5f2d5562011-02-03 09:00:02 +00001133
1134 return method;
1135}
1136
Douglas Gregor64910ca2011-09-09 20:05:21 +00001137static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
Douglas Gregor813a0662015-06-19 18:14:38 +00001138 QualType origType = T;
1139 if (auto nullability = AttributedType::stripOuterNullability(T)) {
1140 if (T == Context.getObjCInstanceType()) {
1141 return Context.getAttributedType(
1142 AttributedType::getNullabilityAttrKind(*nullability),
1143 Context.getObjCIdType(),
1144 Context.getObjCIdType());
1145 }
1146
1147 return origType;
1148 }
1149
Douglas Gregor64910ca2011-09-09 20:05:21 +00001150 if (T == Context.getObjCInstanceType())
1151 return Context.getObjCIdType();
1152
Douglas Gregor813a0662015-06-19 18:14:38 +00001153 return origType;
Douglas Gregor64910ca2011-09-09 20:05:21 +00001154}
1155
Douglas Gregor813a0662015-06-19 18:14:38 +00001156/// Determine the result type of a message send based on the receiver type,
1157/// method, and the kind of message send.
1158///
1159/// This is the "base" result type, which will still need to be adjusted
1160/// to account for nullability.
1161static QualType getBaseMessageSendResultType(Sema &S,
1162 QualType ReceiverType,
1163 ObjCMethodDecl *Method,
1164 bool isClassMessage,
1165 bool isSuperMessage) {
Douglas Gregor33823722011-06-11 01:09:30 +00001166 assert(Method && "Must have a method");
1167 if (!Method->hasRelatedResultType())
1168 return Method->getSendResultType();
Douglas Gregor813a0662015-06-19 18:14:38 +00001169
1170 ASTContext &Context = S.Context;
1171
1172 // Local function that transfers the nullability of the method's
1173 // result type to the returned result.
1174 auto transferNullability = [&](QualType type) -> QualType {
1175 // If the method's result type has nullability, extract it.
1176 if (auto nullability = Method->getSendResultType()->getNullability(Context)){
1177 // Strip off any outer nullability sugar from the provided type.
1178 (void)AttributedType::stripOuterNullability(type);
1179
1180 // Form a new attributed type using the method result type's nullability.
1181 return Context.getAttributedType(
1182 AttributedType::getNullabilityAttrKind(*nullability),
1183 type,
1184 type);
1185 }
1186
1187 return type;
1188 };
1189
Douglas Gregor33823722011-06-11 01:09:30 +00001190 // If a method has a related return type:
1191 // - if the method found is an instance method, but the message send
1192 // was a class message send, T is the declared return type of the method
1193 // found
1194 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregor64910ca2011-09-09 20:05:21 +00001195 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor813a0662015-06-19 18:14:38 +00001196
1197 // - if the receiver is super, T is a pointer to the class of the
Douglas Gregor33823722011-06-11 01:09:30 +00001198 // enclosing method definition
1199 if (isSuperMessage) {
Douglas Gregor813a0662015-06-19 18:14:38 +00001200 if (ObjCMethodDecl *CurMethod = S.getCurMethodDecl())
1201 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) {
1202 return transferNullability(
1203 Context.getObjCObjectPointerType(
1204 Context.getObjCInterfaceType(Class)));
1205 }
Douglas Gregor33823722011-06-11 01:09:30 +00001206 }
Douglas Gregor813a0662015-06-19 18:14:38 +00001207
Douglas Gregor33823722011-06-11 01:09:30 +00001208 // - if the receiver is the name of a class U, T is a pointer to U
1209 if (ReceiverType->getAs<ObjCInterfaceType>() ||
1210 ReceiverType->isObjCQualifiedInterfaceType())
Douglas Gregor813a0662015-06-19 18:14:38 +00001211 return transferNullability(Context.getObjCObjectPointerType(ReceiverType));
1212 // - if the receiver is of type Class or qualified Class type,
Douglas Gregor33823722011-06-11 01:09:30 +00001213 // T is the declared return type of the method.
1214 if (ReceiverType->isObjCClassType() ||
1215 ReceiverType->isObjCQualifiedClassType())
Douglas Gregor64910ca2011-09-09 20:05:21 +00001216 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor813a0662015-06-19 18:14:38 +00001217
Douglas Gregor33823722011-06-11 01:09:30 +00001218 // - if the receiver is id, qualified id, Class, or qualified Class, T
1219 // is the receiver type, otherwise
1220 // - T is the type of the receiver expression.
Douglas Gregor813a0662015-06-19 18:14:38 +00001221 return transferNullability(ReceiverType);
1222}
1223
1224QualType Sema::getMessageSendResultType(QualType ReceiverType,
1225 ObjCMethodDecl *Method,
1226 bool isClassMessage,
1227 bool isSuperMessage) {
1228 // Produce the result type.
1229 QualType resultType = getBaseMessageSendResultType(*this, ReceiverType,
1230 Method,
1231 isClassMessage,
1232 isSuperMessage);
1233
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001234 // If this is a class message, ignore the nullability of the receiver.
1235 if (isClassMessage)
1236 return resultType;
1237
Douglas Gregor813a0662015-06-19 18:14:38 +00001238 // Map the nullability of the result into a table index.
1239 unsigned receiverNullabilityIdx = 0;
1240 if (auto nullability = ReceiverType->getNullability(Context))
1241 receiverNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1242
1243 unsigned resultNullabilityIdx = 0;
1244 if (auto nullability = resultType->getNullability(Context))
1245 resultNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1246
1247 // The table of nullability mappings, indexed by the receiver's nullability
1248 // and then the result type's nullability.
1249 static const uint8_t None = 0;
1250 static const uint8_t NonNull = 1;
1251 static const uint8_t Nullable = 2;
1252 static const uint8_t Unspecified = 3;
1253 static const uint8_t nullabilityMap[4][4] = {
1254 // None NonNull Nullable Unspecified
1255 /* None */ { None, None, Nullable, None },
1256 /* NonNull */ { None, NonNull, Nullable, Unspecified },
1257 /* Nullable */ { Nullable, Nullable, Nullable, Nullable },
1258 /* Unspecified */ { None, Unspecified, Nullable, Unspecified }
1259 };
1260
1261 unsigned newResultNullabilityIdx
1262 = nullabilityMap[receiverNullabilityIdx][resultNullabilityIdx];
1263 if (newResultNullabilityIdx == resultNullabilityIdx)
1264 return resultType;
1265
1266 // Strip off the existing nullability. This removes as little type sugar as
1267 // possible.
1268 do {
1269 if (auto attributed = dyn_cast<AttributedType>(resultType.getTypePtr())) {
1270 resultType = attributed->getModifiedType();
1271 } else {
1272 resultType = resultType.getDesugaredType(Context);
1273 }
1274 } while (resultType->getNullability(Context));
1275
1276 // Add nullability back if needed.
1277 if (newResultNullabilityIdx > 0) {
1278 auto newNullability
1279 = static_cast<NullabilityKind>(newResultNullabilityIdx-1);
1280 return Context.getAttributedType(
1281 AttributedType::getNullabilityAttrKind(newNullability),
1282 resultType, resultType);
1283 }
1284
1285 return resultType;
Douglas Gregor33823722011-06-11 01:09:30 +00001286}
John McCall5f2d5562011-02-03 09:00:02 +00001287
John McCall5ec7e7d2013-03-19 07:04:25 +00001288/// Look for an ObjC method whose result type exactly matches the given type.
1289static const ObjCMethodDecl *
1290findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1291 QualType instancetype) {
Alp Toker314cc812014-01-25 16:55:45 +00001292 if (MD->getReturnType() == instancetype)
1293 return MD;
John McCall5ec7e7d2013-03-19 07:04:25 +00001294
1295 // For these purposes, a method in an @implementation overrides a
1296 // declaration in the @interface.
1297 if (const ObjCImplDecl *impl =
1298 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1299 const ObjCContainerDecl *iface;
1300 if (const ObjCCategoryImplDecl *catImpl =
1301 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1302 iface = catImpl->getCategoryDecl();
1303 } else {
1304 iface = impl->getClassInterface();
1305 }
1306
1307 const ObjCMethodDecl *ifaceMD =
1308 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1309 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1310 }
1311
1312 SmallVector<const ObjCMethodDecl *, 4> overrides;
1313 MD->getOverriddenMethods(overrides);
1314 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1315 if (const ObjCMethodDecl *result =
1316 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1317 return result;
1318 }
1319
Craig Topperc3ec1492014-05-26 06:22:03 +00001320 return nullptr;
John McCall5ec7e7d2013-03-19 07:04:25 +00001321}
1322
1323void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1324 // Only complain if we're in an ObjC method and the required return
1325 // type doesn't match the method's declared return type.
1326 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1327 if (!MD || !MD->hasRelatedResultType() ||
Alp Toker314cc812014-01-25 16:55:45 +00001328 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
John McCall5ec7e7d2013-03-19 07:04:25 +00001329 return;
1330
1331 // Look for a method overridden by this method which explicitly uses
1332 // 'instancetype'.
1333 if (const ObjCMethodDecl *overridden =
1334 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
Aaron Ballman41b10ac2014-08-01 13:20:09 +00001335 SourceRange range = overridden->getReturnTypeSourceRange();
1336 SourceLocation loc = range.getBegin();
John McCall5ec7e7d2013-03-19 07:04:25 +00001337 if (loc.isInvalid())
1338 loc = overridden->getLocation();
1339 Diag(loc, diag::note_related_result_type_explicit)
1340 << /*current method*/ 1 << range;
1341 return;
1342 }
1343
1344 // Otherwise, if we have an interesting method family, note that.
1345 // This should always trigger if the above didn't.
1346 if (ObjCMethodFamily family = MD->getMethodFamily())
1347 Diag(MD->getLocation(), diag::note_related_result_type_family)
1348 << /*current method*/ 1
1349 << family;
1350}
1351
Douglas Gregor33823722011-06-11 01:09:30 +00001352void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1353 E = E->IgnoreParenImpCasts();
1354 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1355 if (!MsgSend)
1356 return;
1357
1358 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1359 if (!Method)
1360 return;
1361
1362 if (!Method->hasRelatedResultType())
1363 return;
Alp Toker314cc812014-01-25 16:55:45 +00001364
1365 if (Context.hasSameUnqualifiedType(
1366 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
Douglas Gregor33823722011-06-11 01:09:30 +00001367 return;
Alp Toker314cc812014-01-25 16:55:45 +00001368
1369 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
Douglas Gregorbab8a962011-09-08 01:46:34 +00001370 Context.getObjCInstanceType()))
1371 return;
1372
Douglas Gregor33823722011-06-11 01:09:30 +00001373 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1374 << Method->isInstanceMethod() << Method->getSelector()
1375 << MsgSend->getType();
1376}
1377
1378bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001379 MultiExprArg Args,
1380 Selector Sel,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001381 ArrayRef<SourceLocation> SelectorLocs,
1382 ObjCMethodDecl *Method,
Douglas Gregor33823722011-06-11 01:09:30 +00001383 bool isClassMessage, bool isSuperMessage,
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001384 SourceLocation lbrac, SourceLocation rbrac,
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00001385 SourceRange RecRange,
John McCall7decc9e2010-11-18 06:31:45 +00001386 QualType &ReturnType, ExprValueKind &VK) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001387 SourceLocation SelLoc;
1388 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1389 SelLoc = SelectorLocs.front();
1390 else
1391 SelLoc = lbrac;
1392
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001393 if (!Method) {
Daniel Dunbar83876b42008-09-11 00:04:36 +00001394 // Apply default argument promotion as for (C99 6.5.2.2p6).
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001395 for (unsigned i = 0, e = Args.size(); i != e; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001396 if (Args[i]->isTypeDependent())
1397 continue;
1398
John McCallcc5788c2013-03-04 07:34:02 +00001399 ExprResult result;
1400 if (getLangOpts().DebuggerSupport) {
1401 QualType paramTy; // ignored
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001402 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
John McCallcc5788c2013-03-04 07:34:02 +00001403 } else {
1404 result = DefaultArgumentPromotion(Args[i]);
1405 }
1406 if (result.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001407 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001408 Args[i] = result.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001409 }
Daniel Dunbar83876b42008-09-11 00:04:36 +00001410
John McCall31168b02011-06-15 23:02:42 +00001411 unsigned DiagID;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001412 if (getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00001413 DiagID = diag::err_arc_method_not_found;
1414 else
1415 DiagID = isClassMessage ? diag::warn_class_method_not_found
1416 : diag::warn_inst_method_not_found;
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001417 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001418 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
Fariborz Jahanian06499232013-06-18 17:10:58 +00001419 if (OMD && !OMD->isInvalidDecl()) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001420 if (getLangOpts().ObjCAutoRefCount)
1421 DiagID = diag::error_method_not_found_with_typo;
1422 else
1423 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1424 : diag::warn_instance_method_not_found_with_typo;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001425 Selector MatchedSel = OMD->getSelector();
1426 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
Fariborz Jahanian5ab87502014-08-12 22:16:41 +00001427 if (MatchedSel.isUnarySelector())
1428 Diag(SelLoc, DiagID)
1429 << Sel<< isClassMessage << MatchedSel
1430 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1431 else
1432 Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001433 }
1434 else
1435 Diag(SelLoc, DiagID)
1436 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001437 SelectorLocs.back());
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001438 // Find the class to which we are sending this message.
1439 if (ReceiverType->isObjCObjectPointerType()) {
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00001440 if (ObjCInterfaceDecl *ThisClass =
1441 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()) {
1442 Diag(ThisClass->getLocation(), diag::note_receiver_class_declared);
1443 if (!RecRange.isInvalid())
1444 if (ThisClass->lookupClassMethod(Sel))
1445 Diag(RecRange.getBegin(),diag::note_receiver_expr_here)
1446 << FixItHint::CreateReplacement(RecRange,
1447 ThisClass->getNameAsString());
1448 }
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001449 }
1450 }
John McCall3f4138c2011-07-13 17:56:40 +00001451
1452 // In debuggers, we want to use __unknown_anytype for these
1453 // results so that clients can cast them.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001454 if (getLangOpts().DebuggerSupport) {
John McCall3f4138c2011-07-13 17:56:40 +00001455 ReturnType = Context.UnknownAnyTy;
1456 } else {
1457 ReturnType = Context.getObjCIdType();
1458 }
John McCall7decc9e2010-11-18 06:31:45 +00001459 VK = VK_RValue;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001460 return false;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001461 }
Mike Stump11289f42009-09-09 15:08:12 +00001462
Douglas Gregor33823722011-06-11 01:09:30 +00001463 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1464 isSuperMessage);
Alp Toker314cc812014-01-25 16:55:45 +00001465 VK = Expr::getValueKindForType(Method->getReturnType());
Mike Stump11289f42009-09-09 15:08:12 +00001466
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001467 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian60462092010-04-08 00:30:06 +00001468 // Method might have more arguments than selector indicates. This is due
1469 // to addition of c-style arguments in method.
1470 if (Method->param_size() > Sel.getNumArgs())
1471 NumNamedArgs = Method->param_size();
1472 // FIXME. This need be cleaned up.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001473 if (Args.size() < NumNamedArgs) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001474 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001475 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
Fariborz Jahanian60462092010-04-08 00:30:06 +00001476 return false;
1477 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001478
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001479 bool IsError = false;
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001480 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001481 // We can't do any type-checking on a type-dependent argument.
1482 if (Args[i]->isTypeDependent())
1483 continue;
1484
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001485 Expr *argExpr = Args[i];
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001486
Alp Toker03376dc2014-07-07 09:02:20 +00001487 ParmVarDecl *param = Method->parameters()[i];
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001488 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump11289f42009-09-09 15:08:12 +00001489
John McCall4124c492011-10-17 18:40:02 +00001490 // Strip the unbridged-cast placeholder expression off unless it's
1491 // a consumed argument.
1492 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1493 !param->hasAttr<CFConsumedAttr>())
1494 argExpr = stripARCUnbridgedCast(argExpr);
1495
John McCallea0a39e2012-11-14 00:49:39 +00001496 // If the parameter is __unknown_anytype, infer its type
1497 // from the argument.
1498 if (param->getType() == Context.UnknownAnyTy) {
John McCallcc5788c2013-03-04 07:34:02 +00001499 QualType paramType;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001500 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
John McCallcc5788c2013-03-04 07:34:02 +00001501 if (argE.isInvalid()) {
John McCallea0a39e2012-11-14 00:49:39 +00001502 IsError = true;
John McCallcc5788c2013-03-04 07:34:02 +00001503 } else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001504 Args[i] = argE.get();
John McCallea0a39e2012-11-14 00:49:39 +00001505
John McCallcc5788c2013-03-04 07:34:02 +00001506 // Update the parameter type in-place.
1507 param->setType(paramType);
1508 }
1509 continue;
John McCallea0a39e2012-11-14 00:49:39 +00001510 }
1511
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001512 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
John McCall4124c492011-10-17 18:40:02 +00001513 param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001514 diag::err_call_incomplete_argument, argExpr))
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001515 return true;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001516
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001517 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
John McCall4124c492011-10-17 18:40:02 +00001518 param);
Fariborz Jahaniana1db7df2014-07-31 17:39:50 +00001519 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001520 if (ArgE.isInvalid())
1521 IsError = true;
1522 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001523 Args[i] = ArgE.getAs<Expr>();
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001524 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001525
1526 // Promote additional arguments to variadic methods.
1527 if (Method->isVariadic()) {
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001528 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001529 if (Args[i]->isTypeDependent())
1530 continue;
1531
Jordy Roseaca01f92012-05-12 17:32:52 +00001532 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
Craig Topperc3ec1492014-05-26 06:22:03 +00001533 nullptr);
John Wiegley01296292011-04-08 18:41:53 +00001534 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001535 Args[i] = Arg.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001536 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001537 } else {
1538 // Check for extra arguments to non-variadic methods.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001539 if (Args.size() != NumNamedArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00001540 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001541 diag::err_typecheck_call_too_many_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001542 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001543 << Method->getSourceRange()
Chris Lattner3b054132008-11-19 05:08:23 +00001544 << SourceRange(Args[NumNamedArgs]->getLocStart(),
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001545 Args.back()->getLocEnd());
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001546 }
1547 }
1548
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001549 DiagnoseSentinelCalls(Method, SelLoc, Args);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001550
1551 // Do additional checkings on method.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001552 IsError |= CheckObjCMethodCall(
Craig Topper8c2a2a02014-08-30 16:55:39 +00001553 Method, SelLoc, makeArrayRef(Args.data(), Args.size()));
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001554
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001555 return IsError;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001556}
1557
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001558bool Sema::isSelfExpr(Expr *RExpr) {
Fariborz Jahanianb3b1e172011-03-27 19:53:47 +00001559 // 'self' is objc 'self' in an objc method only.
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001560 ObjCMethodDecl *Method =
1561 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1562 return isSelfExpr(RExpr, Method);
1563}
1564
1565bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
John McCallfe96e0b2011-11-06 09:01:30 +00001566 if (!method) return false;
1567
John McCall31168b02011-06-15 23:02:42 +00001568 receiver = receiver->IgnoreParenLValueCasts();
1569 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCallfe96e0b2011-11-06 09:01:30 +00001570 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregor486b74e2011-09-27 16:10:05 +00001571 return true;
1572 return false;
Steve Naroff3f49fee2009-03-04 15:11:40 +00001573}
1574
John McCall526ab472011-10-25 17:37:35 +00001575/// LookupMethodInType - Look up a method in an ObjCObjectType.
1576ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1577 bool isInstance) {
1578 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1579 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1580 // Look it up in the main interface (and categories, etc.)
1581 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1582 return method;
1583
1584 // Okay, look for "private" methods declared in any
1585 // @implementations we've seen.
Anna Zaksc77a3b12012-07-27 19:07:44 +00001586 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1587 return method;
John McCall526ab472011-10-25 17:37:35 +00001588 }
1589
1590 // Check qualifiers.
Aaron Ballman1683f7b2014-03-17 15:55:30 +00001591 for (const auto *I : objType->quals())
1592 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
John McCall526ab472011-10-25 17:37:35 +00001593 return method;
1594
Craig Topperc3ec1492014-05-26 06:22:03 +00001595 return nullptr;
John McCall526ab472011-10-25 17:37:35 +00001596}
1597
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001598/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1599/// list of a qualified objective pointer type.
1600ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1601 const ObjCObjectPointerType *OPT,
1602 bool Instance)
1603{
Craig Topperc3ec1492014-05-26 06:22:03 +00001604 ObjCMethodDecl *MD = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +00001605 for (const auto *PROTO : OPT->quals()) {
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001606 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1607 return MD;
1608 }
1609 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001610 return nullptr;
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001611}
1612
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001613/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1614/// objective C interface. This is a property reference expression.
John McCalldadc5752010-08-24 06:29:42 +00001615ExprResult Sema::
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001616HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001617 Expr *BaseExpr, SourceLocation OpLoc,
1618 DeclarationName MemberName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001619 SourceLocation MemberLoc,
1620 SourceLocation SuperLoc, QualType SuperType,
1621 bool Super) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001622 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1623 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00001624
Benjamin Kramer365082d2012-05-19 16:34:46 +00001625 if (!MemberName.isIdentifier()) {
Douglas Gregord6459312011-04-20 18:19:55 +00001626 Diag(MemberLoc, diag::err_invalid_property_name)
1627 << MemberName << QualType(OPT, 0);
1628 return ExprError();
1629 }
Benjamin Kramer365082d2012-05-19 16:34:46 +00001630
1631 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregord6459312011-04-20 18:19:55 +00001632
Douglas Gregor4123a862011-11-14 22:10:01 +00001633 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1634 : BaseExpr->getSourceRange();
1635 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001636 diag::err_property_not_found_forward_class,
1637 MemberName, BaseRange))
Fariborz Jahanian7cabbe02010-12-16 00:56:28 +00001638 return ExprError();
Douglas Gregor4123a862011-11-14 22:10:01 +00001639
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001640 // Search for a declared property first.
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001641 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001642 // Check whether we can reference this property.
1643 if (DiagnoseUseOfDecl(PD, MemberLoc))
1644 return ExprError();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001645 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001646 return new (Context)
1647 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1648 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001649 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001650 return new (Context)
1651 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1652 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001653 }
1654 // Check protocols on qualified interfaces.
Aaron Ballman83731462014-03-17 16:14:00 +00001655 for (const auto *I : OPT->quals())
1656 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001657 // Check whether we can reference this property.
1658 if (DiagnoseUseOfDecl(PD, MemberLoc))
1659 return ExprError();
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001660
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001661 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001662 return new (Context) ObjCPropertyRefExpr(
1663 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
1664 SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001665 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001666 return new (Context)
1667 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1668 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001669 }
1670 // If that failed, look for an "implicit" property by seeing if the nullary
1671 // selector is implemented.
1672
1673 // FIXME: The logic for looking up nullary and unary selectors should be
1674 // shared with the code in ActOnInstanceMessage.
1675
1676 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1677 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001678
1679 // May be founf in property's qualified list.
1680 if (!Getter)
1681 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001682
1683 // If this reference is in an @implementation, check for 'private' methods.
1684 if (!Getter)
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001685 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001686
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001687 if (Getter) {
1688 // Check if we can reference this property.
1689 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1690 return ExprError();
1691 }
1692 // If we found a getter then this may be a valid dot-reference, we
1693 // will look for the matching setter, in case it is needed.
1694 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001695 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1696 PP.getSelectorTable(), Member);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001697 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001698
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001699 // May be founf in property's qualified list.
1700 if (!Setter)
1701 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1702
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001703 if (!Setter) {
1704 // If this reference is in an @implementation, also check for 'private'
1705 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001706 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001707 }
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001708
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001709 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1710 return ExprError();
1711
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001712 // Special warning if member name used in a property-dot for a setter accessor
1713 // does not use a property with same name; e.g. obj.X = ... for a property with
1714 // name 'x'.
1715 if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor()
1716 && !IFace->FindPropertyDeclaration(Member)) {
Fariborz Jahanian4eda2c02014-08-15 17:39:00 +00001717 if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) {
1718 // Do not warn if user is using property-dot syntax to make call to
1719 // user named setter.
1720 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter))
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001721 Diag(MemberLoc,
1722 diag::warn_property_access_suggest)
1723 << MemberName << QualType(OPT, 0) << PDecl->getName()
1724 << FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
Fariborz Jahanian4eda2c02014-08-15 17:39:00 +00001725 }
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001726 }
1727
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001728 if (Getter || Setter) {
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001729 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001730 return new (Context)
1731 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1732 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001733 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001734 return new (Context)
1735 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1736 OK_ObjCProperty, MemberLoc, BaseExpr);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001737
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001738 }
1739
1740 // Attempt to correct for typos in property names.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001741 if (TypoCorrection Corrected =
1742 CorrectTypo(DeclarationNameInfo(MemberName, MemberLoc),
1743 LookupOrdinaryName, nullptr, nullptr,
1744 llvm::make_unique<DeclFilterCCC<ObjCPropertyDecl>>(),
1745 CTK_ErrorRecovery, IFace, false, OPT)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001746 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1747 << MemberName << QualType(OPT, 0));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001748 DeclarationName TypoResult = Corrected.getCorrection();
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001749 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1750 TypoResult, MemberLoc,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001751 SuperLoc, SuperType, Super);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001752 }
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001753 ObjCInterfaceDecl *ClassDeclared;
1754 if (ObjCIvarDecl *Ivar =
1755 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1756 QualType T = Ivar->getType();
1757 if (const ObjCObjectPointerType * OBJPT =
1758 T->getAsObjCInterfacePointerType()) {
Douglas Gregor4123a862011-11-14 22:10:01 +00001759 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001760 diag::err_property_not_as_forward_class,
1761 MemberName, BaseExpr))
Douglas Gregor4123a862011-11-14 22:10:01 +00001762 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001763 }
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001764 Diag(MemberLoc,
1765 diag::err_ivar_access_using_property_syntax_suggest)
1766 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1767 << FixItHint::CreateReplacement(OpLoc, "->");
1768 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001769 }
Chris Lattner90c58fa2010-04-11 07:51:10 +00001770
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001771 Diag(MemberLoc, diag::err_property_not_found)
1772 << MemberName << QualType(OPT, 0);
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001773 if (Setter)
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001774 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001775 << MemberName << BaseExpr->getSourceRange();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001776 return ExprError();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001777}
1778
1779
1780
John McCalldadc5752010-08-24 06:29:42 +00001781ExprResult Sema::
Chris Lattnera36ec422010-04-11 08:28:14 +00001782ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1783 IdentifierInfo &propertyName,
1784 SourceLocation receiverNameLoc,
1785 SourceLocation propertyNameLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00001786
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001787 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001788 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1789 receiverNameLoc);
Douglas Gregor33823722011-06-11 01:09:30 +00001790
1791 bool IsSuper = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00001792 if (!IFace) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001793 // If the "receiver" is 'super' in a method, handle it as an expression-like
1794 // property reference.
John McCall5f2d5562011-02-03 09:00:02 +00001795 if (receiverNamePtr->isStr("super")) {
Douglas Gregor33823722011-06-11 01:09:30 +00001796 IsSuper = true;
1797
Eli Friedman24af8502012-02-03 22:47:37 +00001798 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001799 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) {
1800 if (CurMethod->isInstanceMethod()) {
1801 ObjCInterfaceDecl *Super = Class->getSuperClass();
1802 if (!Super) {
1803 // The current class does not have a superclass.
1804 Diag(receiverNameLoc, diag::error_root_class_cannot_use_super)
1805 << Class->getIdentifier();
1806 return ExprError();
1807 }
1808 QualType T = Context.getObjCInterfaceType(Super);
1809 T = Context.getObjCObjectPointerType(T);
1810
1811 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
1812 /*BaseExpr*/nullptr,
1813 SourceLocation()/*OpLoc*/,
1814 &propertyName,
1815 propertyNameLoc,
1816 receiverNameLoc, T, true);
Fariborz Jahanian05e2aaa2013-03-11 22:26:33 +00001817 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001818
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001819 // Otherwise, if this is a class method, try dispatching to our
1820 // superclass.
1821 IFace = Class->getSuperClass();
Chris Lattnera36ec422010-04-11 08:28:14 +00001822 }
Chris Lattnera36ec422010-04-11 08:28:14 +00001823 }
John McCall5f2d5562011-02-03 09:00:02 +00001824 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001825
1826 if (!IFace) {
Alp Tokerec543272013-12-24 09:48:30 +00001827 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
1828 << tok::l_paren;
Chris Lattnera36ec422010-04-11 08:28:14 +00001829 return ExprError();
1830 }
1831 }
1832
1833 // Search for a declared property first.
Steve Naroff9527bbf2009-03-09 21:12:44 +00001834 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001835 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001836
1837 // If this reference is in an @implementation, check for 'private' methods.
1838 if (!Getter)
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001839 Getter = IFace->lookupPrivateClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001840
1841 if (Getter) {
1842 // FIXME: refactor/share with ActOnMemberReference().
1843 // Check if we can reference this property.
1844 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1845 return ExprError();
1846 }
Mike Stump11289f42009-09-09 15:08:12 +00001847
Steve Naroff9527bbf2009-03-09 21:12:44 +00001848 // Look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00001849 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001850 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1851 PP.getSelectorTable(),
1852 &propertyName);
Mike Stump11289f42009-09-09 15:08:12 +00001853
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001854 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001855 if (!Setter) {
1856 // If this reference is in an @implementation, also check for 'private'
1857 // methods.
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001858 Setter = IFace->lookupPrivateClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001859 }
1860 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00001861 if (!Setter)
1862 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001863
1864 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1865 return ExprError();
1866
1867 if (Getter || Setter) {
Douglas Gregor33823722011-06-11 01:09:30 +00001868 if (IsSuper)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001869 return new (Context)
1870 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1871 OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
1872 Context.getObjCInterfaceType(IFace));
Douglas Gregor33823722011-06-11 01:09:30 +00001873
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001874 return new (Context) ObjCPropertyRefExpr(
1875 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
1876 propertyNameLoc, receiverNameLoc, IFace);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001877 }
1878 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1879 << &propertyName << Context.getObjCInterfaceType(IFace));
1880}
1881
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001882namespace {
1883
1884class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1885 public:
1886 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1887 // Determine whether "super" is acceptable in the current context.
1888 if (Method && Method->getClassInterface())
1889 WantObjCSuper = Method->getClassInterface()->getSuperClass();
1890 }
1891
Craig Toppere14c0f82014-03-12 04:55:44 +00001892 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001893 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1894 candidate.isKeyword("super");
1895 }
1896};
1897
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001898}
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001899
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001900Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001901 IdentifierInfo *Name,
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001902 SourceLocation NameLoc,
1903 bool IsSuper,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001904 bool HasTrailingDot,
John McCallba7bf592010-08-24 05:47:05 +00001905 ParsedType &ReceiverType) {
1906 ReceiverType = ParsedType();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001907
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001908 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor57756ea2010-10-14 22:11:03 +00001909 // messaging super. If the identifier is "super" and there is a
1910 // trailing dot, it's an instance message.
1911 if (IsSuper && S->isInObjcMethodScope())
1912 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001913
1914 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1915 LookupName(Result, S);
1916
1917 switch (Result.getResultKind()) {
1918 case LookupResult::NotFound:
Douglas Gregorca7136b2010-04-19 20:09:36 +00001919 // Normal name lookup didn't find anything. If we're in an
1920 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor57756ea2010-10-14 22:11:03 +00001921 // FIXME: This is a hack. Ivar lookup should be part of normal
1922 // lookup.
Douglas Gregorca7136b2010-04-19 20:09:36 +00001923 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidis3a8de5b2011-11-09 00:22:48 +00001924 if (!Method->getClassInterface()) {
1925 // Fall back: let the parser try to parse it as an instance message.
1926 return ObjCInstanceMessage;
1927 }
1928
Douglas Gregorca7136b2010-04-19 20:09:36 +00001929 ObjCInterfaceDecl *ClassDeclared;
1930 if (Method->getClassInterface()->lookupInstanceVariable(Name,
1931 ClassDeclared))
1932 return ObjCInstanceMessage;
1933 }
Douglas Gregor57756ea2010-10-14 22:11:03 +00001934
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001935 // Break out; we'll perform typo correction below.
1936 break;
1937
1938 case LookupResult::NotFoundInCurrentInstantiation:
1939 case LookupResult::FoundOverloaded:
1940 case LookupResult::FoundUnresolvedValue:
1941 case LookupResult::Ambiguous:
1942 Result.suppressDiagnostics();
1943 return ObjCInstanceMessage;
1944
1945 case LookupResult::Found: {
Fariborz Jahanian14889fc2011-02-08 00:23:07 +00001946 // If the identifier is a class or not, and there is a trailing dot,
1947 // it's an instance message.
1948 if (HasTrailingDot)
1949 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001950 // We found something. If it's a type, then we have a class
1951 // message. Otherwise, it's an instance message.
1952 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001953 QualType T;
1954 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1955 T = Context.getObjCInterfaceType(Class);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001956 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
Douglas Gregore5798dc2010-04-21 20:38:13 +00001957 T = Context.getTypeDeclType(Type);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001958 DiagnoseUseOfDecl(Type, NameLoc);
1959 }
1960 else
Douglas Gregore5798dc2010-04-21 20:38:13 +00001961 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001962
Douglas Gregore5798dc2010-04-21 20:38:13 +00001963 // We have a class message, and T is the type we're
1964 // messaging. Build source-location information for it.
1965 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +00001966 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregore5798dc2010-04-21 20:38:13 +00001967 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001968 }
1969 }
1970
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001971 if (TypoCorrection Corrected = CorrectTypo(
1972 Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr,
1973 llvm::make_unique<ObjCInterfaceOrSuperCCC>(getCurMethodDecl()),
1974 CTK_ErrorRecovery, nullptr, false, nullptr, false)) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001975 if (Corrected.isKeyword()) {
1976 // If we've found the keyword "super" (the only keyword that would be
1977 // returned by CorrectTypo), this is a send to super.
Richard Smithf9b15102013-08-17 00:46:16 +00001978 diagnoseTypo(Corrected,
1979 PDiag(diag::err_unknown_receiver_suggest) << Name);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001980 return ObjCSuperMessage;
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001981 } else if (ObjCInterfaceDecl *Class =
Richard Smithf9b15102013-08-17 00:46:16 +00001982 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001983 // If we found a declaration, correct when it refers to an Objective-C
1984 // class.
Richard Smithf9b15102013-08-17 00:46:16 +00001985 diagnoseTypo(Corrected,
1986 PDiag(diag::err_unknown_receiver_suggest) << Name);
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001987 QualType T = Context.getObjCInterfaceType(Class);
1988 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1989 ReceiverType = CreateParsedType(T, TSInfo);
1990 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001991 }
1992 }
Richard Smithf9b15102013-08-17 00:46:16 +00001993
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001994 // Fall back: let the parser try to parse it as an instance message.
1995 return ObjCInstanceMessage;
1996}
Steve Naroff9527bbf2009-03-09 21:12:44 +00001997
John McCalldadc5752010-08-24 06:29:42 +00001998ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001999 SourceLocation SuperLoc,
2000 Selector Sel,
2001 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002002 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002003 SourceLocation RBracLoc,
2004 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002005 // Determine whether we are inside a method or not.
Eli Friedman24af8502012-02-03 22:47:37 +00002006 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregor4fdba132010-04-21 20:01:04 +00002007 if (!Method) {
2008 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
2009 return ExprError();
2010 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002011
Douglas Gregor4fdba132010-04-21 20:01:04 +00002012 ObjCInterfaceDecl *Class = Method->getClassInterface();
2013 if (!Class) {
2014 Diag(SuperLoc, diag::error_no_super_class_message)
2015 << Method->getDeclName();
2016 return ExprError();
2017 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002018
Douglas Gregor4fdba132010-04-21 20:01:04 +00002019 ObjCInterfaceDecl *Super = Class->getSuperClass();
2020 if (!Super) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002021 // The current class does not have a superclass.
Ted Kremenek499897b2011-01-23 17:21:34 +00002022 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
2023 << Class->getIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002024 return ExprError();
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002025 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002026
Douglas Gregor4fdba132010-04-21 20:01:04 +00002027 // We are in a method whose class has a superclass, so 'super'
2028 // is acting as a keyword.
Jordan Rose2afd6612012-10-19 16:05:26 +00002029 if (Method->getSelector() == Sel)
2030 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber715abaf2011-08-22 17:25:57 +00002031
Jordan Rose2afd6612012-10-19 16:05:26 +00002032 if (Method->isInstanceMethod()) {
Douglas Gregor4fdba132010-04-21 20:01:04 +00002033 // Since we are in an instance method, this is an instance
2034 // message to the superclass instance.
2035 QualType SuperTy = Context.getObjCInterfaceType(Super);
2036 SuperTy = Context.getObjCObjectPointerType(SuperTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00002037 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
2038 Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002039 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002040 }
Douglas Gregor4fdba132010-04-21 20:01:04 +00002041
2042 // Since we are in a class method, this is a class message to
2043 // the superclass.
Craig Topperc3ec1492014-05-26 06:22:03 +00002044 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
Douglas Gregor4fdba132010-04-21 20:01:04 +00002045 Context.getObjCInterfaceType(Super),
Craig Topperc3ec1492014-05-26 06:22:03 +00002046 SuperLoc, Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002047 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002048}
2049
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002050
2051ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
2052 bool isSuperReceiver,
2053 SourceLocation Loc,
2054 Selector Sel,
2055 ObjCMethodDecl *Method,
2056 MultiExprArg Args) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002057 TypeSourceInfo *receiverTypeInfo = nullptr;
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002058 if (!ReceiverType.isNull())
2059 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
2060
2061 return BuildClassMessage(receiverTypeInfo, ReceiverType,
2062 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
2063 Sel, Method, Loc, Loc, Loc, Args,
2064 /*isImplicit=*/true);
2065
2066}
2067
Ted Kremeneke65b0862012-03-06 20:05:56 +00002068static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2069 unsigned DiagID,
2070 bool (*refactor)(const ObjCMessageExpr *,
2071 const NSAPI &, edit::Commit &)) {
2072 SourceLocation MsgLoc = Msg->getExprLoc();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002073 if (S.Diags.isIgnored(DiagID, MsgLoc))
Ted Kremeneke65b0862012-03-06 20:05:56 +00002074 return;
2075
2076 SourceManager &SM = S.SourceMgr;
2077 edit::Commit ECommit(SM, S.LangOpts);
2078 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2079 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2080 << Msg->getSelector() << Msg->getSourceRange();
2081 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2082 if (!ECommit.isCommitable())
2083 return;
2084 for (edit::Commit::edit_iterator
2085 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2086 const edit::Commit::Edit &Edit = *I;
2087 switch (Edit.Kind) {
2088 case edit::Commit::Act_Insert:
2089 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2090 Edit.Text,
2091 Edit.BeforePrev));
2092 break;
2093 case edit::Commit::Act_InsertFromRange:
2094 Builder.AddFixItHint(
2095 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2096 Edit.getInsertFromRange(SM),
2097 Edit.BeforePrev));
2098 break;
2099 case edit::Commit::Act_Remove:
2100 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2101 break;
2102 }
2103 }
2104 }
2105}
2106
2107static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2108 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2109 edit::rewriteObjCRedundantCallWithLiteral);
2110}
2111
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002112/// \brief Diagnose use of %s directive in an NSString which is being passed
2113/// as formatting string to formatting method.
2114static void
2115DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S,
2116 ObjCMethodDecl *Method,
2117 Selector Sel,
2118 Expr **Args, unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002119 unsigned Idx = 0;
2120 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002121 ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily();
2122 if (SFFamily == ObjCStringFormatFamily::SFF_NSString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002123 Idx = 0;
2124 Format = true;
2125 }
2126 else if (Method) {
2127 for (const auto *I : Method->specific_attrs<FormatAttr>()) {
2128 if (S.GetFormatNSStringIdx(I, Idx)) {
2129 Format = true;
2130 break;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002131 }
2132 }
2133 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002134 if (!Format || NumArgs <= Idx)
2135 return;
2136
2137 Expr *FormatExpr = Args[Idx];
2138 if (ObjCStringLiteral *OSL =
2139 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) {
2140 StringLiteral *FormatString = OSL->getString();
2141 if (S.FormatStringHasSArg(FormatString)) {
2142 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2143 << "%s" << 0 << 0;
2144 if (Method)
2145 S.Diag(Method->getLocation(), diag::note_method_declared_at)
2146 << Method->getDeclName();
2147 }
2148 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002149}
2150
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002151/// \brief Build an Objective-C class message expression.
2152///
2153/// This routine takes care of both normal class messages and
2154/// class messages to the superclass.
2155///
2156/// \param ReceiverTypeInfo Type source information that describes the
2157/// receiver of this message. This may be NULL, in which case we are
2158/// sending to the superclass and \p SuperLoc must be a valid source
2159/// location.
2160
2161/// \param ReceiverType The type of the object receiving the
2162/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2163/// type as that refers to. For a superclass send, this is the type of
2164/// the superclass.
2165///
2166/// \param SuperLoc The location of the "super" keyword in a
2167/// superclass message.
2168///
2169/// \param Sel The selector to which the message is being sent.
2170///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002171/// \param Method The method that this class message is invoking, if
2172/// already known.
2173///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002174/// \param LBracLoc The location of the opening square bracket ']'.
2175///
James Dennettffad8b72012-06-22 08:10:18 +00002176/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002177///
James Dennettffad8b72012-06-22 08:10:18 +00002178/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002179ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002180 QualType ReceiverType,
2181 SourceLocation SuperLoc,
2182 Selector Sel,
2183 ObjCMethodDecl *Method,
2184 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002185 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002186 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002187 MultiExprArg ArgsIn,
2188 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002189 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00002190 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002191 if (LBracLoc.isInvalid()) {
2192 Diag(Loc, diag::err_missing_open_square_message_send)
2193 << FixItHint::CreateInsertion(Loc, "[");
2194 LBracLoc = Loc;
2195 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002196 SourceLocation SelLoc;
2197 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2198 SelLoc = SelectorLocs.front();
2199 else
2200 SelLoc = Loc;
2201
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002202 if (ReceiverType->isDependentType()) {
2203 // If the receiver type is dependent, we can't type-check anything
2204 // at this point. Build a dependent expression.
2205 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002206 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002207 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002208 return ObjCMessageExpr::Create(
2209 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
2210 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2211 isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002212 }
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002213
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002214 // Find the class to which we are sending this message.
Craig Topperc3ec1492014-05-26 06:22:03 +00002215 ObjCInterfaceDecl *Class = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00002216 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2217 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002218 Diag(Loc, diag::err_invalid_receiver_class_message)
2219 << ReceiverType;
2220 return ExprError();
Steve Naroffe2177fb2008-07-25 19:39:00 +00002221 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002222 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanianc27cd1b2011-10-15 19:18:36 +00002223 // objc++ diagnoses during typename annotation.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002224 if (!getLangOpts().CPlusPlus)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002225 (void)DiagnoseUseOfDecl(Class, SelLoc);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002226 // Find the method we are messaging.
Douglas Gregorb5186b12010-04-22 17:01:48 +00002227 if (!Method) {
Douglas Gregor4123a862011-11-14 22:10:01 +00002228 SourceRange TypeRange
2229 = SuperLoc.isValid()? SourceRange(SuperLoc)
2230 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002231 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002232 (getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002233 ? diag::err_arc_receiver_forward_class
2234 : diag::warn_receiver_forward_class),
2235 TypeRange)) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002236 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorb5186b12010-04-22 17:01:48 +00002237 Method = LookupFactoryMethodInGlobalPool(Sel,
2238 SourceRange(LBracLoc, RBracLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00002239 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002240 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2241 << Method->getDeclName();
2242 }
2243 if (!Method)
2244 Method = Class->lookupClassMethod(Sel);
2245
2246 // If we have an implementation in scope, check "private" methods.
2247 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002248 Method = Class->lookupPrivateClassMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002249
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002250 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002251 return ExprError();
Fariborz Jahanian1bd844d2009-05-08 23:02:36 +00002252 }
Mike Stump11289f42009-09-09 15:08:12 +00002253
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002254 // Check the argument types and determine the result type.
2255 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002256 ExprValueKind VK = VK_RValue;
2257
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002258 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002259 Expr **Args = ArgsIn.data();
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002260 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2261 Sel, SelectorLocs,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00002262 Method, true,
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00002263 SuperLoc.isValid(), LBracLoc, RBracLoc,
2264 SourceRange(),
Douglas Gregor33823722011-06-11 01:09:30 +00002265 ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002266 return ExprError();
Ted Kremeneka3a37ae2008-06-24 15:50:53 +00002267
Alp Toker314cc812014-01-25 16:55:45 +00002268 if (Method && !Method->getReturnType()->isVoidType() &&
2269 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002270 diag::err_illegal_message_expr_incomplete_type))
2271 return ExprError();
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002272
Fariborz Jahaniane8b45502014-08-22 19:52:49 +00002273 // Warn about explicit call of +initialize on its own class. But not on 'super'.
Fariborz Jahanian42292282014-08-25 21:27:38 +00002274 if (Method && Method->getMethodFamily() == OMF_initialize) {
2275 if (!SuperLoc.isValid()) {
2276 const ObjCInterfaceDecl *ID =
2277 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext());
2278 if (ID == Class) {
2279 Diag(Loc, diag::warn_direct_initialize_call);
2280 Diag(Method->getLocation(), diag::note_method_declared_at)
2281 << Method->getDeclName();
2282 }
2283 }
2284 else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2285 // [super initialize] is allowed only within an +initialize implementation
2286 if (CurMeth->getMethodFamily() != OMF_initialize) {
2287 Diag(Loc, diag::warn_direct_super_initialize_call);
2288 Diag(Method->getLocation(), diag::note_method_declared_at)
2289 << Method->getDeclName();
2290 Diag(CurMeth->getLocation(), diag::note_method_declared_at)
2291 << CurMeth->getDeclName();
2292 }
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002293 }
2294 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002295
2296 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2297
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002298 // Construct the appropriate ObjCMessageExpr.
Ted Kremeneke65b0862012-03-06 20:05:56 +00002299 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002300 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002301 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002302 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002303 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002304 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002305 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002306 else {
John McCall7decc9e2010-11-18 06:31:45 +00002307 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002308 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002309 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002310 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002311 if (!isImplicit)
2312 checkCocoaAPI(*this, Result);
2313 }
Douglas Gregoraae38d62010-05-22 05:17:18 +00002314 return MaybeBindToTemporary(Result);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002315}
2316
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002317// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002318// ArgExprs is optional - if it is present, the number of expressions
2319// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002320ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor3e972002010-09-15 23:19:31 +00002321 ParsedType Receiver,
2322 Selector Sel,
2323 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002324 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor3e972002010-09-15 23:19:31 +00002325 SourceLocation RBracLoc,
2326 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002327 TypeSourceInfo *ReceiverTypeInfo;
2328 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2329 if (ReceiverType.isNull())
2330 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002331
Mike Stump11289f42009-09-09 15:08:12 +00002332
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002333 if (!ReceiverTypeInfo)
2334 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2335
2336 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002337 /*SuperLoc=*/SourceLocation(), Sel,
2338 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2339 Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002340}
2341
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002342ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2343 QualType ReceiverType,
2344 SourceLocation Loc,
2345 Selector Sel,
2346 ObjCMethodDecl *Method,
2347 MultiExprArg Args) {
2348 return BuildInstanceMessage(Receiver, ReceiverType,
2349 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2350 Sel, Method, Loc, Loc, Loc, Args,
2351 /*isImplicit=*/true);
2352}
2353
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002354/// \brief Build an Objective-C instance message expression.
2355///
2356/// This routine takes care of both normal instance messages and
2357/// instance messages to the superclass instance.
2358///
2359/// \param Receiver The expression that computes the object that will
2360/// receive this message. This may be empty, in which case we are
2361/// sending to the superclass instance and \p SuperLoc must be a valid
2362/// source location.
2363///
2364/// \param ReceiverType The (static) type of the object receiving the
2365/// message. When a \p Receiver expression is provided, this is the
2366/// same type as that expression. For a superclass instance send, this
2367/// is a pointer to the type of the superclass.
2368///
2369/// \param SuperLoc The location of the "super" keyword in a
2370/// superclass instance message.
2371///
2372/// \param Sel The selector to which the message is being sent.
2373///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002374/// \param Method The method that this instance message is invoking, if
2375/// already known.
2376///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002377/// \param LBracLoc The location of the opening square bracket ']'.
2378///
James Dennettffad8b72012-06-22 08:10:18 +00002379/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002380///
James Dennettffad8b72012-06-22 08:10:18 +00002381/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002382ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002383 QualType ReceiverType,
2384 SourceLocation SuperLoc,
2385 Selector Sel,
2386 ObjCMethodDecl *Method,
2387 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002388 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002389 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002390 MultiExprArg ArgsIn,
2391 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002392 // The location of the receiver.
2393 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002394 SourceRange RecRange =
2395 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2396 SourceLocation SelLoc;
2397 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2398 SelLoc = SelectorLocs.front();
2399 else
2400 SelLoc = Loc;
2401
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002402 if (LBracLoc.isInvalid()) {
2403 Diag(Loc, diag::err_missing_open_square_message_send)
2404 << FixItHint::CreateInsertion(Loc, "[");
2405 LBracLoc = Loc;
2406 }
2407
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002408 // If we have a receiver expression, perform appropriate promotions
2409 // and determine receiver type.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002410 if (Receiver) {
John McCall4124c492011-10-17 18:40:02 +00002411 if (Receiver->hasPlaceholderType()) {
Douglas Gregord8fb1e32011-12-01 01:37:36 +00002412 ExprResult Result;
2413 if (Receiver->getType() == Context.UnknownAnyTy)
2414 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2415 else
2416 Result = CheckPlaceholderExpr(Receiver);
2417 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002418 Receiver = Result.get();
John McCall4124c492011-10-17 18:40:02 +00002419 }
2420
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002421 if (Receiver->isTypeDependent()) {
2422 // If the receiver is type-dependent, we can't type-check anything
2423 // at this point. Build a dependent expression.
2424 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002425 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002426 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002427 return ObjCMessageExpr::Create(
2428 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
2429 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2430 RBracLoc, isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002431 }
2432
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002433 // If necessary, apply function/array conversion to the receiver.
2434 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00002435 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2436 if (Result.isInvalid())
2437 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002438 Receiver = Result.get();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002439 ReceiverType = Receiver->getType();
John McCall80c93a02013-03-01 09:20:14 +00002440
2441 // If the receiver is an ObjC pointer, a block pointer, or an
2442 // __attribute__((NSObject)) pointer, we don't need to do any
2443 // special conversion in order to look up a receiver.
2444 if (ReceiverType->isObjCRetainableType()) {
2445 // do nothing
2446 } else if (!getLangOpts().ObjCAutoRefCount &&
2447 !Context.getObjCIdType().isNull() &&
2448 (ReceiverType->isPointerType() ||
2449 ReceiverType->isIntegerType())) {
2450 // Implicitly convert integers and pointers to 'id' but emit a warning.
2451 // But not in ARC.
2452 Diag(Loc, diag::warn_bad_receiver_type)
2453 << ReceiverType
2454 << Receiver->getSourceRange();
2455 if (ReceiverType->isPointerType()) {
2456 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002457 CK_CPointerToObjCPointerCast).get();
John McCall80c93a02013-03-01 09:20:14 +00002458 } else {
2459 // TODO: specialized warning on null receivers?
2460 bool IsNull = Receiver->isNullPointerConstant(Context,
2461 Expr::NPC_ValueDependentIsNull);
2462 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2463 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002464 Kind).get();
John McCall80c93a02013-03-01 09:20:14 +00002465 }
2466 ReceiverType = Receiver->getType();
2467 } else if (getLangOpts().CPlusPlus) {
Douglas Gregor4b60a152013-11-07 22:34:54 +00002468 // The receiver must be a complete type.
2469 if (RequireCompleteType(Loc, Receiver->getType(),
2470 diag::err_incomplete_receiver_type))
2471 return ExprError();
2472
John McCall80c93a02013-03-01 09:20:14 +00002473 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2474 if (result.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002475 Receiver = result.get();
John McCall80c93a02013-03-01 09:20:14 +00002476 ReceiverType = Receiver->getType();
2477 }
2478 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002479 }
2480
John McCall80c93a02013-03-01 09:20:14 +00002481 // There's a somewhat weird interaction here where we assume that we
2482 // won't actually have a method unless we also don't need to do some
2483 // of the more detailed type-checking on the receiver.
2484
Douglas Gregorb5186b12010-04-22 17:01:48 +00002485 if (!Method) {
2486 // Handle messages to id.
Fariborz Jahanian32e59ba2010-08-10 18:10:50 +00002487 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002488 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002489 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2490 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002491 SourceRange(LBracLoc, RBracLoc),
2492 receiverIsId);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002493 if (!Method)
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002494 Method = LookupFactoryMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002495 SourceRange(LBracLoc,RBracLoc),
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002496 receiverIsId);
Fariborz Jahanian05e77f82014-11-07 23:51:15 +00002497 if (Method) {
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00002498 if (ObjCMethodDecl *BestMethod =
Fariborz Jahaniand288fad2014-08-13 23:38:04 +00002499 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00002500 Method = BestMethod;
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002501 if (!AreMultipleMethodsInGlobalPool(Sel, Method,
2502 SourceRange(LBracLoc, RBracLoc),
2503 receiverIsId)) {
Sylvestre Ledru30f17082014-11-17 18:26:39 +00002504 DiagnoseUseOfDecl(Method, SelLoc);
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002505 }
Fariborz Jahanian05e77f82014-11-07 23:51:15 +00002506 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002507 } else if (ReceiverType->isObjCClassType() ||
2508 ReceiverType->isObjCQualifiedClassType()) {
2509 // Handle messages to Class.
Nico Weber2e0c8f72014-12-27 03:58:08 +00002510 // We allow sending a message to a qualified Class ("Class<foo>"), which
2511 // is ok as long as one of the protocols implements the selector (if not,
2512 // warn).
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002513 if (const ObjCObjectPointerType *QClassTy
2514 = ReceiverType->getAsObjCQualifiedClassType()) {
2515 // Search protocols for class methods.
2516 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2517 if (!Method) {
2518 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2519 // warn if instance method found for a Class message.
2520 if (Method) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002521 Diag(SelLoc, diag::warn_instance_method_on_class_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002522 << Method->getSelector() << Sel;
Ted Kremenek59b10db2012-02-27 22:55:11 +00002523 Diag(Method->getLocation(), diag::note_method_declared_at)
2524 << Method->getDeclName();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002525 }
Steve Naroff3f49fee2009-03-04 15:11:40 +00002526 }
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002527 } else {
2528 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2529 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2530 // First check the public methods in the class interface.
2531 Method = ClassDecl->lookupClassMethod(Sel);
2532
2533 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002534 Method = ClassDecl->lookupPrivateClassMethod(Sel);
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002535 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002536 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002537 return ExprError();
2538 }
2539 if (!Method) {
2540 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregor486b74e2011-09-27 16:10:05 +00002541 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002542 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002543 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002544 if (!Method) {
2545 // If no class (factory) method was found, check if an _instance_
2546 // method of the same name exists in the root class only.
2547 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002548 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002549 if (Method)
2550 if (const ObjCInterfaceDecl *ID =
2551 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2552 if (ID->getSuperClass())
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002553 Diag(SelLoc, diag::warn_root_inst_method_not_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002554 << Sel << SourceRange(LBracLoc, RBracLoc);
2555 }
2556 }
Fariborz Jahaniand288fad2014-08-13 23:38:04 +00002557 if (Method)
2558 if (ObjCMethodDecl *BestMethod =
2559 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
2560 Method = BestMethod;
Douglas Gregor9a129192010-04-21 00:45:42 +00002561 }
2562 }
2563 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002564 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00002565 ObjCInterfaceDecl *ClassDecl = nullptr;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002566
2567 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2568 // long as one of the protocols implements the selector (if not, warn).
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002569 // And as long as message is not deprecated/unavailable (warn if it is).
Douglas Gregorb5186b12010-04-22 17:01:48 +00002570 if (const ObjCObjectPointerType *QIdTy
2571 = ReceiverType->getAsObjCQualifiedIdType()) {
2572 // Search protocols for instance methods.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002573 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2574 if (!Method)
2575 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002576 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002577 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002578 } else if (const ObjCObjectPointerType *OCIType
2579 = ReceiverType->getAsObjCInterfacePointerType()) {
2580 // We allow sending a message to a pointer to an interface (an object).
2581 ClassDecl = OCIType->getInterfaceDecl();
John McCall31168b02011-06-15 23:02:42 +00002582
Douglas Gregor4123a862011-11-14 22:10:01 +00002583 // Try to complete the type. Under ARC, this is a hard error from which
2584 // we don't try to recover.
Craig Topperc3ec1492014-05-26 06:22:03 +00002585 const ObjCInterfaceDecl *forwardClass = nullptr;
Douglas Gregor4123a862011-11-14 22:10:01 +00002586 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002587 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002588 ? diag::err_arc_receiver_forward_instance
2589 : diag::warn_receiver_forward_instance,
2590 Receiver? Receiver->getSourceRange()
2591 : SourceRange(SuperLoc))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002592 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregor4123a862011-11-14 22:10:01 +00002593 return ExprError();
2594
2595 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanianc934de62012-02-03 01:02:44 +00002596 Diag(Receiver ? Receiver->getLocStart()
2597 : SuperLoc, diag::note_receiver_is_id);
Craig Topperc3ec1492014-05-26 06:22:03 +00002598 Method = nullptr;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002599 } else {
2600 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCall31168b02011-06-15 23:02:42 +00002601 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002602
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002603 if (!Method)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002604 // Search protocol qualifiers.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002605 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2606
Douglas Gregorb5186b12010-04-22 17:01:48 +00002607 if (!Method) {
2608 // If we have implementations in scope, check "private" methods.
Anna Zaksc77a3b12012-07-27 19:07:44 +00002609 Method = ClassDecl->lookupPrivateMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002610
David Blaikiebbafb8a2012-03-11 07:00:24 +00002611 if (!Method && getLangOpts().ObjCAutoRefCount) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002612 Diag(SelLoc, diag::err_arc_may_not_respond)
2613 << OCIType->getPointeeType() << Sel << RecRange
Fariborz Jahanian32c13502012-11-28 01:27:44 +00002614 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
John McCall31168b02011-06-15 23:02:42 +00002615 return ExprError();
2616 }
2617
Douglas Gregor486b74e2011-09-27 16:10:05 +00002618 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002619 // If we still haven't found a method, look in the global pool. This
2620 // behavior isn't very desirable, however we need it for GCC
2621 // compatibility. FIXME: should we deviate??
2622 if (OCIType->qual_empty()) {
2623 Method = LookupInstanceMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002624 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002625 if (Method) {
2626 if (auto BestMethod =
2627 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
2628 Method = BestMethod;
2629 AreMultipleMethodsInGlobalPool(Sel, Method,
2630 SourceRange(LBracLoc, RBracLoc),
2631 true);
2632 }
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +00002633 if (Method && !forwardClass)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002634 Diag(SelLoc, diag::warn_maynot_respond)
2635 << OCIType->getInterfaceDecl()->getIdentifier()
2636 << Sel << RecRange;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002637 }
2638 }
2639 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002640 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002641 return ExprError();
John McCallfec112d2011-09-09 06:11:02 +00002642 } else {
John McCall80c93a02013-03-01 09:20:14 +00002643 // Reject other random receiver types (e.g. structs).
2644 Diag(Loc, diag::err_bad_receiver_type)
2645 << ReceiverType << Receiver->getSourceRange();
2646 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002647 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002648 }
Chris Lattner6b946cc2008-07-21 05:57:44 +00002649 }
Mike Stump11289f42009-09-09 15:08:12 +00002650
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002651 FunctionScopeInfo *DIFunctionScopeInfo =
2652 (Method && Method->getMethodFamily() == OMF_init)
Craig Topperc3ec1492014-05-26 06:22:03 +00002653 ? getEnclosingFunction() : nullptr;
2654
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002655 if (DIFunctionScopeInfo &&
2656 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002657 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2658 bool isDesignatedInitChain = false;
2659 if (SuperLoc.isValid()) {
2660 if (const ObjCObjectPointerType *
2661 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2662 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
Argyrios Kyrtzidisd664a342013-12-13 03:48:17 +00002663 // Either we know this is a designated initializer or we
2664 // conservatively assume it because we don't know for sure.
2665 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2666 ID->isDesignatedInitializer(Sel)) {
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002667 isDesignatedInitChain = true;
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002668 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002669 }
2670 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002671 }
2672 }
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002673 if (!isDesignatedInitChain) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002674 const ObjCMethodDecl *InitMethod = nullptr;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002675 bool isDesignated =
2676 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2677 assert(isDesignated && InitMethod);
2678 (void)isDesignated;
2679 Diag(SelLoc, SuperLoc.isValid() ?
2680 diag::warn_objc_designated_init_non_designated_init_call :
2681 diag::warn_objc_designated_init_non_super_designated_init_call);
2682 Diag(InitMethod->getLocation(),
2683 diag::note_objc_designated_init_marked_here);
2684 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002685 }
2686
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002687 if (DIFunctionScopeInfo &&
2688 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002689 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2690 if (SuperLoc.isValid()) {
2691 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2692 } else {
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002693 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002694 }
2695 }
2696
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002697 // Check the message arguments.
2698 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002699 Expr **Args = ArgsIn.data();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002700 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002701 ExprValueKind VK = VK_RValue;
Fariborz Jahanian68500912010-12-01 01:07:24 +00002702 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2703 ReceiverType->isObjCQualifiedClassType());
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002704 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2705 Sel, SelectorLocs, Method,
Douglas Gregor33823722011-06-11 01:09:30 +00002706 ClassMessage, SuperLoc.isValid(),
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00002707 LBracLoc, RBracLoc, RecRange, ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002708 return ExprError();
Alp Toker314cc812014-01-25 16:55:45 +00002709
2710 if (Method && !Method->getReturnType()->isVoidType() &&
2711 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002712 diag::err_illegal_message_expr_incomplete_type))
2713 return ExprError();
Douglas Gregor9a129192010-04-21 00:45:42 +00002714
John McCall31168b02011-06-15 23:02:42 +00002715 // In ARC, forbid the user from sending messages to
2716 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002717 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002718 ObjCMethodFamily family =
2719 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2720 switch (family) {
2721 case OMF_init:
2722 if (Method)
2723 checkInitMethod(Method, ReceiverType);
2724
2725 case OMF_None:
2726 case OMF_alloc:
2727 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00002728 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002729 case OMF_mutableCopy:
2730 case OMF_new:
2731 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002732 case OMF_initialize:
John McCall31168b02011-06-15 23:02:42 +00002733 break;
2734
2735 case OMF_dealloc:
2736 case OMF_retain:
2737 case OMF_release:
2738 case OMF_autorelease:
2739 case OMF_retainCount:
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002740 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
2741 << Sel << RecRange;
John McCall31168b02011-06-15 23:02:42 +00002742 break;
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002743
2744 case OMF_performSelector:
2745 if (Method && NumArgs >= 1) {
2746 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2747 Selector ArgSel = SelExp->getSelector();
2748 ObjCMethodDecl *SelMethod =
2749 LookupInstanceMethodInGlobalPool(ArgSel,
2750 SelExp->getSourceRange());
2751 if (!SelMethod)
2752 SelMethod =
2753 LookupFactoryMethodInGlobalPool(ArgSel,
2754 SelExp->getSourceRange());
2755 if (SelMethod) {
2756 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2757 switch (SelFamily) {
2758 case OMF_alloc:
2759 case OMF_copy:
2760 case OMF_mutableCopy:
2761 case OMF_new:
2762 case OMF_self:
2763 case OMF_init:
2764 // Issue error, unless ns_returns_not_retained.
2765 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2766 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002767 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002768 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002769 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2770 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002771 }
2772 break;
2773 default:
2774 // +0 call. OK. unless ns_returns_retained.
2775 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2776 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002777 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002778 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002779 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2780 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002781 }
2782 break;
2783 }
2784 }
2785 } else {
2786 // error (may leak).
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002787 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002788 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2789 }
2790 }
2791 break;
John McCall31168b02011-06-15 23:02:42 +00002792 }
2793 }
2794
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002795 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2796
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002797 // Construct the appropriate ObjCMessageExpr instance.
John McCall31168b02011-06-15 23:02:42 +00002798 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002799 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002800 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002801 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002802 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002803 makeArrayRef(Args, NumArgs), RBracLoc,
2804 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002805 else {
John McCall7decc9e2010-11-18 06:31:45 +00002806 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002807 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002808 makeArrayRef(Args, NumArgs), RBracLoc,
2809 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002810 if (!isImplicit)
2811 checkCocoaAPI(*this, Result);
2812 }
John McCall31168b02011-06-15 23:02:42 +00002813
David Blaikiebbafb8a2012-03-11 07:00:24 +00002814 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002815 // In ARC, annotate delegate init calls.
2816 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregor486b74e2011-09-27 16:10:05 +00002817 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCall31168b02011-06-15 23:02:42 +00002818 // Only consider init calls *directly* in init implementations,
2819 // not within blocks.
2820 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2821 if (method && method->getMethodFamily() == OMF_init) {
2822 // The implicit assignment to self means we also don't want to
2823 // consume the result.
2824 Result->setDelegateInitCall(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002825 return Result;
John McCall31168b02011-06-15 23:02:42 +00002826 }
2827 }
2828
2829 // In ARC, check for message sends which are likely to introduce
2830 // retain cycles.
2831 checkRetainCycles(Result);
Jordan Rose22487652012-10-11 16:06:21 +00002832
2833 if (!isImplicit && Method) {
2834 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
2835 bool IsWeak =
2836 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
2837 if (!IsWeak && Sel.isUnarySelector())
2838 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002839 if (IsWeak &&
2840 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
2841 getCurFunction()->recordUseOfWeak(Result, Prop);
Jordan Rose22487652012-10-11 16:06:21 +00002842 }
2843 }
John McCall31168b02011-06-15 23:02:42 +00002844 }
Alex Denisove1d882c2015-03-04 17:55:52 +00002845
2846 CheckObjCCircularContainer(Result);
2847
Douglas Gregoraae38d62010-05-22 05:17:18 +00002848 return MaybeBindToTemporary(Result);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002849}
2850
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002851static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
2852 if (ObjCSelectorExpr *OSE =
2853 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
2854 Selector Sel = OSE->getSelector();
2855 SourceLocation Loc = OSE->getAtLoc();
Chandler Carruth12c8f652015-03-27 00:55:05 +00002856 auto Pos = S.ReferencedSelectors.find(Sel);
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002857 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
2858 S.ReferencedSelectors.erase(Pos);
2859 }
2860}
2861
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002862// ActOnInstanceMessage - used for both unary and keyword messages.
2863// ArgExprs is optional - if it is present, the number of expressions
2864// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002865ExprResult Sema::ActOnInstanceMessage(Scope *S,
2866 Expr *Receiver,
2867 Selector Sel,
2868 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002869 ArrayRef<SourceLocation> SelectorLocs,
John McCalldadc5752010-08-24 06:29:42 +00002870 SourceLocation RBracLoc,
2871 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002872 if (!Receiver)
2873 return ExprError();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00002874
2875 // A ParenListExpr can show up while doing error recovery with invalid code.
2876 if (isa<ParenListExpr>(Receiver)) {
2877 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
2878 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002879 Receiver = Result.get();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00002880 }
Fariborz Jahanian17748062013-01-22 19:05:17 +00002881
2882 if (RespondsToSelectorSel.isNull()) {
2883 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
2884 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
2885 }
2886 if (Sel == RespondsToSelectorSel)
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002887 RemoveSelectorFromWarningCache(*this, Args[0]);
Craig Topperc3ec1492014-05-26 06:22:03 +00002888
John McCallb268a282010-08-23 23:25:46 +00002889 return BuildInstanceMessage(Receiver, Receiver->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002890 /*SuperLoc=*/SourceLocation(), Sel,
2891 /*Method=*/nullptr, LBracLoc, SelectorLocs,
2892 RBracLoc, Args);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002893}
Chris Lattner2a3569b2008-04-07 05:30:13 +00002894
John McCall31168b02011-06-15 23:02:42 +00002895enum ARCConversionTypeClass {
John McCalle4fe2452011-10-01 01:01:08 +00002896 /// int, void, struct A
John McCall31168b02011-06-15 23:02:42 +00002897 ACTC_none,
John McCalle4fe2452011-10-01 01:01:08 +00002898
2899 /// id, void (^)()
John McCall31168b02011-06-15 23:02:42 +00002900 ACTC_retainable,
John McCalle4fe2452011-10-01 01:01:08 +00002901
2902 /// id*, id***, void (^*)(),
2903 ACTC_indirectRetainable,
2904
2905 /// void* might be a normal C type, or it might a CF type.
2906 ACTC_voidPtr,
2907
2908 /// struct A*
2909 ACTC_coreFoundation
John McCall31168b02011-06-15 23:02:42 +00002910};
John McCalle4fe2452011-10-01 01:01:08 +00002911static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2912 return (ACTC == ACTC_retainable ||
2913 ACTC == ACTC_coreFoundation ||
2914 ACTC == ACTC_voidPtr);
2915}
2916static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2917 return ACTC == ACTC_none ||
2918 ACTC == ACTC_voidPtr ||
2919 ACTC == ACTC_coreFoundation;
2920}
2921
John McCall31168b02011-06-15 23:02:42 +00002922static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCalle4fe2452011-10-01 01:01:08 +00002923 bool isIndirect = false;
John McCall31168b02011-06-15 23:02:42 +00002924
2925 // Ignore an outermost reference type.
John McCalle4fe2452011-10-01 01:01:08 +00002926 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall31168b02011-06-15 23:02:42 +00002927 type = ref->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002928 isIndirect = true;
2929 }
John McCall31168b02011-06-15 23:02:42 +00002930
2931 // Drill through pointers and arrays recursively.
2932 while (true) {
2933 if (const PointerType *ptr = type->getAs<PointerType>()) {
2934 type = ptr->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002935
2936 // The first level of pointer may be the innermost pointer on a CF type.
2937 if (!isIndirect) {
2938 if (type->isVoidType()) return ACTC_voidPtr;
2939 if (type->isRecordType()) return ACTC_coreFoundation;
2940 }
John McCall31168b02011-06-15 23:02:42 +00002941 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2942 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2943 } else {
2944 break;
2945 }
John McCalle4fe2452011-10-01 01:01:08 +00002946 isIndirect = true;
John McCall31168b02011-06-15 23:02:42 +00002947 }
2948
John McCalle4fe2452011-10-01 01:01:08 +00002949 if (isIndirect) {
2950 if (type->isObjCARCBridgableType())
2951 return ACTC_indirectRetainable;
2952 return ACTC_none;
2953 }
2954
2955 if (type->isObjCARCBridgableType())
2956 return ACTC_retainable;
2957
2958 return ACTC_none;
John McCall31168b02011-06-15 23:02:42 +00002959}
2960
2961namespace {
John McCalle4fe2452011-10-01 01:01:08 +00002962 /// A result from the cast checker.
2963 enum ACCResult {
2964 /// Cannot be casted.
2965 ACC_invalid,
2966
2967 /// Can be safely retained or not retained.
2968 ACC_bottom,
2969
2970 /// Can be casted at +0.
2971 ACC_plusZero,
2972
2973 /// Can be casted at +1.
2974 ACC_plusOne
2975 };
2976 ACCResult merge(ACCResult left, ACCResult right) {
2977 if (left == right) return left;
2978 if (left == ACC_bottom) return right;
2979 if (right == ACC_bottom) return left;
2980 return ACC_invalid;
2981 }
2982
2983 /// A checker which white-lists certain expressions whose conversion
2984 /// to or from retainable type would otherwise be forbidden in ARC.
2985 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2986 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2987
John McCall31168b02011-06-15 23:02:42 +00002988 ASTContext &Context;
John McCalle4fe2452011-10-01 01:01:08 +00002989 ARCConversionTypeClass SourceClass;
2990 ARCConversionTypeClass TargetClass;
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002991 bool Diagnose;
John McCalle4fe2452011-10-01 01:01:08 +00002992
2993 static bool isCFType(QualType type) {
2994 // Someday this can use ns_bridged. For now, it has to do this.
2995 return type->isCARCBridgableType();
John McCall31168b02011-06-15 23:02:42 +00002996 }
John McCalle4fe2452011-10-01 01:01:08 +00002997
2998 public:
2999 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003000 ARCConversionTypeClass target, bool diagnose)
3001 : Context(Context), SourceClass(source), TargetClass(target),
3002 Diagnose(diagnose) {}
John McCalle4fe2452011-10-01 01:01:08 +00003003
3004 using super::Visit;
3005 ACCResult Visit(Expr *e) {
3006 return super::Visit(e->IgnoreParens());
3007 }
3008
3009 ACCResult VisitStmt(Stmt *s) {
3010 return ACC_invalid;
3011 }
3012
3013 /// Null pointer constants can be casted however you please.
3014 ACCResult VisitExpr(Expr *e) {
3015 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
3016 return ACC_bottom;
3017 return ACC_invalid;
3018 }
3019
3020 /// Objective-C string literals can be safely casted.
3021 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
3022 // If we're casting to any retainable type, go ahead. Global
3023 // strings are immune to retains, so this is bottom.
3024 if (isAnyRetainable(TargetClass)) return ACC_bottom;
3025
3026 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00003027 }
3028
John McCalle4fe2452011-10-01 01:01:08 +00003029 /// Look through certain implicit and explicit casts.
3030 ACCResult VisitCastExpr(CastExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00003031 switch (e->getCastKind()) {
3032 case CK_NullToPointer:
John McCalle4fe2452011-10-01 01:01:08 +00003033 return ACC_bottom;
3034
John McCall31168b02011-06-15 23:02:42 +00003035 case CK_NoOp:
3036 case CK_LValueToRValue:
3037 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00003038 case CK_CPointerToObjCPointerCast:
3039 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00003040 case CK_AnyPointerToBlockPointerCast:
3041 return Visit(e->getSubExpr());
John McCalle4fe2452011-10-01 01:01:08 +00003042
John McCall31168b02011-06-15 23:02:42 +00003043 default:
John McCalle4fe2452011-10-01 01:01:08 +00003044 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00003045 }
3046 }
John McCalle4fe2452011-10-01 01:01:08 +00003047
3048 /// Look through unary extension.
3049 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00003050 return Visit(e->getSubExpr());
3051 }
John McCalle4fe2452011-10-01 01:01:08 +00003052
3053 /// Ignore the LHS of a comma operator.
3054 ACCResult VisitBinComma(BinaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00003055 return Visit(e->getRHS());
3056 }
John McCalle4fe2452011-10-01 01:01:08 +00003057
3058 /// Conditional operators are okay if both sides are okay.
3059 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
3060 ACCResult left = Visit(e->getTrueExpr());
3061 if (left == ACC_invalid) return ACC_invalid;
3062 return merge(left, Visit(e->getFalseExpr()));
John McCall31168b02011-06-15 23:02:42 +00003063 }
John McCalle4fe2452011-10-01 01:01:08 +00003064
John McCallfe96e0b2011-11-06 09:01:30 +00003065 /// Look through pseudo-objects.
3066 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
3067 // If we're getting here, we should always have a result.
3068 return Visit(e->getResultExpr());
3069 }
3070
John McCalle4fe2452011-10-01 01:01:08 +00003071 /// Statement expressions are okay if their result expression is okay.
3072 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00003073 return Visit(e->getSubStmt()->body_back());
3074 }
John McCall31168b02011-06-15 23:02:42 +00003075
John McCalle4fe2452011-10-01 01:01:08 +00003076 /// Some declaration references are okay.
3077 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
John McCalle4fe2452011-10-01 01:01:08 +00003078 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
Ben Langmuir443aa4b2015-02-25 20:09:06 +00003079 // References to global constants are okay.
John McCalle4fe2452011-10-01 01:01:08 +00003080 if (isAnyRetainable(TargetClass) &&
3081 isAnyRetainable(SourceClass) &&
3082 var &&
3083 var->getStorageClass() == SC_Extern &&
Ben Langmuir443aa4b2015-02-25 20:09:06 +00003084 var->getType().isConstQualified()) {
3085
3086 // In system headers, they can also be assumed to be immune to retains.
3087 // These are things like 'kCFStringTransformToLatin'.
3088 if (Context.getSourceManager().isInSystemHeader(var->getLocation()))
3089 return ACC_bottom;
3090
3091 return ACC_plusZero;
John McCalle4fe2452011-10-01 01:01:08 +00003092 }
3093
3094 // Nothing else.
3095 return ACC_invalid;
Fariborz Jahanian78876372011-06-21 17:38:29 +00003096 }
John McCalle4fe2452011-10-01 01:01:08 +00003097
3098 /// Some calls are okay.
3099 ACCResult VisitCallExpr(CallExpr *e) {
3100 if (FunctionDecl *fn = e->getDirectCallee())
3101 if (ACCResult result = checkCallToFunction(fn))
3102 return result;
3103
3104 return super::VisitCallExpr(e);
3105 }
3106
3107 ACCResult checkCallToFunction(FunctionDecl *fn) {
3108 // Require a CF*Ref return type.
Alp Toker314cc812014-01-25 16:55:45 +00003109 if (!isCFType(fn->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003110 return ACC_invalid;
3111
3112 if (!isAnyRetainable(TargetClass))
3113 return ACC_invalid;
3114
3115 // Honor an explicit 'not retained' attribute.
3116 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3117 return ACC_plusZero;
3118
3119 // Honor an explicit 'retained' attribute, except that for
3120 // now we're not going to permit implicit handling of +1 results,
3121 // because it's a bit frightening.
3122 if (fn->hasAttr<CFReturnsRetainedAttr>())
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003123 return Diagnose ? ACC_plusOne
3124 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003125
3126 // Recognize this specific builtin function, which is used by CFSTR.
3127 unsigned builtinID = fn->getBuiltinID();
3128 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3129 return ACC_bottom;
3130
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003131 // Otherwise, don't do anything implicit with an unaudited function.
3132 if (!fn->hasAttr<CFAuditedTransferAttr>())
3133 return ACC_invalid;
3134
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003135 // Otherwise, it's +0 unless it follows the create convention.
3136 if (ento::coreFoundation::followsCreateRule(fn))
3137 return Diagnose ? ACC_plusOne
3138 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003139
John McCalle4fe2452011-10-01 01:01:08 +00003140 return ACC_plusZero;
3141 }
3142
3143 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3144 return checkCallToMethod(e->getMethodDecl());
3145 }
3146
3147 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3148 ObjCMethodDecl *method;
3149 if (e->isExplicitProperty())
3150 method = e->getExplicitProperty()->getGetterMethodDecl();
3151 else
3152 method = e->getImplicitPropertyGetter();
3153 return checkCallToMethod(method);
3154 }
3155
3156 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3157 if (!method) return ACC_invalid;
3158
3159 // Check for message sends to functions returning CF types. We
3160 // just obey the Cocoa conventions with these, even though the
3161 // return type is CF.
Alp Toker314cc812014-01-25 16:55:45 +00003162 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003163 return ACC_invalid;
3164
3165 // If the method is explicitly marked not-retained, it's +0.
3166 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3167 return ACC_plusZero;
3168
3169 // If the method is explicitly marked as returning retained, or its
3170 // selector follows a +1 Cocoa convention, treat it as +1.
3171 if (method->hasAttr<CFReturnsRetainedAttr>())
3172 return ACC_plusOne;
3173
3174 switch (method->getSelector().getMethodFamily()) {
3175 case OMF_alloc:
3176 case OMF_copy:
3177 case OMF_mutableCopy:
3178 case OMF_new:
3179 return ACC_plusOne;
3180
3181 default:
3182 // Otherwise, treat it as +0.
3183 return ACC_plusZero;
Fariborz Jahanian9b83be82011-06-21 19:42:38 +00003184 }
3185 }
John McCalle4fe2452011-10-01 01:01:08 +00003186 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003187}
Fariborz Jahanian4ad56862011-06-20 20:54:42 +00003188
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003189bool Sema::isKnownName(StringRef name) {
3190 if (name.empty())
3191 return false;
3192 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003193 Sema::LookupOrdinaryName);
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003194 return LookupName(R, TUScope, false);
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003195}
3196
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003197static void addFixitForObjCARCConversion(Sema &S,
3198 DiagnosticBuilder &DiagB,
3199 Sema::CheckedConversionKind CCK,
3200 SourceLocation afterLParen,
3201 QualType castType,
3202 Expr *castExpr,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003203 Expr *realCast,
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003204 const char *bridgeKeyword,
3205 const char *CFBridgeName) {
3206 // We handle C-style and implicit casts here.
3207 switch (CCK) {
3208 case Sema::CCK_ImplicitConversion:
3209 case Sema::CCK_CStyleCast:
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003210 case Sema::CCK_OtherCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003211 break;
3212 case Sema::CCK_FunctionalCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003213 return;
3214 }
3215
3216 if (CFBridgeName) {
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003217 if (CCK == Sema::CCK_OtherCast) {
3218 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3219 SourceRange range(NCE->getOperatorLoc(),
3220 NCE->getAngleBrackets().getEnd());
3221 SmallString<32> BridgeCall;
3222
3223 SourceManager &SM = S.getSourceManager();
3224 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3225 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3226 BridgeCall += ' ';
3227
3228 BridgeCall += CFBridgeName;
3229 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3230 }
3231 return;
3232 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003233 Expr *castedE = castExpr;
3234 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3235 castedE = CCE->getSubExpr();
3236 castedE = castedE->IgnoreImpCasts();
3237 SourceRange range = castedE->getSourceRange();
Jordan Rose288c4212012-06-07 01:10:31 +00003238
3239 SmallString<32> BridgeCall;
3240
3241 SourceManager &SM = S.getSourceManager();
3242 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3243 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3244 BridgeCall += ' ';
3245
3246 BridgeCall += CFBridgeName;
3247
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003248 if (isa<ParenExpr>(castedE)) {
3249 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003250 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003251 } else {
Jordan Rose288c4212012-06-07 01:10:31 +00003252 BridgeCall += '(';
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003253 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003254 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003255 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3256 S.PP.getLocForEndOfToken(range.getEnd()),
3257 ")"));
3258 }
3259 return;
3260 }
3261
3262 if (CCK == Sema::CCK_CStyleCast) {
3263 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003264 } else if (CCK == Sema::CCK_OtherCast) {
3265 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3266 std::string castCode = "(";
3267 castCode += bridgeKeyword;
3268 castCode += castType.getAsString();
3269 castCode += ")";
3270 SourceRange Range(NCE->getOperatorLoc(),
3271 NCE->getAngleBrackets().getEnd());
3272 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3273 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003274 } else {
3275 std::string castCode = "(";
3276 castCode += bridgeKeyword;
3277 castCode += castType.getAsString();
3278 castCode += ")";
3279 Expr *castedE = castExpr->IgnoreImpCasts();
3280 SourceRange range = castedE->getSourceRange();
3281 if (isa<ParenExpr>(castedE)) {
3282 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3283 castCode));
3284 } else {
3285 castCode += "(";
3286 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3287 castCode));
3288 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3289 S.PP.getLocForEndOfToken(range.getEnd()),
3290 ")"));
3291 }
3292 }
3293}
3294
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003295template <typename T>
3296static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3297 TypedefNameDecl *TDNDecl = TD->getDecl();
3298 QualType QT = TDNDecl->getUnderlyingType();
3299 if (QT->isPointerType()) {
3300 QT = QT->getPointeeType();
3301 if (const RecordType *RT = QT->getAs<RecordType>())
Fariborz Jahanian9af6a782014-06-11 19:10:46 +00003302 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
Aaron Ballman2084f8f2013-12-19 13:20:36 +00003303 return RD->getAttr<T>();
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003304 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003305 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003306}
3307
3308static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3309 TypedefNameDecl *&TDNDecl) {
3310 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3311 TDNDecl = TD->getDecl();
3312 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3313 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3314 return ObjCBAttr;
3315 T = TDNDecl->getUnderlyingType();
3316 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003317 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003318}
3319
John McCall4124c492011-10-17 18:40:02 +00003320static void
3321diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3322 QualType castType, ARCConversionTypeClass castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003323 Expr *castExpr, Expr *realCast,
3324 ARCConversionTypeClass exprACTC,
John McCall4124c492011-10-17 18:40:02 +00003325 Sema::CheckedConversionKind CCK) {
John McCall31168b02011-06-15 23:02:42 +00003326 SourceLocation loc =
John McCalle4fe2452011-10-01 01:01:08 +00003327 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCall31168b02011-06-15 23:02:42 +00003328
John McCall4124c492011-10-17 18:40:02 +00003329 if (S.makeUnavailableInSystemHeader(loc,
John McCalle4fe2452011-10-01 01:01:08 +00003330 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCall31168b02011-06-15 23:02:42 +00003331 return;
John McCall4124c492011-10-17 18:40:02 +00003332
3333 QualType castExprType = castExpr->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00003334 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003335 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3336 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3337 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
Fariborz Jahanian1ad83a32014-06-18 23:22:38 +00003338 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003339 return;
John McCall31168b02011-06-15 23:02:42 +00003340
John McCall640767f2011-06-17 06:50:50 +00003341 unsigned srcKind = 0;
John McCall31168b02011-06-15 23:02:42 +00003342 switch (exprACTC) {
John McCalle4fe2452011-10-01 01:01:08 +00003343 case ACTC_none:
3344 case ACTC_coreFoundation:
3345 case ACTC_voidPtr:
3346 srcKind = (castExprType->isPointerType() ? 1 : 0);
3347 break;
3348 case ACTC_retainable:
3349 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3350 break;
3351 case ACTC_indirectRetainable:
3352 srcKind = 4;
3353 break;
John McCall31168b02011-06-15 23:02:42 +00003354 }
3355
John McCall4124c492011-10-17 18:40:02 +00003356 // Check whether this could be fixed with a bridge cast.
3357 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
3358 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCall31168b02011-06-15 23:02:42 +00003359
John McCall4124c492011-10-17 18:40:02 +00003360 // Bridge from an ARC type to a CF type.
3361 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003362
John McCall4124c492011-10-17 18:40:02 +00003363 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3364 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3365 << 2 // of C pointer type
3366 << castExprType
3367 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3368 << castType
3369 << castRange
3370 << castExpr->getSourceRange();
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003371 bool br = S.isKnownName("CFBridgingRelease");
Jordan Rose4502b532012-07-31 01:07:43 +00003372 ACCResult CreateRule =
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003373 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003374 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003375 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003376 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003377 DiagnosticBuilder DiagB =
3378 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3379 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Craig Topperc3ec1492014-05-26 06:22:03 +00003380
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003381 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003382 castType, castExpr, realCast, "__bridge ",
3383 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003384 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003385 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003386 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003387 DiagnosticBuilder DiagB =
3388 (CCK == Sema::CCK_OtherCast && !br) ?
3389 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3390 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3391 diag::note_arc_bridge_transfer)
3392 << castExprType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003393
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003394 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003395 castType, castExpr, realCast, "__bridge_transfer ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003396 br ? "CFBridgingRelease" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003397 }
John McCall4124c492011-10-17 18:40:02 +00003398
3399 return;
3400 }
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003401
John McCall4124c492011-10-17 18:40:02 +00003402 // Bridge from a CF type to an ARC type.
3403 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003404 bool br = S.isKnownName("CFBridgingRetain");
John McCall4124c492011-10-17 18:40:02 +00003405 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3406 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3407 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3408 << castExprType
3409 << 2 // to C pointer type
3410 << castType
3411 << castRange
3412 << castExpr->getSourceRange();
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003413 ACCResult CreateRule =
3414 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003415 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003416 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003417 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003418 DiagnosticBuilder DiagB =
3419 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3420 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003421 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003422 castType, castExpr, realCast, "__bridge ",
3423 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003424 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003425 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003426 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003427 DiagnosticBuilder DiagB =
3428 (CCK == Sema::CCK_OtherCast && !br) ?
3429 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3430 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3431 diag::note_arc_bridge_retained)
3432 << castType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003433
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003434 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003435 castType, castExpr, realCast, "__bridge_retained ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003436 br ? "CFBridgingRetain" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003437 }
John McCall4124c492011-10-17 18:40:02 +00003438
3439 return;
John McCall31168b02011-06-15 23:02:42 +00003440 }
3441
John McCall4124c492011-10-17 18:40:02 +00003442 S.Diag(loc, diag::err_arc_mismatched_cast)
3443 << (CCK != Sema::CCK_ImplicitConversion)
3444 << srcKind << castExprType << castType
John McCall31168b02011-06-15 23:02:42 +00003445 << castRange << castExpr->getSourceRange();
3446}
3447
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003448template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003449static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3450 bool &HadTheAttribute, bool warn) {
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003451 QualType T = castExpr->getType();
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003452 HadTheAttribute = false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003453 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3454 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003455 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003456 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003457 HadTheAttribute = true;
Fariborz Jahanianc9e266b2014-12-11 22:56:26 +00003458 if (Parm->isStr("id"))
3459 return true;
3460
Craig Topperc3ec1492014-05-26 06:22:03 +00003461 NamedDecl *Target = nullptr;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003462 // Check for an existing type with this name.
3463 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3464 Sema::LookupOrdinaryName);
3465 if (S.LookupName(R, S.TUScope)) {
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003466 Target = R.getFoundDecl();
3467 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3468 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3469 if (const ObjCObjectPointerType *InterfacePointerType =
3470 castType->getAsObjCInterfacePointerType()) {
3471 ObjCInterfaceDecl *CastClass
3472 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003473 if ((CastClass == ExprClass) ||
Fariborz Jahanian27aa9b42015-04-10 22:07:47 +00003474 (CastClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003475 return true;
3476 if (warn)
3477 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3478 << T << Target->getName() << castType->getPointeeType();
3479 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003480 } else if (castType->isObjCIdType() ||
3481 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3482 castType, ExprClass)))
3483 // ok to cast to 'id'.
3484 // casting to id<p-list> is ok if bridge type adopts all of
3485 // p-list protocols.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003486 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003487 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003488 if (warn) {
3489 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3490 << T << Target->getName() << castType;
3491 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3492 S.Diag(Target->getLocStart(), diag::note_declared_at);
3493 }
3494 return false;
Fariborz Jahanian2c312122013-11-16 23:22:37 +00003495 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003496 }
Fariborz Jahanian696c8872015-04-09 23:39:53 +00003497 } else if (!castType->isObjCIdType()) {
3498 S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface)
3499 << castExpr->getType() << Parm;
3500 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3501 if (Target)
3502 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003503 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003504 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003505 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003506 return false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003507 }
3508 T = TDNDecl->getUnderlyingType();
3509 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003510 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003511}
3512
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003513template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003514static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
3515 bool &HadTheAttribute, bool warn) {
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003516 QualType T = castType;
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003517 HadTheAttribute = false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003518 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3519 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003520 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003521 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003522 HadTheAttribute = true;
John McCallaf6b3f82015-03-10 18:41:23 +00003523 if (Parm->isStr("id"))
3524 return true;
3525
Craig Topperc3ec1492014-05-26 06:22:03 +00003526 NamedDecl *Target = nullptr;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003527 // Check for an existing type with this name.
3528 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3529 Sema::LookupOrdinaryName);
3530 if (S.LookupName(R, S.TUScope)) {
3531 Target = R.getFoundDecl();
3532 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3533 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3534 if (const ObjCObjectPointerType *InterfacePointerType =
3535 castExpr->getType()->getAsObjCInterfacePointerType()) {
3536 ObjCInterfaceDecl *ExprClass
3537 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003538 if ((CastClass == ExprClass) ||
3539 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003540 return true;
3541 if (warn) {
3542 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3543 << castExpr->getType()->getPointeeType() << T;
3544 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3545 }
3546 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003547 } else if (castExpr->getType()->isObjCIdType() ||
3548 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3549 castExpr->getType(), CastClass)))
3550 // ok to cast an 'id' expression to a CFtype.
3551 // ok to cast an 'id<plist>' expression to CFtype provided plist
3552 // adopts all of CFtype's ObjetiveC's class plist.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003553 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003554 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003555 if (warn) {
3556 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3557 << castExpr->getType() << castType;
3558 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3559 S.Diag(Target->getLocStart(), diag::note_declared_at);
3560 }
3561 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003562 }
3563 }
3564 }
3565 S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject)
3566 << castExpr->getType() << castType;
3567 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3568 if (Target)
3569 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003570 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003571 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003572 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003573 }
3574 T = TDNDecl->getUnderlyingType();
3575 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003576 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003577}
3578
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003579void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003580 if (!getLangOpts().ObjC1)
3581 return;
Alp Tokerf6a24ce2013-12-05 16:25:25 +00003582 // warn in presence of __bridge casting to or from a toll free bridge cast.
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003583 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3584 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003585 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003586 bool HasObjCBridgeAttr;
3587 bool ObjCBridgeAttrWillNotWarn =
3588 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3589 false);
3590 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3591 return;
3592 bool HasObjCBridgeMutableAttr;
3593 bool ObjCBridgeMutableAttrWillNotWarn =
3594 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3595 HasObjCBridgeMutableAttr, false);
3596 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3597 return;
3598
3599 if (HasObjCBridgeAttr)
3600 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3601 true);
3602 else if (HasObjCBridgeMutableAttr)
3603 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3604 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003605 }
3606 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003607 bool HasObjCBridgeAttr;
3608 bool ObjCBridgeAttrWillNotWarn =
3609 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3610 false);
3611 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3612 return;
3613 bool HasObjCBridgeMutableAttr;
3614 bool ObjCBridgeMutableAttrWillNotWarn =
3615 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3616 HasObjCBridgeMutableAttr, false);
3617 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3618 return;
3619
3620 if (HasObjCBridgeAttr)
3621 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3622 true);
3623 else if (HasObjCBridgeMutableAttr)
3624 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3625 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003626 }
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003627}
3628
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003629void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
3630 QualType SrcType = castExpr->getType();
3631 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
3632 if (PRE->isExplicitProperty()) {
3633 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
3634 SrcType = PDecl->getType();
3635 }
3636 else if (PRE->isImplicitProperty()) {
3637 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
3638 SrcType = Getter->getReturnType();
3639
3640 }
3641 }
3642
3643 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
3644 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
3645 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
3646 return;
3647 CheckObjCBridgeRelatedConversions(castExpr->getLocStart(),
3648 castType, SrcType, castExpr);
3649 return;
3650}
3651
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00003652bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
3653 CastKind &Kind) {
3654 if (!getLangOpts().ObjC1)
3655 return false;
3656 ARCConversionTypeClass exprACTC =
3657 classifyTypeForARCConversion(castExpr->getType());
3658 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3659 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
3660 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
3661 CheckTollFreeBridgeCast(castType, castExpr);
3662 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
3663 : CK_CPointerToObjCPointerCast;
3664 return true;
3665 }
3666 return false;
3667}
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003668
3669bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
3670 QualType DestType, QualType SrcType,
3671 ObjCInterfaceDecl *&RelatedClass,
3672 ObjCMethodDecl *&ClassMethod,
3673 ObjCMethodDecl *&InstanceMethod,
3674 TypedefNameDecl *&TDNDecl,
3675 bool CfToNs) {
3676 QualType T = CfToNs ? SrcType : DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003677 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
3678 if (!ObjCBAttr)
3679 return false;
3680
3681 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
3682 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
3683 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
3684 if (!RCId)
3685 return false;
Craig Topperc3ec1492014-05-26 06:22:03 +00003686 NamedDecl *Target = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003687 // Check for an existing type with this name.
3688 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
3689 Sema::LookupOrdinaryName);
3690 if (!LookupName(R, TUScope)) {
3691 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003692 << SrcType << DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003693 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3694 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003695 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003696 Target = R.getFoundDecl();
3697 if (Target && isa<ObjCInterfaceDecl>(Target))
3698 RelatedClass = cast<ObjCInterfaceDecl>(Target);
3699 else {
3700 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
3701 << SrcType << DestType;
3702 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3703 if (Target)
3704 Diag(Target->getLocStart(), diag::note_declared_at);
3705 return false;
3706 }
3707
3708 // Check for an existing class method with the given selector name.
3709 if (CfToNs && CMId) {
3710 Selector Sel = Context.Selectors.getUnarySelector(CMId);
3711 ClassMethod = RelatedClass->lookupMethod(Sel, false);
3712 if (!ClassMethod) {
3713 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003714 << SrcType << DestType << Sel << false;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003715 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3716 return false;
3717 }
3718 }
3719
3720 // Check for an existing instance method with the given selector name.
3721 if (!CfToNs && IMId) {
3722 Selector Sel = Context.Selectors.getNullarySelector(IMId);
3723 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
3724 if (!InstanceMethod) {
3725 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003726 << SrcType << DestType << Sel << true;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003727 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3728 return false;
3729 }
3730 }
3731 return true;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003732}
3733
3734bool
3735Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003736 QualType DestType, QualType SrcType,
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003737 Expr *&SrcExpr) {
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003738 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
3739 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
3740 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
3741 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
3742 if (!CfToNs && !NsToCf)
3743 return false;
3744
3745 ObjCInterfaceDecl *RelatedClass;
Craig Topperc3ec1492014-05-26 06:22:03 +00003746 ObjCMethodDecl *ClassMethod = nullptr;
3747 ObjCMethodDecl *InstanceMethod = nullptr;
3748 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003749 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
3750 ClassMethod, InstanceMethod, TDNDecl, CfToNs))
3751 return false;
3752
3753 if (CfToNs) {
3754 // Implicit conversion from CF to ObjC object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003755 if (ClassMethod) {
3756 std::string ExpressionString = "[";
3757 ExpressionString += RelatedClass->getNameAsString();
3758 ExpressionString += " ";
3759 ExpressionString += ClassMethod->getSelector().getAsString();
3760 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
3761 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003762 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003763 << SrcType << DestType << ClassMethod->getSelector() << false
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003764 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString)
3765 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003766 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3767 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3768
3769 QualType receiverType =
3770 Context.getObjCInterfaceType(RelatedClass);
3771 // Argument.
3772 Expr *args[] = { SrcExpr };
3773 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
3774 ClassMethod->getLocation(),
3775 ClassMethod->getSelector(), ClassMethod,
3776 MultiExprArg(args, 1));
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003777 SrcExpr = msg.get();
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003778 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003779 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003780 }
3781 else {
3782 // Implicit conversion from ObjC type to CF object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003783 if (InstanceMethod) {
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003784 std::string ExpressionString;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003785 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003786 if (InstanceMethod->isPropertyAccessor())
3787 if (const ObjCPropertyDecl *PDecl = InstanceMethod->findPropertyDecl()) {
3788 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
3789 ExpressionString = ".";
3790 ExpressionString += PDecl->getNameAsString();
3791 Diag(Loc, diag::err_objc_bridged_related_known_method)
3792 << SrcType << DestType << InstanceMethod->getSelector() << true
3793 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3794 }
3795 if (ExpressionString.empty()) {
3796 // Provide a fixit: [ObjectExpr InstanceMethod]
3797 ExpressionString = " ";
3798 ExpressionString += InstanceMethod->getSelector().getAsString();
3799 ExpressionString += "]";
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003800
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003801 Diag(Loc, diag::err_objc_bridged_related_known_method)
3802 << SrcType << DestType << InstanceMethod->getSelector() << true
3803 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[")
3804 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3805 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003806 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3807 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3808
3809 ExprResult msg =
3810 BuildInstanceMessageImplicit(SrcExpr, SrcType,
3811 InstanceMethod->getLocation(),
3812 InstanceMethod->getSelector(),
3813 InstanceMethod, None);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003814 SrcExpr = msg.get();
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003815 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003816 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003817 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003818 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003819}
3820
John McCall4124c492011-10-17 18:40:02 +00003821Sema::ARCConversionResult
3822Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003823 Expr *&castExpr, CheckedConversionKind CCK,
Fariborz Jahanianc03ef572014-06-18 23:52:49 +00003824 bool DiagnoseCFAudited,
3825 BinaryOperatorKind Opc) {
John McCall4124c492011-10-17 18:40:02 +00003826 QualType castExprType = castExpr->getType();
3827
3828 // For the purposes of the classification, we assume reference types
3829 // will bind to temporaries.
3830 QualType effCastType = castType;
3831 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
3832 effCastType = ref->getPointeeType();
3833
3834 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
3835 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003836 if (exprACTC == castACTC) {
3837 // check for viablity and report error if casting an rvalue to a
3838 // life-time qualifier.
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003839 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003840 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003841 (castType != castExprType)) {
3842 const Type *DT = castType.getTypePtr();
3843 QualType QDT = castType;
3844 // We desugar some types but not others. We ignore those
3845 // that cannot happen in a cast; i.e. auto, and those which
3846 // should not be de-sugared; i.e typedef.
3847 if (const ParenType *PT = dyn_cast<ParenType>(DT))
3848 QDT = PT->desugar();
3849 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
3850 QDT = TP->desugar();
3851 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
3852 QDT = AT->desugar();
3853 if (QDT != castType &&
3854 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
3855 SourceLocation loc =
3856 (castRange.isValid() ? castRange.getBegin()
3857 : castExpr->getExprLoc());
3858 Diag(loc, diag::err_arc_nolifetime_behavior);
3859 }
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003860 }
3861 return ACR_okay;
3862 }
3863
John McCall4124c492011-10-17 18:40:02 +00003864 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
3865
3866 // Allow all of these types to be cast to integer types (but not
3867 // vice-versa).
3868 if (castACTC == ACTC_none && castType->isIntegralType(Context))
3869 return ACR_okay;
3870
3871 // Allow casts between pointers to lifetime types (e.g., __strong id*)
3872 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
3873 // must be explicit.
3874 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
3875 return ACR_okay;
3876 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
3877 CCK != CCK_ImplicitConversion)
3878 return ACR_okay;
3879
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003880 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
John McCall4124c492011-10-17 18:40:02 +00003881 // For invalid casts, fall through.
3882 case ACC_invalid:
3883 break;
3884
3885 // Do nothing for both bottom and +0.
3886 case ACC_bottom:
3887 case ACC_plusZero:
3888 return ACR_okay;
3889
3890 // If the result is +1, consume it here.
3891 case ACC_plusOne:
3892 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
3893 CK_ARCConsumeObject, castExpr,
Craig Topperc3ec1492014-05-26 06:22:03 +00003894 nullptr, VK_RValue);
John McCall4124c492011-10-17 18:40:02 +00003895 ExprNeedsCleanups = true;
3896 return ACR_okay;
3897 }
3898
3899 // If this is a non-implicit cast from id or block type to a
3900 // CoreFoundation type, delay complaining in case the cast is used
3901 // in an acceptable context.
3902 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
3903 CCK != CCK_ImplicitConversion)
3904 return ACR_unbridged;
3905
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00003906 // Do not issue bridge cast" diagnostic when implicit casting a cstring
3907 // to 'NSString *'. Let caller issue a normal mismatched diagnostic with
3908 // suitable fix-it.
Fariborz Jahanian283bf892013-12-18 21:04:43 +00003909 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
3910 ConversionToObjCStringLiteralCheck(castType, castExpr))
3911 return ACR_okay;
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00003912
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003913 // Do not issue "bridge cast" diagnostic when implicit casting
3914 // a retainable object to a CF type parameter belonging to an audited
3915 // CF API function. Let caller issue a normal type mismatched diagnostic
3916 // instead.
3917 if (!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
3918 castACTC != ACTC_coreFoundation)
Fariborz Jahanianc03ef572014-06-18 23:52:49 +00003919 if (!(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
3920 (Opc == BO_NE || Opc == BO_EQ)))
3921 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3922 castExpr, castExpr, exprACTC, CCK);
John McCall4124c492011-10-17 18:40:02 +00003923 return ACR_okay;
3924}
3925
3926/// Given that we saw an expression with the ARCUnbridgedCastTy
3927/// placeholder type, complain bitterly.
3928void Sema::diagnoseARCUnbridgedCast(Expr *e) {
3929 // We expect the spurious ImplicitCastExpr to already have been stripped.
3930 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3931 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
3932
3933 SourceRange castRange;
3934 QualType castType;
3935 CheckedConversionKind CCK;
3936
3937 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
3938 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
3939 castType = cast->getTypeAsWritten();
3940 CCK = CCK_CStyleCast;
3941 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
3942 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
3943 castType = cast->getTypeAsWritten();
3944 CCK = CCK_OtherCast;
3945 } else {
3946 castType = cast->getType();
3947 CCK = CCK_ImplicitConversion;
3948 }
3949
3950 ARCConversionTypeClass castACTC =
3951 classifyTypeForARCConversion(castType.getNonReferenceType());
3952
3953 Expr *castExpr = realCast->getSubExpr();
3954 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
3955
3956 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003957 castExpr, realCast, ACTC_retainable, CCK);
John McCall4124c492011-10-17 18:40:02 +00003958}
3959
3960/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
3961/// type, remove the placeholder cast.
3962Expr *Sema::stripARCUnbridgedCast(Expr *e) {
3963 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3964
3965 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
3966 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
3967 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
3968 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
3969 assert(uo->getOpcode() == UO_Extension);
3970 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
3971 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
3972 sub->getValueKind(), sub->getObjectKind(),
3973 uo->getOperatorLoc());
3974 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
3975 assert(!gse->isResultDependent());
3976
3977 unsigned n = gse->getNumAssocs();
3978 SmallVector<Expr*, 4> subExprs(n);
3979 SmallVector<TypeSourceInfo*, 4> subTypes(n);
3980 for (unsigned i = 0; i != n; ++i) {
3981 subTypes[i] = gse->getAssocTypeSourceInfo(i);
3982 Expr *sub = gse->getAssocExpr(i);
3983 if (i == gse->getResultIndex())
3984 sub = stripARCUnbridgedCast(sub);
3985 subExprs[i] = sub;
3986 }
3987
3988 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
3989 gse->getControllingExpr(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003990 subTypes, subExprs,
3991 gse->getDefaultLoc(),
John McCall4124c492011-10-17 18:40:02 +00003992 gse->getRParenLoc(),
3993 gse->containsUnexpandedParameterPack(),
3994 gse->getResultIndex());
3995 } else {
3996 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
3997 return cast<ImplicitCastExpr>(e)->getSubExpr();
3998 }
3999}
4000
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004001bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
4002 QualType exprType) {
4003 QualType canCastType =
4004 Context.getCanonicalType(castType).getUnqualifiedType();
4005 QualType canExprType =
4006 Context.getCanonicalType(exprType).getUnqualifiedType();
4007 if (isa<ObjCObjectPointerType>(canCastType) &&
4008 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
4009 canExprType->isObjCObjectPointerType()) {
4010 if (const ObjCObjectPointerType *ObjT =
4011 canExprType->getAs<ObjCObjectPointerType>())
Richard Smith802c4b72012-08-23 06:16:52 +00004012 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
4013 return !ObjI->isArcWeakrefUnavailable();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004014 }
4015 return true;
4016}
4017
John McCall4db5c3c2011-07-07 06:58:02 +00004018/// Look for an ObjCReclaimReturnedObject cast and destroy it.
4019static Expr *maybeUndoReclaimObject(Expr *e) {
4020 // For now, we just undo operands that are *immediately* reclaim
4021 // expressions, which prevents the vast majority of potential
4022 // problems here. To catch them all, we'd need to rebuild arbitrary
4023 // value-propagating subexpressions --- we can't reliably rebuild
4024 // in-place because of expression sharing.
4025 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall2d637d22011-09-10 06:18:15 +00004026 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall4db5c3c2011-07-07 06:58:02 +00004027 return ice->getSubExpr();
4028
4029 return e;
4030}
4031
John McCall31168b02011-06-15 23:02:42 +00004032ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
4033 ObjCBridgeCastKind Kind,
4034 SourceLocation BridgeKeywordLoc,
4035 TypeSourceInfo *TSInfo,
4036 Expr *SubExpr) {
John McCalleb075542011-08-26 00:48:42 +00004037 ExprResult SubResult = UsualUnaryConversions(SubExpr);
4038 if (SubResult.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004039 SubExpr = SubResult.get();
John McCalleb075542011-08-26 00:48:42 +00004040
John McCall31168b02011-06-15 23:02:42 +00004041 QualType T = TSInfo->getType();
4042 QualType FromType = SubExpr->getType();
4043
John McCall9320b872011-09-09 05:25:32 +00004044 CastKind CK;
4045
John McCall31168b02011-06-15 23:02:42 +00004046 bool MustConsume = false;
4047 if (T->isDependentType() || SubExpr->isTypeDependent()) {
4048 // Okay: we'll build a dependent expression type.
John McCall9320b872011-09-09 05:25:32 +00004049 CK = CK_Dependent;
John McCall31168b02011-06-15 23:02:42 +00004050 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
4051 // Casting CF -> id
John McCall9320b872011-09-09 05:25:32 +00004052 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
4053 : CK_CPointerToObjCPointerCast);
John McCall31168b02011-06-15 23:02:42 +00004054 switch (Kind) {
4055 case OBC_Bridge:
4056 break;
4057
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004058 case OBC_BridgeRetained: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00004059 bool br = isKnownName("CFBridgingRelease");
John McCall31168b02011-06-15 23:02:42 +00004060 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4061 << 2
4062 << FromType
4063 << (T->isBlockPointerType()? 1 : 0)
4064 << T
4065 << SubExpr->getSourceRange()
4066 << Kind;
4067 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4068 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
4069 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004070 << FromType << br
John McCall31168b02011-06-15 23:02:42 +00004071 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004072 br ? "CFBridgingRelease "
4073 : "__bridge_transfer ");
John McCall31168b02011-06-15 23:02:42 +00004074
4075 Kind = OBC_Bridge;
4076 break;
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004077 }
John McCall31168b02011-06-15 23:02:42 +00004078
4079 case OBC_BridgeTransfer:
4080 // We must consume the Objective-C object produced by the cast.
4081 MustConsume = true;
4082 break;
4083 }
4084 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
4085 // Okay: id -> CF
John McCall9320b872011-09-09 05:25:32 +00004086 CK = CK_BitCast;
John McCall31168b02011-06-15 23:02:42 +00004087 switch (Kind) {
Fariborz Jahanian214567c2014-10-28 17:26:21 +00004088 case OBC_Bridge:
4089 // Reclaiming a value that's going to be __bridge-casted to CF
4090 // is very dangerous, so we don't do it.
4091 SubExpr = maybeUndoReclaimObject(SubExpr);
4092 break;
John McCall31168b02011-06-15 23:02:42 +00004093
4094 case OBC_BridgeRetained:
4095 // Produce the object before casting it.
4096 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall2d637d22011-09-10 06:18:15 +00004097 CK_ARCProduceObject,
Craig Topperc3ec1492014-05-26 06:22:03 +00004098 SubExpr, nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004099 break;
4100
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004101 case OBC_BridgeTransfer: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00004102 bool br = isKnownName("CFBridgingRetain");
John McCall31168b02011-06-15 23:02:42 +00004103 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4104 << (FromType->isBlockPointerType()? 1 : 0)
4105 << FromType
4106 << 2
4107 << T
4108 << SubExpr->getSourceRange()
4109 << Kind;
4110
4111 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4112 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
4113 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004114 << T << br
4115 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4116 br ? "CFBridgingRetain " : "__bridge_retained");
John McCall31168b02011-06-15 23:02:42 +00004117
4118 Kind = OBC_Bridge;
4119 break;
4120 }
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004121 }
John McCall31168b02011-06-15 23:02:42 +00004122 } else {
4123 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
4124 << FromType << T << Kind
4125 << SubExpr->getSourceRange()
4126 << TSInfo->getTypeLoc().getSourceRange();
4127 return ExprError();
4128 }
4129
John McCall9320b872011-09-09 05:25:32 +00004130 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCall31168b02011-06-15 23:02:42 +00004131 BridgeKeywordLoc,
4132 TSInfo, SubExpr);
4133
4134 if (MustConsume) {
4135 ExprNeedsCleanups = true;
John McCall2d637d22011-09-10 06:18:15 +00004136 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
Craig Topperc3ec1492014-05-26 06:22:03 +00004137 nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004138 }
4139
4140 return Result;
4141}
4142
4143ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
4144 SourceLocation LParenLoc,
4145 ObjCBridgeCastKind Kind,
4146 SourceLocation BridgeKeywordLoc,
4147 ParsedType Type,
4148 SourceLocation RParenLoc,
4149 Expr *SubExpr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004150 TypeSourceInfo *TSInfo = nullptr;
John McCall31168b02011-06-15 23:02:42 +00004151 QualType T = GetTypeFromParser(Type, &TSInfo);
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00004152 if (Kind == OBC_Bridge)
4153 CheckTollFreeBridgeCast(T, SubExpr);
John McCall31168b02011-06-15 23:02:42 +00004154 if (!TSInfo)
4155 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
4156 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
4157 SubExpr);
4158}