blob: 5bffdd1573a6ba4434ff96181e8cc8ba2b936f20 [file] [log] [blame]
Chris Lattner85a932e2008-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 McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Chris Lattner85a932e2008-01-04 22:32:30 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclObjC.h"
Steve Narofff494b572008-05-29 21:12:08 +000017#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor2725ca82010-04-21 19:57:20 +000019#include "clang/AST/TypeLoc.h"
Chandler Carruth55fc8732012-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 Naroff61f72cb2009-03-09 21:12:44 +000023#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-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 Naroff61f72cb2009-03-09 21:12:44 +000029
Chris Lattner85a932e2008-01-04 22:32:30 +000030using namespace clang;
John McCall26743b22011-02-03 09:00:02 +000031using namespace sema;
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +000032using llvm::makeArrayRef;
Chris Lattner85a932e2008-01-04 22:32:30 +000033
John McCallf312b1e2010-08-26 23:41:50 +000034ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
35 Expr **strings,
36 unsigned NumStrings) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000037 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
38
Chris Lattnerf4b136f2009-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 Lattner39c28bb2009-02-18 06:48:40 +000043 StringLiteral *S = Strings[0];
Mike Stump1eb44332009-09-09 15:08:12 +000044
Chris Lattnerf4b136f2009-02-18 06:13:04 +000045 // If we have a multi-part string, merge it all together.
46 if (NumStrings != 1) {
Chris Lattner85a932e2008-01-04 22:32:30 +000047 // Concatenate objc strings.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +000048 SmallString<128> StrBuf;
Chris Lattner5f9e2722011-07-23 10:55:15 +000049 SmallVector<SourceLocation, 8> StrLocs;
Mike Stump1eb44332009-09-09 15:08:12 +000050
Chris Lattner726e1682009-02-18 05:49:11 +000051 for (unsigned i = 0; i != NumStrings; ++i) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000052 S = Strings[i];
Mike Stump1eb44332009-09-09 15:08:12 +000053
Douglas Gregor5cee1192011-07-27 05:40:30 +000054 // ObjC strings can't be wide or UTF.
55 if (!S->isAscii()) {
Chris Lattnerf4b136f2009-02-18 06:13:04 +000056 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
57 << S->getSourceRange();
58 return true;
59 }
Mike Stump1eb44332009-09-09 15:08:12 +000060
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +000061 // Append the string.
62 StrBuf += S->getString();
Mike Stump1eb44332009-09-09 15:08:12 +000063
Chris Lattner39c28bb2009-02-18 06:48:40 +000064 // Get the locations of the string tokens.
65 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Chris Lattner85a932e2008-01-04 22:32:30 +000066 }
Mike Stump1eb44332009-09-09 15:08:12 +000067
Chris Lattner39c28bb2009-02-18 06:48:40 +000068 // Create the aggregate string with the appropriate content and location
69 // information.
Stephen Hines651f13c2014-04-23 16:59:28 -070070 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 Lattner85a932e2008-01-04 22:32:30 +000078 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +000079
80 return BuildObjCStringLiteral(AtLocs[0], S);
81}
Mike Stump1eb44332009-09-09 15:08:12 +000082
Ted Kremenekebcb57a2012-03-06 20:05:56 +000083ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
Chris Lattner69039812009-02-18 06:01:06 +000084 // Verify that this composite string is acceptable for ObjC strings.
85 if (CheckObjCString(S))
Chris Lattner85a932e2008-01-04 22:32:30 +000086 return true;
Chris Lattnera0af1fe2009-02-18 06:06:56 +000087
88 // Initialize the constant string interface lazily. This assumes
Steve Naroffd9fd7642009-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 Lattnera0af1fe2009-02-18 06:06:56 +000092 QualType Ty = Context.getObjCConstantStringInterface();
93 if (!Ty.isNull()) {
Steve Naroff14108da2009-07-10 23:34:53 +000094 Ty = Context.getObjCObjectPointerType(Ty);
David Blaikie4e4d0842012-03-11 07:00:24 +000095 } else if (getLangOpts().NoConstantCFStrings) {
Fariborz Jahanian4c733072010-10-19 17:19:29 +000096 IdentifierInfo *NSIdent=0;
David Blaikie4e4d0842012-03-11 07:00:24 +000097 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Fariborz Jahanian4c733072010-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 Kremenekebcb57a2012-03-06 20:05:56 +0000104 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Fariborz Jahanian8a437762010-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 Lattner13fd7e52008-06-21 21:44:18 +0000117 } else {
Patrick Beardeb382ec2012-04-19 00:25:12 +0000118 IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000119 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Douglas Gregorc83c6872010-04-15 22:33:43 +0000120 LookupOrdinaryName);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000121 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
122 Context.setObjCConstantStringInterface(StrIF);
123 Ty = Context.getObjCConstantStringInterface();
Steve Naroff14108da2009-07-10 23:34:53 +0000124 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000125 } else {
Fariborz Jahanianf64bc202012-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,
136 0, SourceLocation());
137 Ty = Context.getObjCInterfaceType(NSStringIDecl);
138 Context.setObjCNSStringType(Ty);
139 }
140 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000141 }
Chris Lattner13fd7e52008-06-21 21:44:18 +0000142 }
Mike Stump1eb44332009-09-09 15:08:12 +0000143
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000144 return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
145}
146
Jordy Rosec8521fa2012-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.
Stephen Hines651f13c2014-04-23 16:59:28 -0700159 QualType ReturnType = Method->getReturnType();
Jordy Rosec8521fa2012-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 Kremenekebcb57a2012-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 Beardeb382ec2012-04-19 00:25:12 +0000174 QualType NumberType,
175 bool isLiteral = false,
176 SourceRange R = SourceRange()) {
David Blaikiedc84cd52013-02-20 22:23:23 +0000177 Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
178 S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
179
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000180 if (!Kind) {
Patrick Beardeb382ec2012-04-19 00:25:12 +0000181 if (isLiteral) {
182 S.Diag(Loc, diag::err_invalid_nsnumber_type)
183 << NumberType << R;
184 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000185 return 0;
186 }
Patrick Beardeb382ec2012-04-19 00:25:12 +0000187
Ted Kremenekebcb57a2012-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 Beardeb382ec2012-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 Rosed2d06552012-05-12 17:32:52 +0000200 IdentifierInfo *NSNumberId =
201 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber);
Patrick Beardeb382ec2012-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 Rosed2d06552012-05-12 17:32:52 +0000208 S.NSNumberDecl = ObjCInterfaceDecl::Create(CX,
209 CX.getTranslationUnitDecl(),
210 SourceLocation(), NSNumberId,
211 0, SourceLocation());
Patrick Beardeb382ec2012-04-19 00:25:12 +0000212 } else {
213 // Otherwise, require a declaration of NSNumber.
214 S.Diag(Loc, diag::err_undeclared_nsnumber);
215 return 0;
216 }
217 } else if (!S.NSNumberDecl->hasDefinition()) {
218 S.Diag(Loc, diag::err_undeclared_nsnumber);
219 return 0;
220 }
221
222 // generate the pointer to NSNumber type.
Jordy Rosed2d06552012-05-12 17:32:52 +0000223 QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
224 S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
Patrick Beardeb382ec2012-04-19 00:25:12 +0000225 }
226
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000227 // Look for the appropriate method within NSNumber.
Jordy Rosed2d06552012-05-12 17:32:52 +0000228 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
David Blaikie4e4d0842012-03-11 07:00:24 +0000229 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
Patrick Beardeb382ec2012-04-19 00:25:12 +0000230 // create a stub definition this NSNumber factory method.
Stephen Hines651f13c2014-04-23 16:59:28 -0700231 TypeSourceInfo *ReturnTInfo = 0;
232 Method =
233 ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
234 S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
235 /*isInstance=*/false, /*isVariadic=*/false,
236 /*isPropertyAccessor=*/false,
237 /*isImplicitlyDeclared=*/true,
238 /*isDefined=*/false, ObjCMethodDecl::Required,
239 /*HasRelatedResultType=*/false);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000240 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
241 SourceLocation(), SourceLocation(),
Patrick Beardeb382ec2012-04-19 00:25:12 +0000242 &CX.Idents.get("value"),
Jordy Rosed2d06552012-05-12 17:32:52 +0000243 NumberType, /*TInfo=*/0, SC_None,
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000244 0);
Dmitri Gribenko55431692013-05-05 00:41:58 +0000245 Method->setMethodParams(S.Context, value, None);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000246 }
247
Jordy Rosec8521fa2012-05-12 17:32:44 +0000248 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000249 return 0;
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000250
251 // Note: if the parameter type is out-of-line, we'll catch it later in the
252 // implicit conversion.
253
254 S.NSNumberLiteralMethods[*Kind] = Method;
255 return Method;
256}
257
Patrick Beardeb382ec2012-04-19 00:25:12 +0000258/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
259/// numeric literal expression. Type of the expression will be "NSNumber *".
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000260ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000261 // Determine the type of the literal.
262 QualType NumberType = Number->getType();
263 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
264 // In C, character literals have type 'int'. That's not the type we want
265 // to use to determine the Objective-c literal kind.
266 switch (Char->getKind()) {
267 case CharacterLiteral::Ascii:
268 NumberType = Context.CharTy;
269 break;
270
271 case CharacterLiteral::Wide:
Hans Wennborg15f92ba2013-05-10 10:08:40 +0000272 NumberType = Context.getWideCharType();
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000273 break;
274
275 case CharacterLiteral::UTF16:
276 NumberType = Context.Char16Ty;
277 break;
278
279 case CharacterLiteral::UTF32:
280 NumberType = Context.Char32Ty;
281 break;
282 }
283 }
284
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000285 // Look for the appropriate method within NSNumber.
286 // Construct the literal.
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000287 SourceRange NR(Number->getSourceRange());
Patrick Beardeb382ec2012-04-19 00:25:12 +0000288 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000289 true, NR);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000290 if (!Method)
291 return ExprError();
292
293 // Convert the number to the type that the parameter expects.
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000294 ParmVarDecl *ParamDecl = Method->param_begin()[0];
295 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
296 ParamDecl);
297 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
298 SourceLocation(),
299 Owned(Number));
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000300 if (ConvertedNumber.isInvalid())
301 return ExprError();
302 Number = ConvertedNumber.get();
303
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000304 // Use the effective source range of the literal, including the leading '@'.
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000305 return MaybeBindToTemporary(
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000306 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
307 SourceRange(AtLoc, NR.getEnd())));
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000308}
309
310ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
311 SourceLocation ValueLoc,
312 bool Value) {
313 ExprResult Inner;
David Blaikie4e4d0842012-03-11 07:00:24 +0000314 if (getLangOpts().CPlusPlus) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000315 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
316 } else {
317 // C doesn't actually have a way to represent literal values of type
318 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
319 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
320 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
321 CK_IntegralToBoolean);
322 }
323
324 return BuildObjCNumericLiteral(AtLoc, Inner.get());
325}
326
327/// \brief Check that the given expression is a valid element of an Objective-C
328/// collection literal.
329static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
Fariborz Jahaniandc25f8c2013-08-13 23:44:55 +0000330 QualType T,
331 bool ArrayLiteral = false) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000332 // If the expression is type-dependent, there's nothing for us to do.
333 if (Element->isTypeDependent())
334 return Element;
335
336 ExprResult Result = S.CheckPlaceholderExpr(Element);
337 if (Result.isInvalid())
338 return ExprError();
339 Element = Result.get();
340
341 // In C++, check for an implicit conversion to an Objective-C object pointer
342 // type.
David Blaikie4e4d0842012-03-11 07:00:24 +0000343 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000344 InitializedEntity Entity
Jordy Rosed2d06552012-05-12 17:32:52 +0000345 = InitializedEntity::InitializeParameter(S.Context, T,
346 /*Consumed=*/false);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000347 InitializationKind Kind
Jordy Rosed2d06552012-05-12 17:32:52 +0000348 = InitializationKind::CreateCopy(Element->getLocStart(),
349 SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000350 InitializationSequence Seq(S, Entity, Kind, Element);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000351 if (!Seq.Failed())
Benjamin Kramer5354e772012-08-23 23:38:35 +0000352 return Seq.Perform(S, Entity, Kind, Element);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000353 }
354
355 Expr *OrigElement = Element;
356
357 // Perform lvalue-to-rvalue conversion.
358 Result = S.DefaultLvalueConversion(Element);
359 if (Result.isInvalid())
360 return ExprError();
361 Element = Result.get();
362
363 // Make sure that we have an Objective-C pointer type or block.
364 if (!Element->getType()->isObjCObjectPointerType() &&
365 !Element->getType()->isBlockPointerType()) {
366 bool Recovered = false;
367
368 // If this is potentially an Objective-C numeric literal, add the '@'.
369 if (isa<IntegerLiteral>(OrigElement) ||
370 isa<CharacterLiteral>(OrigElement) ||
371 isa<FloatingLiteral>(OrigElement) ||
372 isa<ObjCBoolLiteralExpr>(OrigElement) ||
373 isa<CXXBoolLiteralExpr>(OrigElement)) {
374 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
375 int Which = isa<CharacterLiteral>(OrigElement) ? 1
376 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
377 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
378 : 3;
379
380 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
381 << Which << OrigElement->getSourceRange()
382 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
383
384 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
385 OrigElement);
386 if (Result.isInvalid())
387 return ExprError();
388
389 Element = Result.get();
390 Recovered = true;
391 }
392 }
393 // If this is potentially an Objective-C string literal, add the '@'.
394 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
395 if (String->isAscii()) {
396 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
397 << 0 << OrigElement->getSourceRange()
398 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
399
400 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
401 if (Result.isInvalid())
402 return ExprError();
403
404 Element = Result.get();
405 Recovered = true;
406 }
407 }
Fariborz Jahaniandc25f8c2013-08-13 23:44:55 +0000408
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000409 if (!Recovered) {
410 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
411 << Element->getType();
412 return ExprError();
413 }
414 }
Fariborz Jahaniandc25f8c2013-08-13 23:44:55 +0000415 if (ArrayLiteral)
Ted Kremeneka1882982013-10-09 22:34:33 +0000416 if (ObjCStringLiteral *getString =
417 dyn_cast<ObjCStringLiteral>(OrigElement)) {
418 if (StringLiteral *SL = getString->getString()) {
419 unsigned numConcat = SL->getNumConcatenated();
420 if (numConcat > 1) {
421 // Only warn if the concatenated string doesn't come from a macro.
422 bool hasMacro = false;
423 for (unsigned i = 0; i < numConcat ; ++i)
424 if (SL->getStrTokenLoc(i).isMacroID()) {
425 hasMacro = true;
426 break;
427 }
428 if (!hasMacro)
429 S.Diag(Element->getLocStart(),
430 diag::warn_concatenated_nsarray_literal)
431 << Element->getType();
432 }
433 }
Fariborz Jahaniandc25f8c2013-08-13 23:44:55 +0000434 }
435
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000436 // Make sure that the element has the type that the container factory
437 // function expects.
438 return S.PerformCopyInitialization(
439 InitializedEntity::InitializeParameter(S.Context, T,
440 /*Consumed=*/false),
441 Element->getLocStart(), Element);
442}
443
Patrick Beardeb382ec2012-04-19 00:25:12 +0000444ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
445 if (ValueExpr->isTypeDependent()) {
446 ObjCBoxedExpr *BoxedExpr =
447 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, NULL, SR);
448 return Owned(BoxedExpr);
449 }
450 ObjCMethodDecl *BoxingMethod = NULL;
451 QualType BoxedType;
452 // Convert the expression to an RValue, so we can check for pointer types...
453 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
454 if (RValue.isInvalid()) {
455 return ExprError();
456 }
457 ValueExpr = RValue.get();
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000458 QualType ValueType(ValueExpr->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +0000459 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
460 QualType PointeeType = PT->getPointeeType();
461 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
462
463 if (!NSStringDecl) {
464 IdentifierInfo *NSStringId =
465 NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
466 NamedDecl *Decl = LookupSingleName(TUScope, NSStringId,
467 SR.getBegin(), LookupOrdinaryName);
468 NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl);
469 if (!NSStringDecl) {
470 if (getLangOpts().DebuggerObjCLiteral) {
471 // Support boxed expressions in the debugger w/o NSString declaration.
Jordy Rosed2d06552012-05-12 17:32:52 +0000472 DeclContext *TU = Context.getTranslationUnitDecl();
473 NSStringDecl = ObjCInterfaceDecl::Create(Context, TU,
474 SourceLocation(),
475 NSStringId,
Patrick Beardeb382ec2012-04-19 00:25:12 +0000476 0, SourceLocation());
477 } else {
478 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
479 return ExprError();
480 }
481 } else if (!NSStringDecl->hasDefinition()) {
482 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
483 return ExprError();
484 }
485 assert(NSStringDecl && "NSStringDecl should not be NULL");
Jordy Rosed2d06552012-05-12 17:32:52 +0000486 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
487 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
Patrick Beardeb382ec2012-04-19 00:25:12 +0000488 }
489
490 if (!StringWithUTF8StringMethod) {
491 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
492 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
493
494 // Look for the appropriate method within NSString.
Jordy Rosec8521fa2012-05-12 17:32:44 +0000495 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
496 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
Patrick Beardeb382ec2012-04-19 00:25:12 +0000497 // Debugger needs to work even if NSString hasn't been defined.
Stephen Hines651f13c2014-04-23 16:59:28 -0700498 TypeSourceInfo *ReturnTInfo = 0;
499 ObjCMethodDecl *M = ObjCMethodDecl::Create(
500 Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
501 NSStringPointer, ReturnTInfo, NSStringDecl,
502 /*isInstance=*/false, /*isVariadic=*/false,
503 /*isPropertyAccessor=*/false,
504 /*isImplicitlyDeclared=*/true,
505 /*isDefined=*/false, ObjCMethodDecl::Required,
506 /*HasRelatedResultType=*/false);
Jordy Rosed2d06552012-05-12 17:32:52 +0000507 QualType ConstCharType = Context.CharTy.withConst();
Patrick Beardeb382ec2012-04-19 00:25:12 +0000508 ParmVarDecl *value =
509 ParmVarDecl::Create(Context, M,
510 SourceLocation(), SourceLocation(),
511 &Context.Idents.get("value"),
Jordy Rosed2d06552012-05-12 17:32:52 +0000512 Context.getPointerType(ConstCharType),
Patrick Beardeb382ec2012-04-19 00:25:12 +0000513 /*TInfo=*/0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000514 SC_None, 0);
Dmitri Gribenko55431692013-05-05 00:41:58 +0000515 M->setMethodParams(Context, value, None);
Jordy Rosec8521fa2012-05-12 17:32:44 +0000516 BoxingMethod = M;
Patrick Beardeb382ec2012-04-19 00:25:12 +0000517 }
Jordy Rose99446d92012-05-12 15:53:41 +0000518
Jordy Rosec8521fa2012-05-12 17:32:44 +0000519 if (!validateBoxingMethod(*this, SR.getBegin(), NSStringDecl,
520 stringWithUTF8String, BoxingMethod))
521 return ExprError();
522
523 StringWithUTF8StringMethod = BoxingMethod;
Patrick Beardeb382ec2012-04-19 00:25:12 +0000524 }
525
526 BoxingMethod = StringWithUTF8StringMethod;
527 BoxedType = NSStringPointer;
528 }
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000529 } else if (ValueType->isBuiltinType()) {
Patrick Beardeb382ec2012-04-19 00:25:12 +0000530 // The other types we support are numeric, char and BOOL/bool. We could also
531 // provide limited support for structure types, such as NSRange, NSRect, and
532 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
533 // for more details.
534
535 // Check for a top-level character literal.
536 if (const CharacterLiteral *Char =
537 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
538 // In C, character literals have type 'int'. That's not the type we want
539 // to use to determine the Objective-c literal kind.
540 switch (Char->getKind()) {
541 case CharacterLiteral::Ascii:
542 ValueType = Context.CharTy;
543 break;
544
545 case CharacterLiteral::Wide:
Hans Wennborg15f92ba2013-05-10 10:08:40 +0000546 ValueType = Context.getWideCharType();
Patrick Beardeb382ec2012-04-19 00:25:12 +0000547 break;
548
549 case CharacterLiteral::UTF16:
550 ValueType = Context.Char16Ty;
551 break;
552
553 case CharacterLiteral::UTF32:
554 ValueType = Context.Char32Ty;
555 break;
556 }
557 }
558
559 // FIXME: Do I need to do anything special with BoolTy expressions?
560
561 // Look for the appropriate method within NSNumber.
562 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType);
563 BoxedType = NSNumberPointer;
Argyrios Kyrtzidisf5343ff2012-05-15 19:17:44 +0000564
565 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
566 if (!ET->getDecl()->isComplete()) {
567 Diag(SR.getBegin(), diag::err_objc_incomplete_boxed_expression_type)
568 << ValueType << ValueExpr->getSourceRange();
569 return ExprError();
570 }
571
572 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(),
573 ET->getDecl()->getIntegerType());
574 BoxedType = NSNumberPointer;
Patrick Beardeb382ec2012-04-19 00:25:12 +0000575 }
576
577 if (!BoxingMethod) {
578 Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type)
579 << ValueType << ValueExpr->getSourceRange();
580 return ExprError();
581 }
582
583 // Convert the expression to the type that the parameter requires.
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000584 ParmVarDecl *ParamDecl = BoxingMethod->param_begin()[0];
585 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
586 ParamDecl);
587 ExprResult ConvertedValueExpr = PerformCopyInitialization(Entity,
588 SourceLocation(),
589 Owned(ValueExpr));
Patrick Beardeb382ec2012-04-19 00:25:12 +0000590 if (ConvertedValueExpr.isInvalid())
591 return ExprError();
592 ValueExpr = ConvertedValueExpr.get();
593
594 ObjCBoxedExpr *BoxedExpr =
595 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
596 BoxingMethod, SR);
597 return MaybeBindToTemporary(BoxedExpr);
598}
599
John McCall1503f0d2012-07-31 05:14:30 +0000600/// Build an ObjC subscript pseudo-object expression, given that
601/// that's supported by the runtime.
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000602ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
603 Expr *IndexExpr,
604 ObjCMethodDecl *getterMethod,
605 ObjCMethodDecl *setterMethod) {
Fariborz Jahaniand9553e32013-11-01 21:58:17 +0000606 assert(!LangOpts.isSubscriptPointerArithmetic());
John McCall260611a2012-06-20 06:18:46 +0000607
John McCall1503f0d2012-07-31 05:14:30 +0000608 // We can't get dependent types here; our callers should have
609 // filtered them out.
610 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
611 "base or index cannot have dependent type here");
612
613 // Filter out placeholders in the index. In theory, overloads could
614 // be preserved here, although that might not actually work correctly.
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000615 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
616 if (Result.isInvalid())
617 return ExprError();
618 IndexExpr = Result.get();
619
John McCall1503f0d2012-07-31 05:14:30 +0000620 // Perform lvalue-to-rvalue conversion on the base.
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000621 Result = DefaultLvalueConversion(BaseExpr);
622 if (Result.isInvalid())
623 return ExprError();
624 BaseExpr = Result.get();
John McCall1503f0d2012-07-31 05:14:30 +0000625
626 // Build the pseudo-object expression.
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000627 return Owned(ObjCSubscriptRefExpr::Create(Context,
628 BaseExpr,
629 IndexExpr,
630 Context.PseudoObjectTy,
631 getterMethod,
632 setterMethod, RB));
633
634}
635
636ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
637 // Look up the NSArray class, if we haven't done so already.
638 if (!NSArrayDecl) {
639 NamedDecl *IF = LookupSingleName(TUScope,
640 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
641 SR.getBegin(),
642 LookupOrdinaryName);
643 NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikie4e4d0842012-03-11 07:00:24 +0000644 if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000645 NSArrayDecl = ObjCInterfaceDecl::Create (Context,
646 Context.getTranslationUnitDecl(),
647 SourceLocation(),
648 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
649 0, SourceLocation());
650
651 if (!NSArrayDecl) {
652 Diag(SR.getBegin(), diag::err_undeclared_nsarray);
653 return ExprError();
654 }
655 }
656
657 // Find the arrayWithObjects:count: method, if we haven't done so already.
658 QualType IdT = Context.getObjCIdType();
659 if (!ArrayWithObjectsMethod) {
660 Selector
661 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
Jordy Rosec8521fa2012-05-12 17:32:44 +0000662 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
663 if (!Method && getLangOpts().DebuggerObjCLiteral) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700664 TypeSourceInfo *ReturnTInfo = 0;
665 Method = ObjCMethodDecl::Create(
666 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
667 Context.getTranslationUnitDecl(), false /*Instance*/,
668 false /*isVariadic*/,
669 /*isPropertyAccessor=*/false,
670 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
671 ObjCMethodDecl::Required, false);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000672 SmallVector<ParmVarDecl *, 2> Params;
Jordy Rosec8521fa2012-05-12 17:32:44 +0000673 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Rosed2d06552012-05-12 17:32:52 +0000674 SourceLocation(),
675 SourceLocation(),
676 &Context.Idents.get("objects"),
677 Context.getPointerType(IdT),
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000678 /*TInfo=*/0, SC_None, 0);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000679 Params.push_back(objects);
Jordy Rosec8521fa2012-05-12 17:32:44 +0000680 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Rosed2d06552012-05-12 17:32:52 +0000681 SourceLocation(),
682 SourceLocation(),
683 &Context.Idents.get("cnt"),
684 Context.UnsignedLongTy,
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000685 /*TInfo=*/0, SC_None, 0);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000686 Params.push_back(cnt);
Dmitri Gribenko55431692013-05-05 00:41:58 +0000687 Method->setMethodParams(Context, Params, None);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000688 }
689
Jordy Rosec8521fa2012-05-12 17:32:44 +0000690 if (!validateBoxingMethod(*this, SR.getBegin(), NSArrayDecl, Sel, Method))
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000691 return ExprError();
Jordy Rosec8521fa2012-05-12 17:32:44 +0000692
Jordy Rose3eda6fa2012-05-12 17:32:56 +0000693 // Dig out the type that all elements should be converted to.
694 QualType T = Method->param_begin()[0]->getType();
695 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;
700 Diag(Method->param_begin()[0]->getLocation(),
701 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.
708 if (!Method->param_begin()[1]->getType()->isIntegerType()) {
709 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
710 << Sel;
711 Diag(Method->param_begin()[1]->getLocation(),
712 diag::note_objc_literal_method_param)
713 << 1
714 << Method->param_begin()[1]->getType()
715 << "integral";
716 return ExprError();
717 }
718
719 // We've found a good +arrayWithObjects:count: method. Save it!
Jordy Rosec8521fa2012-05-12 17:32:44 +0000720 ArrayWithObjectsMethod = Method;
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000721 }
722
Jordy Rose3eda6fa2012-05-12 17:32:56 +0000723 QualType ObjectsType = ArrayWithObjectsMethod->param_begin()[0]->getType();
724 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
Ted Kremenekebcb57a2012-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 Kramer5354e772012-08-23 23:38:35 +0000728 Expr **ElementsBuffer = Elements.data();
Ted Kremenekebcb57a2012-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 Jahaniandc25f8c2013-08-13 23:44:55 +0000732 RequiredType, true);
Ted Kremenekebcb57a2012-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 Kramer5354e772012-08-23 23:38:35 +0000744 ObjCArrayLiteral::Create(Context, Elements, Ty,
745 ArrayWithObjectsMethod, SR));
Ted Kremenekebcb57a2012-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 Blaikie4e4d0842012-03-11 07:00:24 +0000757 if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000758 NSDictionaryDecl = ObjCInterfaceDecl::Create (Context,
759 Context.getTranslationUnitDecl(),
760 SourceLocation(),
761 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
762 0, SourceLocation());
763
764 if (!NSDictionaryDecl) {
765 Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
766 return ExprError();
767 }
768 }
769
770 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
771 // so already.
772 QualType IdT = Context.getObjCIdType();
773 if (!DictionaryWithObjectsMethod) {
774 Selector Sel = NSAPIObj->getNSDictionarySelector(
Jordy Rosed2d06552012-05-12 17:32:52 +0000775 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
Jordy Rosec8521fa2012-05-12 17:32:44 +0000776 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
777 if (!Method && getLangOpts().DebuggerObjCLiteral) {
778 Method = ObjCMethodDecl::Create(Context,
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000779 SourceLocation(), SourceLocation(), Sel,
780 IdT,
781 0 /*TypeSourceInfo */,
782 Context.getTranslationUnitDecl(),
783 false /*Instance*/, false/*isVariadic*/,
Jordan Rose1e4691b2012-10-10 16:42:25 +0000784 /*isPropertyAccessor=*/false,
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000785 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
786 ObjCMethodDecl::Required,
787 false);
788 SmallVector<ParmVarDecl *, 3> Params;
Jordy Rosec8521fa2012-05-12 17:32:44 +0000789 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Rosed2d06552012-05-12 17:32:52 +0000790 SourceLocation(),
791 SourceLocation(),
792 &Context.Idents.get("objects"),
793 Context.getPointerType(IdT),
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000794 /*TInfo=*/0, SC_None, 0);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000795 Params.push_back(objects);
Jordy Rosec8521fa2012-05-12 17:32:44 +0000796 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
Jordy Rosed2d06552012-05-12 17:32:52 +0000797 SourceLocation(),
798 SourceLocation(),
799 &Context.Idents.get("keys"),
800 Context.getPointerType(IdT),
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000801 /*TInfo=*/0, SC_None, 0);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000802 Params.push_back(keys);
Jordy Rosec8521fa2012-05-12 17:32:44 +0000803 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Rosed2d06552012-05-12 17:32:52 +0000804 SourceLocation(),
805 SourceLocation(),
806 &Context.Idents.get("cnt"),
807 Context.UnsignedLongTy,
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000808 /*TInfo=*/0, SC_None, 0);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000809 Params.push_back(cnt);
Dmitri Gribenko55431692013-05-05 00:41:58 +0000810 Method->setMethodParams(Context, Params, None);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000811 }
812
Jordy Rosec8521fa2012-05-12 17:32:44 +0000813 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
814 Method))
815 return ExprError();
816
Jordy Rose3eda6fa2012-05-12 17:32:56 +0000817 // Dig out the type that all values should be converted to.
818 QualType ValueT = Method->param_begin()[0]->getType();
819 const PointerType *PtrValue = ValueT->getAs<PointerType>();
820 if (!PtrValue ||
821 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000822 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
Jordy Rose3eda6fa2012-05-12 17:32:56 +0000823 << Sel;
824 Diag(Method->param_begin()[0]->getLocation(),
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000825 diag::note_objc_literal_method_param)
Jordy Rose3eda6fa2012-05-12 17:32:56 +0000826 << 0 << ValueT
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000827 << Context.getPointerType(IdT.withConst());
828 return ExprError();
829 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000830
Jordy Rose3eda6fa2012-05-12 17:32:56 +0000831 // Dig out the type that all keys should be converted to.
832 QualType KeyT = Method->param_begin()[1]->getType();
833 const PointerType *PtrKey = KeyT->getAs<PointerType>();
834 if (!PtrKey ||
835 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
836 IdT)) {
837 bool err = true;
838 if (PtrKey) {
839 if (QIDNSCopying.isNull()) {
840 // key argument of selector is id<NSCopying>?
841 if (ObjCProtocolDecl *NSCopyingPDecl =
842 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
843 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
844 QIDNSCopying =
845 Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
846 (ObjCProtocolDecl**) PQ,1);
847 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
848 }
849 }
850 if (!QIDNSCopying.isNull())
851 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
852 QIDNSCopying);
853 }
854
855 if (err) {
856 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
857 << Sel;
858 Diag(Method->param_begin()[1]->getLocation(),
859 diag::note_objc_literal_method_param)
860 << 1 << KeyT
861 << Context.getPointerType(IdT.withConst());
862 return ExprError();
863 }
864 }
865
866 // Check that the 'count' parameter is integral.
867 QualType CountType = Method->param_begin()[2]->getType();
868 if (!CountType->isIntegerType()) {
869 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
870 << Sel;
871 Diag(Method->param_begin()[2]->getLocation(),
872 diag::note_objc_literal_method_param)
873 << 2 << CountType
874 << "integral";
875 return ExprError();
876 }
877
878 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
879 DictionaryWithObjectsMethod = Method;
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000880 }
881
Jordy Rose3eda6fa2012-05-12 17:32:56 +0000882 QualType ValuesT = DictionaryWithObjectsMethod->param_begin()[0]->getType();
883 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
884 QualType KeysT = DictionaryWithObjectsMethod->param_begin()[1]->getType();
885 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
886
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000887 // Check that each of the keys and values provided is valid in a collection
888 // literal, performing conversions as necessary.
889 bool HasPackExpansions = false;
890 for (unsigned I = 0, N = NumElements; I != N; ++I) {
891 // Check the key.
892 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
893 KeyT);
894 if (Key.isInvalid())
895 return ExprError();
896
897 // Check the value.
898 ExprResult Value
899 = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
900 if (Value.isInvalid())
901 return ExprError();
902
903 Elements[I].Key = Key.get();
904 Elements[I].Value = Value.get();
905
906 if (Elements[I].EllipsisLoc.isInvalid())
907 continue;
908
909 if (!Elements[I].Key->containsUnexpandedParameterPack() &&
910 !Elements[I].Value->containsUnexpandedParameterPack()) {
911 Diag(Elements[I].EllipsisLoc,
912 diag::err_pack_expansion_without_parameter_packs)
913 << SourceRange(Elements[I].Key->getLocStart(),
914 Elements[I].Value->getLocEnd());
915 return ExprError();
916 }
917
918 HasPackExpansions = true;
919 }
920
921
922 QualType Ty
923 = Context.getObjCObjectPointerType(
Robert Wilhelmecf119c2013-08-19 07:57:02 +0000924 Context.getObjCInterfaceType(NSDictionaryDecl));
925 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
926 Context, makeArrayRef(Elements, NumElements), HasPackExpansions, Ty,
927 DictionaryWithObjectsMethod, SR));
Chris Lattner85a932e2008-01-04 22:32:30 +0000928}
929
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000930ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregor81d34662010-04-20 15:39:42 +0000931 TypeSourceInfo *EncodedTypeInfo,
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000932 SourceLocation RParenLoc) {
Douglas Gregor81d34662010-04-20 15:39:42 +0000933 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000934 QualType StrTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000935 if (EncodedType->isDependentType())
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000936 StrTy = Context.DependentTy;
937 else {
Fariborz Jahanian6c916152011-06-16 22:34:44 +0000938 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
939 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000940 if (RequireCompleteType(AtLoc, EncodedType,
Douglas Gregord10099e2012-05-04 16:32:21 +0000941 diag::err_incomplete_type_objc_at_encode,
942 EncodedTypeInfo->getTypeLoc()))
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000943 return ExprError();
944
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000945 std::string Str;
946 Context.getObjCEncodingForType(EncodedType, Str);
947
948 // The type of @encode is the same as the type of the corresponding string,
949 // which is an array type.
950 StrTy = Context.CharTy;
951 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikie4e4d0842012-03-11 07:00:24 +0000952 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000953 StrTy.addConst();
954 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
955 ArrayType::Normal, 0);
956 }
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Douglas Gregor81d34662010-04-20 15:39:42 +0000958 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000959}
960
John McCallf312b1e2010-08-26 23:41:50 +0000961ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
962 SourceLocation EncodeLoc,
963 SourceLocation LParenLoc,
964 ParsedType ty,
965 SourceLocation RParenLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000966 // FIXME: Preserve type source info ?
Douglas Gregor81d34662010-04-20 15:39:42 +0000967 TypeSourceInfo *TInfo;
968 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
969 if (!TInfo)
970 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
971 PP.getLocForEndOfToken(LParenLoc));
Chris Lattner85a932e2008-01-04 22:32:30 +0000972
Douglas Gregor81d34662010-04-20 15:39:42 +0000973 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000974}
975
Stephen Hines651f13c2014-04-23 16:59:28 -0700976static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
977 SourceLocation AtLoc,
978 ObjCMethodDecl *Method,
979 ObjCMethodList &MethList) {
980 ObjCMethodList *M = &MethList;
981 bool Warned = false;
982 for (M = M->getNext(); M; M=M->getNext()) {
983 ObjCMethodDecl *MatchingMethodDecl = M->Method;
984 if (MatchingMethodDecl == Method ||
985 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
986 MatchingMethodDecl->getSelector() != Method->getSelector())
987 continue;
988 if (!S.MatchTwoMethodDeclarations(Method,
989 MatchingMethodDecl, Sema::MMS_loose)) {
990 if (!Warned) {
991 Warned = true;
992 S.Diag(AtLoc, diag::warning_multiple_selectors)
993 << Method->getSelector();
994 S.Diag(Method->getLocation(), diag::note_method_declared_at)
995 << Method->getDeclName();
996 }
997 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
998 << MatchingMethodDecl->getDeclName();
999 }
1000 }
1001 return Warned;
1002}
1003
1004static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
1005 ObjCMethodDecl *Method) {
1006 if (S.Diags.getDiagnosticLevel(diag::warning_multiple_selectors,
1007 SourceLocation())
1008 == DiagnosticsEngine::Ignored)
1009 return;
1010 bool Warned = false;
1011 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1012 e = S.MethodPool.end(); b != e; b++) {
1013 // first, instance methods
1014 ObjCMethodList &InstMethList = b->second.first;
1015 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc,
1016 Method, InstMethList))
1017 Warned = true;
1018
1019 // second, class methods
1020 ObjCMethodList &ClsMethList = b->second.second;
1021 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc,
1022 Method, ClsMethList) ||
1023 Warned)
1024 return;
1025 }
1026}
1027
John McCallf312b1e2010-08-26 23:41:50 +00001028ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1029 SourceLocation AtLoc,
1030 SourceLocation SelLoc,
1031 SourceLocation LParenLoc,
Fariborz Jahanian48f3cc22013-01-22 18:35:43 +00001032 SourceLocation RParenLoc) {
1033 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
1034 SourceRange(LParenLoc, RParenLoc), false, false);
1035 if (!Method)
1036 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian7ff22de2009-06-16 16:25:00 +00001037 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian9464a082013-06-05 18:46:14 +00001038 if (!Method) {
1039 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1040 Selector MatchedSel = OM->getSelector();
1041 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1042 RParenLoc.getLocWithOffset(-1));
1043 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1044 << Sel << MatchedSel
1045 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1046
1047 } else
1048 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Stephen Hines651f13c2014-04-23 16:59:28 -07001049 } else
1050 DiagnoseMismatchedSelectors(*this, AtLoc, Method);
Fariborz Jahanian4c91d892011-07-13 19:05:43 +00001051
Fariborz Jahanian48f3cc22013-01-22 18:35:43 +00001052 if (!Method ||
1053 Method->getImplementationControl() != ObjCMethodDecl::Optional) {
1054 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
1055 = ReferencedSelectors.find(Sel);
1056 if (Pos == ReferencedSelectors.end())
1057 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
Fariborz Jahanian4c91d892011-07-13 19:05:43 +00001058 }
Fariborz Jahanian3fe10412010-07-22 18:24:20 +00001059
Fariborz Jahanian48f3cc22013-01-22 18:35:43 +00001060 // In ARC, forbid the user from using @selector for
John McCallf85e1932011-06-15 23:02:42 +00001061 // retain/release/autorelease/dealloc/retainCount.
David Blaikie4e4d0842012-03-11 07:00:24 +00001062 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001063 switch (Sel.getMethodFamily()) {
1064 case OMF_retain:
1065 case OMF_release:
1066 case OMF_autorelease:
1067 case OMF_retainCount:
1068 case OMF_dealloc:
1069 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1070 Sel << SourceRange(LParenLoc, RParenLoc);
1071 break;
1072
1073 case OMF_None:
1074 case OMF_alloc:
1075 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +00001076 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +00001077 case OMF_init:
1078 case OMF_mutableCopy:
1079 case OMF_new:
1080 case OMF_self:
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001081 case OMF_performSelector:
John McCallf85e1932011-06-15 23:02:42 +00001082 break;
1083 }
1084 }
Chris Lattnera0af1fe2009-02-18 06:06:56 +00001085 QualType Ty = Context.getObjCSelType();
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +00001086 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +00001087}
1088
John McCallf312b1e2010-08-26 23:41:50 +00001089ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1090 SourceLocation AtLoc,
1091 SourceLocation ProtoLoc,
1092 SourceLocation LParenLoc,
Argyrios Kyrtzidis7d24e282012-05-16 00:50:02 +00001093 SourceLocation ProtoIdLoc,
John McCallf312b1e2010-08-26 23:41:50 +00001094 SourceLocation RParenLoc) {
Argyrios Kyrtzidis7d24e282012-05-16 00:50:02 +00001095 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +00001096 if (!PDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +00001097 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattner85a932e2008-01-04 22:32:30 +00001098 return true;
1099 }
Mike Stump1eb44332009-09-09 15:08:12 +00001100
Chris Lattnera0af1fe2009-02-18 06:06:56 +00001101 QualType Ty = Context.getObjCProtoType();
1102 if (Ty.isNull())
Chris Lattner85a932e2008-01-04 22:32:30 +00001103 return true;
Steve Naroff14108da2009-07-10 23:34:53 +00001104 Ty = Context.getObjCObjectPointerType(Ty);
Argyrios Kyrtzidis7d24e282012-05-16 00:50:02 +00001105 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +00001106}
1107
John McCall26743b22011-02-03 09:00:02 +00001108/// Try to capture an implicit reference to 'self'.
Eli Friedmanb942cb22012-02-03 22:47:37 +00001109ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1110 DeclContext *DC = getFunctionLevelDeclContext();
John McCall26743b22011-02-03 09:00:02 +00001111
1112 // If we're not in an ObjC method, error out. Note that, unlike the
1113 // C++ case, we don't require an instance method --- class methods
1114 // still have a 'self', and we really do still need to capture it!
1115 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1116 if (!method)
1117 return 0;
1118
Douglas Gregor999713e2012-02-18 09:37:24 +00001119 tryCaptureVariable(method->getSelfDecl(), Loc);
John McCall26743b22011-02-03 09:00:02 +00001120
1121 return method;
1122}
1123
Douglas Gregor5c16d632011-09-09 20:05:21 +00001124static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1125 if (T == Context.getObjCInstanceType())
1126 return Context.getObjCIdType();
1127
1128 return T;
1129}
1130
Douglas Gregor926df6c2011-06-11 01:09:30 +00001131QualType Sema::getMessageSendResultType(QualType ReceiverType,
1132 ObjCMethodDecl *Method,
1133 bool isClassMessage, bool isSuperMessage) {
1134 assert(Method && "Must have a method");
1135 if (!Method->hasRelatedResultType())
1136 return Method->getSendResultType();
1137
1138 // If a method has a related return type:
1139 // - if the method found is an instance method, but the message send
1140 // was a class message send, T is the declared return type of the method
1141 // found
1142 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregor5c16d632011-09-09 20:05:21 +00001143 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001144
1145 // - if the receiver is super, T is a pointer to the class of the
1146 // enclosing method definition
1147 if (isSuperMessage) {
1148 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
1149 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
1150 return Context.getObjCObjectPointerType(
1151 Context.getObjCInterfaceType(Class));
1152 }
1153
1154 // - if the receiver is the name of a class U, T is a pointer to U
1155 if (ReceiverType->getAs<ObjCInterfaceType>() ||
1156 ReceiverType->isObjCQualifiedInterfaceType())
1157 return Context.getObjCObjectPointerType(ReceiverType);
1158 // - if the receiver is of type Class or qualified Class type,
1159 // T is the declared return type of the method.
1160 if (ReceiverType->isObjCClassType() ||
1161 ReceiverType->isObjCQualifiedClassType())
Douglas Gregor5c16d632011-09-09 20:05:21 +00001162 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001163
1164 // - if the receiver is id, qualified id, Class, or qualified Class, T
1165 // is the receiver type, otherwise
1166 // - T is the type of the receiver expression.
1167 return ReceiverType;
1168}
John McCall26743b22011-02-03 09:00:02 +00001169
John McCall7cca8212013-03-19 07:04:25 +00001170/// Look for an ObjC method whose result type exactly matches the given type.
1171static const ObjCMethodDecl *
1172findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1173 QualType instancetype) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001174 if (MD->getReturnType() == instancetype)
1175 return MD;
John McCall7cca8212013-03-19 07:04:25 +00001176
1177 // For these purposes, a method in an @implementation overrides a
1178 // declaration in the @interface.
1179 if (const ObjCImplDecl *impl =
1180 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1181 const ObjCContainerDecl *iface;
1182 if (const ObjCCategoryImplDecl *catImpl =
1183 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1184 iface = catImpl->getCategoryDecl();
1185 } else {
1186 iface = impl->getClassInterface();
1187 }
1188
1189 const ObjCMethodDecl *ifaceMD =
1190 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1191 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1192 }
1193
1194 SmallVector<const ObjCMethodDecl *, 4> overrides;
1195 MD->getOverriddenMethods(overrides);
1196 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1197 if (const ObjCMethodDecl *result =
1198 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1199 return result;
1200 }
1201
1202 return 0;
1203}
1204
1205void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1206 // Only complain if we're in an ObjC method and the required return
1207 // type doesn't match the method's declared return type.
1208 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1209 if (!MD || !MD->hasRelatedResultType() ||
Stephen Hines651f13c2014-04-23 16:59:28 -07001210 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
John McCall7cca8212013-03-19 07:04:25 +00001211 return;
1212
1213 // Look for a method overridden by this method which explicitly uses
1214 // 'instancetype'.
1215 if (const ObjCMethodDecl *overridden =
1216 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
1217 SourceLocation loc;
1218 SourceRange range;
Stephen Hines651f13c2014-04-23 16:59:28 -07001219 if (TypeSourceInfo *TSI = overridden->getReturnTypeSourceInfo()) {
John McCall7cca8212013-03-19 07:04:25 +00001220 range = TSI->getTypeLoc().getSourceRange();
1221 loc = range.getBegin();
1222 }
1223 if (loc.isInvalid())
1224 loc = overridden->getLocation();
1225 Diag(loc, diag::note_related_result_type_explicit)
1226 << /*current method*/ 1 << range;
1227 return;
1228 }
1229
1230 // Otherwise, if we have an interesting method family, note that.
1231 // This should always trigger if the above didn't.
1232 if (ObjCMethodFamily family = MD->getMethodFamily())
1233 Diag(MD->getLocation(), diag::note_related_result_type_family)
1234 << /*current method*/ 1
1235 << family;
1236}
1237
Douglas Gregor926df6c2011-06-11 01:09:30 +00001238void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1239 E = E->IgnoreParenImpCasts();
1240 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1241 if (!MsgSend)
1242 return;
1243
1244 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1245 if (!Method)
1246 return;
1247
1248 if (!Method->hasRelatedResultType())
1249 return;
Stephen Hines651f13c2014-04-23 16:59:28 -07001250
1251 if (Context.hasSameUnqualifiedType(
1252 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
Douglas Gregor926df6c2011-06-11 01:09:30 +00001253 return;
Stephen Hines651f13c2014-04-23 16:59:28 -07001254
1255 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
Douglas Gregore97179c2011-09-08 01:46:34 +00001256 Context.getObjCInstanceType()))
1257 return;
1258
Douglas Gregor926df6c2011-06-11 01:09:30 +00001259 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1260 << Method->isInstanceMethod() << Method->getSelector()
1261 << MsgSend->getType();
1262}
1263
1264bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
Dmitri Gribenko416c9b32013-05-10 00:27:15 +00001265 MultiExprArg Args,
1266 Selector Sel,
Fariborz Jahanian376c4322012-08-31 17:03:18 +00001267 ArrayRef<SourceLocation> SelectorLocs,
1268 ObjCMethodDecl *Method,
Douglas Gregor926df6c2011-06-11 01:09:30 +00001269 bool isClassMessage, bool isSuperMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +00001270 SourceLocation lbrac, SourceLocation rbrac,
John McCallf89e55a2010-11-18 06:31:45 +00001271 QualType &ReturnType, ExprValueKind &VK) {
Argyrios Kyrtzidisf4d02392013-05-01 00:24:09 +00001272 SourceLocation SelLoc;
1273 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1274 SelLoc = SelectorLocs.front();
1275 else
1276 SelLoc = lbrac;
1277
Daniel Dunbar637cebb2008-09-11 00:01:56 +00001278 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +00001279 // Apply default argument promotion as for (C99 6.5.2.2p6).
Dmitri Gribenko416c9b32013-05-10 00:27:15 +00001280 for (unsigned i = 0, e = Args.size(); i != e; i++) {
Douglas Gregor92e986e2010-04-22 16:44:27 +00001281 if (Args[i]->isTypeDependent())
1282 continue;
1283
John McCall48f90422013-03-04 07:34:02 +00001284 ExprResult result;
1285 if (getLangOpts().DebuggerSupport) {
1286 QualType paramTy; // ignored
Argyrios Kyrtzidisf4d02392013-05-01 00:24:09 +00001287 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
John McCall48f90422013-03-04 07:34:02 +00001288 } else {
1289 result = DefaultArgumentPromotion(Args[i]);
1290 }
1291 if (result.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001292 return true;
John McCall48f90422013-03-04 07:34:02 +00001293 Args[i] = result.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +00001294 }
Daniel Dunbar6660c8a2008-09-11 00:04:36 +00001295
John McCallf85e1932011-06-15 23:02:42 +00001296 unsigned DiagID;
David Blaikie4e4d0842012-03-11 07:00:24 +00001297 if (getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +00001298 DiagID = diag::err_arc_method_not_found;
1299 else
1300 DiagID = isClassMessage ? diag::warn_class_method_not_found
1301 : diag::warn_inst_method_not_found;
Fariborz Jahanian9f00b1d2013-05-14 23:24:17 +00001302 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian419245e2013-06-18 15:31:36 +00001303 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
Fariborz Jahaniancd9c9b52013-06-18 17:10:58 +00001304 if (OMD && !OMD->isInvalidDecl()) {
Fariborz Jahanian419245e2013-06-18 15:31:36 +00001305 if (getLangOpts().ObjCAutoRefCount)
1306 DiagID = diag::error_method_not_found_with_typo;
1307 else
1308 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1309 : diag::warn_instance_method_not_found_with_typo;
Fariborz Jahaniand395e342013-06-17 17:10:54 +00001310 Selector MatchedSel = OMD->getSelector();
1311 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
Fariborz Jahanian419245e2013-06-18 15:31:36 +00001312 Diag(SelLoc, DiagID)
1313 << Sel<< isClassMessage << MatchedSel
Fariborz Jahaniand395e342013-06-17 17:10:54 +00001314 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1315 }
1316 else
1317 Diag(SelLoc, DiagID)
1318 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
Fariborz Jahanian376c4322012-08-31 17:03:18 +00001319 SelectorLocs.back());
Fariborz Jahanian9f00b1d2013-05-14 23:24:17 +00001320 // Find the class to which we are sending this message.
1321 if (ReceiverType->isObjCObjectPointerType()) {
Fariborz Jahanian14040142013-05-15 15:27:35 +00001322 if (ObjCInterfaceDecl *Class =
1323 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl())
1324 Diag(Class->getLocation(), diag::note_receiver_class_declared);
Fariborz Jahanian9f00b1d2013-05-14 23:24:17 +00001325 }
1326 }
John McCall48218c62011-07-13 17:56:40 +00001327
1328 // In debuggers, we want to use __unknown_anytype for these
1329 // results so that clients can cast them.
David Blaikie4e4d0842012-03-11 07:00:24 +00001330 if (getLangOpts().DebuggerSupport) {
John McCall48218c62011-07-13 17:56:40 +00001331 ReturnType = Context.UnknownAnyTy;
1332 } else {
1333 ReturnType = Context.getObjCIdType();
1334 }
John McCallf89e55a2010-11-18 06:31:45 +00001335 VK = VK_RValue;
Daniel Dunbar637cebb2008-09-11 00:01:56 +00001336 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +00001337 }
Mike Stump1eb44332009-09-09 15:08:12 +00001338
Douglas Gregor926df6c2011-06-11 01:09:30 +00001339 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1340 isSuperMessage);
Stephen Hines651f13c2014-04-23 16:59:28 -07001341 VK = Expr::getValueKindForType(Method->getReturnType());
Mike Stump1eb44332009-09-09 15:08:12 +00001342
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001343 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +00001344 // Method might have more arguments than selector indicates. This is due
1345 // to addition of c-style arguments in method.
1346 if (Method->param_size() > Sel.getNumArgs())
1347 NumNamedArgs = Method->param_size();
1348 // FIXME. This need be cleaned up.
Dmitri Gribenko416c9b32013-05-10 00:27:15 +00001349 if (Args.size() < NumNamedArgs) {
Argyrios Kyrtzidisf4d02392013-05-01 00:24:09 +00001350 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
Dmitri Gribenko416c9b32013-05-10 00:27:15 +00001351 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +00001352 return false;
1353 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001354
Chris Lattner312531a2009-04-12 08:11:20 +00001355 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001356 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregor92e986e2010-04-22 16:44:27 +00001357 // We can't do any type-checking on a type-dependent argument.
1358 if (Args[i]->isTypeDependent())
1359 continue;
1360
Chris Lattner85a932e2008-01-04 22:32:30 +00001361 Expr *argExpr = Args[i];
Douglas Gregor92e986e2010-04-22 16:44:27 +00001362
John McCall5acb0c92011-10-17 18:40:02 +00001363 ParmVarDecl *param = Method->param_begin()[i];
Chris Lattner85a932e2008-01-04 22:32:30 +00001364 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +00001365
John McCall5acb0c92011-10-17 18:40:02 +00001366 // Strip the unbridged-cast placeholder expression off unless it's
1367 // a consumed argument.
1368 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1369 !param->hasAttr<CFConsumedAttr>())
1370 argExpr = stripARCUnbridgedCast(argExpr);
1371
John McCallb8a8de32012-11-14 00:49:39 +00001372 // If the parameter is __unknown_anytype, infer its type
1373 // from the argument.
1374 if (param->getType() == Context.UnknownAnyTy) {
John McCall48f90422013-03-04 07:34:02 +00001375 QualType paramType;
Argyrios Kyrtzidisf4d02392013-05-01 00:24:09 +00001376 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
John McCall48f90422013-03-04 07:34:02 +00001377 if (argE.isInvalid()) {
John McCallb8a8de32012-11-14 00:49:39 +00001378 IsError = true;
John McCall48f90422013-03-04 07:34:02 +00001379 } else {
1380 Args[i] = argE.take();
John McCallb8a8de32012-11-14 00:49:39 +00001381
John McCall48f90422013-03-04 07:34:02 +00001382 // Update the parameter type in-place.
1383 param->setType(paramType);
1384 }
1385 continue;
John McCallb8a8de32012-11-14 00:49:39 +00001386 }
1387
Douglas Gregor688fc9b2010-04-21 23:24:10 +00001388 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
John McCall5acb0c92011-10-17 18:40:02 +00001389 param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00001390 diag::err_call_incomplete_argument, argExpr))
Douglas Gregor688fc9b2010-04-21 23:24:10 +00001391 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +00001392
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001393 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
John McCall5acb0c92011-10-17 18:40:02 +00001394 param);
Argyrios Kyrtzidisf4d02392013-05-01 00:24:09 +00001395 ExprResult ArgE = PerformCopyInitialization(Entity, SelLoc, Owned(argExpr));
Douglas Gregor688fc9b2010-04-21 23:24:10 +00001396 if (ArgE.isInvalid())
1397 IsError = true;
1398 else
1399 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +00001400 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001401
1402 // Promote additional arguments to variadic methods.
1403 if (Method->isVariadic()) {
Dmitri Gribenko416c9b32013-05-10 00:27:15 +00001404 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
Douglas Gregor92e986e2010-04-22 16:44:27 +00001405 if (Args[i]->isTypeDependent())
1406 continue;
1407
Jordy Rosed2d06552012-05-12 17:32:52 +00001408 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
1409 0);
John Wiegley429bb272011-04-08 18:41:53 +00001410 IsError |= Arg.isInvalid();
1411 Args[i] = Arg.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +00001412 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001413 } else {
1414 // Check for extra arguments to non-variadic methods.
Dmitri Gribenko416c9b32013-05-10 00:27:15 +00001415 if (Args.size() != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001416 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001417 diag::err_typecheck_call_too_many_args)
Dmitri Gribenko416c9b32013-05-10 00:27:15 +00001418 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
Eric Christopherccfa9632010-04-16 04:56:46 +00001419 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001420 << SourceRange(Args[NumNamedArgs]->getLocStart(),
Dmitri Gribenko416c9b32013-05-10 00:27:15 +00001421 Args.back()->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001422 }
1423 }
1424
Dmitri Gribenko416c9b32013-05-10 00:27:15 +00001425 DiagnoseSentinelCalls(Method, SelLoc, Args);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001426
1427 // Do additional checkings on method.
Dmitri Gribenko416c9b32013-05-10 00:27:15 +00001428 IsError |= CheckObjCMethodCall(
Robert Wilhelmecf119c2013-08-19 07:57:02 +00001429 Method, SelLoc, makeArrayRef<const Expr *>(Args.data(), Args.size()));
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001430
Chris Lattner312531a2009-04-12 08:11:20 +00001431 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +00001432}
1433
Stephen Hines651f13c2014-04-23 16:59:28 -07001434bool Sema::isSelfExpr(Expr *RExpr) {
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +00001435 // 'self' is objc 'self' in an objc method only.
Stephen Hines651f13c2014-04-23 16:59:28 -07001436 ObjCMethodDecl *Method =
1437 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1438 return isSelfExpr(RExpr, Method);
1439}
1440
1441bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
John McCall4b9c2d22011-11-06 09:01:30 +00001442 if (!method) return false;
1443
John McCallf85e1932011-06-15 23:02:42 +00001444 receiver = receiver->IgnoreParenLValueCasts();
1445 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCall4b9c2d22011-11-06 09:01:30 +00001446 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregorc737acb2011-09-27 16:10:05 +00001447 return true;
1448 return false;
Steve Naroff6b9dfd42009-03-04 15:11:40 +00001449}
1450
John McCall3c3b7f92011-10-25 17:37:35 +00001451/// LookupMethodInType - Look up a method in an ObjCObjectType.
1452ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1453 bool isInstance) {
1454 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1455 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1456 // Look it up in the main interface (and categories, etc.)
1457 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1458 return method;
1459
1460 // Okay, look for "private" methods declared in any
1461 // @implementations we've seen.
Anna Zakse61354b2012-07-27 19:07:44 +00001462 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1463 return method;
John McCall3c3b7f92011-10-25 17:37:35 +00001464 }
1465
1466 // Check qualifiers.
Stephen Hines651f13c2014-04-23 16:59:28 -07001467 for (const auto *I : objType->quals())
1468 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
John McCall3c3b7f92011-10-25 17:37:35 +00001469 return method;
1470
1471 return 0;
1472}
1473
Fariborz Jahanian61478062011-03-09 20:18:06 +00001474/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1475/// list of a qualified objective pointer type.
1476ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1477 const ObjCObjectPointerType *OPT,
1478 bool Instance)
1479{
1480 ObjCMethodDecl *MD = 0;
Stephen Hines651f13c2014-04-23 16:59:28 -07001481 for (const auto *PROTO : OPT->quals()) {
Fariborz Jahanian61478062011-03-09 20:18:06 +00001482 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1483 return MD;
1484 }
1485 }
1486 return 0;
1487}
1488
Fariborz Jahanian98795562012-04-19 23:49:39 +00001489static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) {
1490 if (!Receiver)
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001491 return;
1492
Fariborz Jahanian31170392012-06-04 19:16:34 +00001493 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Receiver))
1494 Receiver = OVE->getSourceExpr();
1495
Fariborz Jahanian98795562012-04-19 23:49:39 +00001496 Expr *RExpr = Receiver->IgnoreParenImpCasts();
1497 SourceLocation Loc = RExpr->getLocStart();
1498 QualType T = RExpr->getType();
Jordan Rose04bec392012-10-10 16:42:54 +00001499 const ObjCPropertyDecl *PDecl = 0;
1500 const ObjCMethodDecl *GDecl = 0;
Fariborz Jahanian98795562012-04-19 23:49:39 +00001501 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) {
1502 RExpr = POE->getSyntacticForm();
1503 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) {
1504 if (PRE->isImplicitProperty()) {
1505 GDecl = PRE->getImplicitPropertyGetter();
1506 if (GDecl) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001507 T = GDecl->getReturnType();
Fariborz Jahanian98795562012-04-19 23:49:39 +00001508 }
1509 }
1510 else {
1511 PDecl = PRE->getExplicitProperty();
1512 if (PDecl) {
1513 T = PDecl->getType();
1514 }
1515 }
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001516 }
Fariborz Jahanian98795562012-04-19 23:49:39 +00001517 }
Fariborz Jahanian31170392012-06-04 19:16:34 +00001518 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RExpr)) {
1519 // See if receiver is a method which envokes a synthesized getter
1520 // backing a 'weak' property.
1521 ObjCMethodDecl *Method = ME->getMethodDecl();
Jordan Rose04bec392012-10-10 16:42:54 +00001522 if (Method && Method->getSelector().getNumArgs() == 0) {
1523 PDecl = Method->findPropertyDecl();
Fariborz Jahanian31170392012-06-04 19:16:34 +00001524 if (PDecl)
1525 T = PDecl->getType();
1526 }
1527 }
Fariborz Jahanian98795562012-04-19 23:49:39 +00001528
Jordan Rose3437daa2012-09-28 22:21:42 +00001529 if (T.getObjCLifetime() != Qualifiers::OCL_Weak) {
1530 if (!PDecl)
1531 return;
1532 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak))
1533 return;
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001534 }
Jordan Rose3437daa2012-09-28 22:21:42 +00001535
1536 S.Diag(Loc, diag::warn_receiver_is_weak)
1537 << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2));
1538
1539 if (PDecl)
Fariborz Jahanian98795562012-04-19 23:49:39 +00001540 S.Diag(PDecl->getLocation(), diag::note_property_declare);
Jordan Rose3437daa2012-09-28 22:21:42 +00001541 else if (GDecl)
1542 S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl;
1543
1544 S.Diag(Loc, diag::note_arc_assign_to_strong);
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001545}
1546
Chris Lattner7f816522010-04-11 07:45:24 +00001547/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1548/// objective C interface. This is a property reference expression.
John McCall60d7b3a2010-08-24 06:29:42 +00001549ExprResult Sema::
Chris Lattner7f816522010-04-11 07:45:24 +00001550HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001551 Expr *BaseExpr, SourceLocation OpLoc,
1552 DeclarationName MemberName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001553 SourceLocation MemberLoc,
1554 SourceLocation SuperLoc, QualType SuperType,
1555 bool Super) {
Chris Lattner7f816522010-04-11 07:45:24 +00001556 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1557 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Benjamin Kramerc4704422012-05-19 16:03:58 +00001558
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001559 if (!MemberName.isIdentifier()) {
Douglas Gregor109ec1b2011-04-20 18:19:55 +00001560 Diag(MemberLoc, diag::err_invalid_property_name)
1561 << MemberName << QualType(OPT, 0);
1562 return ExprError();
1563 }
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001564
1565 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregor109ec1b2011-04-20 18:19:55 +00001566
Douglas Gregorb3029962011-11-14 22:10:01 +00001567 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1568 : BaseExpr->getSourceRange();
1569 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00001570 diag::err_property_not_found_forward_class,
1571 MemberName, BaseRange))
Fariborz Jahanian8b1aba42010-12-16 00:56:28 +00001572 return ExprError();
Douglas Gregorb3029962011-11-14 22:10:01 +00001573
Chris Lattner7f816522010-04-11 07:45:24 +00001574 // Search for a declared property first.
Fariborz Jahanianb5b155c2012-05-24 22:48:38 +00001575 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Chris Lattner7f816522010-04-11 07:45:24 +00001576 // Check whether we can reference this property.
1577 if (DiagnoseUseOfDecl(PD, MemberLoc))
1578 return ExprError();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001579 if (Super)
John McCall3c3b7f92011-10-25 17:37:35 +00001580 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001581 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001582 MemberLoc,
1583 SuperLoc, SuperType));
1584 else
John McCall3c3b7f92011-10-25 17:37:35 +00001585 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001586 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001587 MemberLoc, BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +00001588 }
1589 // Check protocols on qualified interfaces.
Stephen Hines651f13c2014-04-23 16:59:28 -07001590 for (const auto *I : OPT->quals())
1591 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
Chris Lattner7f816522010-04-11 07:45:24 +00001592 // Check whether we can reference this property.
1593 if (DiagnoseUseOfDecl(PD, MemberLoc))
1594 return ExprError();
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001595
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001596 if (Super)
John McCall3c3b7f92011-10-25 17:37:35 +00001597 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1598 Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001599 VK_LValue,
1600 OK_ObjCProperty,
1601 MemberLoc,
1602 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001603 else
John McCall3c3b7f92011-10-25 17:37:35 +00001604 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1605 Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001606 VK_LValue,
1607 OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001608 MemberLoc,
1609 BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +00001610 }
1611 // If that failed, look for an "implicit" property by seeing if the nullary
1612 // selector is implemented.
1613
1614 // FIXME: The logic for looking up nullary and unary selectors should be
1615 // shared with the code in ActOnInstanceMessage.
1616
1617 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1618 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001619
1620 // May be founf in property's qualified list.
1621 if (!Getter)
1622 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner7f816522010-04-11 07:45:24 +00001623
1624 // If this reference is in an @implementation, check for 'private' methods.
1625 if (!Getter)
Fariborz Jahanian74b27562010-12-03 23:37:08 +00001626 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner7f816522010-04-11 07:45:24 +00001627
Chris Lattner7f816522010-04-11 07:45:24 +00001628 if (Getter) {
1629 // Check if we can reference this property.
1630 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1631 return ExprError();
1632 }
1633 // If we found a getter then this may be a valid dot-reference, we
1634 // will look for the matching setter, in case it is needed.
1635 Selector SetterSel =
Adrian Prantl80e8ea92013-06-07 22:29:12 +00001636 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1637 PP.getSelectorTable(), Member);
Chris Lattner7f816522010-04-11 07:45:24 +00001638 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanianb5b155c2012-05-24 22:48:38 +00001639
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001640 // May be founf in property's qualified list.
1641 if (!Setter)
1642 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1643
Chris Lattner7f816522010-04-11 07:45:24 +00001644 if (!Setter) {
1645 // If this reference is in an @implementation, also check for 'private'
1646 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +00001647 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner7f816522010-04-11 07:45:24 +00001648 }
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001649
Chris Lattner7f816522010-04-11 07:45:24 +00001650 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1651 return ExprError();
1652
Fariborz Jahanian99130e52010-12-22 19:46:35 +00001653 if (Getter || Setter) {
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001654 if (Super)
John McCall12f78a62010-12-02 01:19:52 +00001655 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001656 Context.PseudoObjectTy,
1657 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +00001658 MemberLoc,
1659 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001660 else
John McCall12f78a62010-12-02 01:19:52 +00001661 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001662 Context.PseudoObjectTy,
1663 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +00001664 MemberLoc, BaseExpr));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001665
Chris Lattner7f816522010-04-11 07:45:24 +00001666 }
1667
1668 // Attempt to correct for typos in property names.
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001669 DeclFilterCCC<ObjCPropertyDecl> Validator;
1670 if (TypoCorrection Corrected = CorrectTypo(
Richard Smith2d670972013-08-17 00:46:16 +00001671 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
1672 NULL, Validator, IFace, false, OPT)) {
1673 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1674 << MemberName << QualType(OPT, 0));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001675 DeclarationName TypoResult = Corrected.getCorrection();
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001676 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1677 TypoResult, MemberLoc,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001678 SuperLoc, SuperType, Super);
Chris Lattner7f816522010-04-11 07:45:24 +00001679 }
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +00001680 ObjCInterfaceDecl *ClassDeclared;
1681 if (ObjCIvarDecl *Ivar =
1682 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1683 QualType T = Ivar->getType();
1684 if (const ObjCObjectPointerType * OBJPT =
1685 T->getAsObjCInterfacePointerType()) {
Douglas Gregorb3029962011-11-14 22:10:01 +00001686 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00001687 diag::err_property_not_as_forward_class,
1688 MemberName, BaseExpr))
Douglas Gregorb3029962011-11-14 22:10:01 +00001689 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +00001690 }
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001691 Diag(MemberLoc,
1692 diag::err_ivar_access_using_property_syntax_suggest)
1693 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1694 << FixItHint::CreateReplacement(OpLoc, "->");
1695 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +00001696 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +00001697
Chris Lattner7f816522010-04-11 07:45:24 +00001698 Diag(MemberLoc, diag::err_property_not_found)
1699 << MemberName << QualType(OPT, 0);
Fariborz Jahanian99130e52010-12-22 19:46:35 +00001700 if (Setter)
Chris Lattner7f816522010-04-11 07:45:24 +00001701 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian99130e52010-12-22 19:46:35 +00001702 << MemberName << BaseExpr->getSourceRange();
Chris Lattner7f816522010-04-11 07:45:24 +00001703 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +00001704}
1705
1706
1707
John McCall60d7b3a2010-08-24 06:29:42 +00001708ExprResult Sema::
Chris Lattnereb483eb2010-04-11 08:28:14 +00001709ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1710 IdentifierInfo &propertyName,
1711 SourceLocation receiverNameLoc,
1712 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001713
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001714 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +00001715 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1716 receiverNameLoc);
Douglas Gregor926df6c2011-06-11 01:09:30 +00001717
1718 bool IsSuper = false;
Chris Lattnereb483eb2010-04-11 08:28:14 +00001719 if (IFace == 0) {
1720 // If the "receiver" is 'super' in a method, handle it as an expression-like
1721 // property reference.
John McCall26743b22011-02-03 09:00:02 +00001722 if (receiverNamePtr->isStr("super")) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00001723 IsSuper = true;
1724
Eli Friedmanb942cb22012-02-03 22:47:37 +00001725 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Chris Lattnereb483eb2010-04-11 08:28:14 +00001726 if (CurMethod->isInstanceMethod()) {
Fariborz Jahanian6fc9e7a2013-03-11 22:26:33 +00001727 ObjCInterfaceDecl *Super =
1728 CurMethod->getClassInterface()->getSuperClass();
1729 if (!Super) {
1730 // The current class does not have a superclass.
1731 Diag(receiverNameLoc, diag::error_root_class_cannot_use_super)
1732 << CurMethod->getClassInterface()->getIdentifier();
1733 return ExprError();
1734 }
1735 QualType T = Context.getObjCInterfaceType(Super);
Chris Lattnereb483eb2010-04-11 08:28:14 +00001736 T = Context.getObjCObjectPointerType(T);
Chris Lattnereb483eb2010-04-11 08:28:14 +00001737
1738 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001739 /*BaseExpr*/0,
1740 SourceLocation()/*OpLoc*/,
1741 &propertyName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001742 propertyNameLoc,
1743 receiverNameLoc, T, true);
Chris Lattnereb483eb2010-04-11 08:28:14 +00001744 }
Mike Stump1eb44332009-09-09 15:08:12 +00001745
Chris Lattnereb483eb2010-04-11 08:28:14 +00001746 // Otherwise, if this is a class method, try dispatching to our
1747 // superclass.
1748 IFace = CurMethod->getClassInterface()->getSuperClass();
1749 }
John McCall26743b22011-02-03 09:00:02 +00001750 }
Chris Lattnereb483eb2010-04-11 08:28:14 +00001751
1752 if (IFace == 0) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001753 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
1754 << tok::l_paren;
Chris Lattnereb483eb2010-04-11 08:28:14 +00001755 return ExprError();
1756 }
1757 }
1758
1759 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +00001760 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001761 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001762
1763 // If this reference is in an @implementation, check for 'private' methods.
1764 if (!Getter)
1765 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1766 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001767 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001768 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001769
1770 if (Getter) {
1771 // FIXME: refactor/share with ActOnMemberReference().
1772 // Check if we can reference this property.
1773 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1774 return ExprError();
1775 }
Mike Stump1eb44332009-09-09 15:08:12 +00001776
Steve Naroff61f72cb2009-03-09 21:12:44 +00001777 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +00001778 Selector SetterSel =
Adrian Prantl80e8ea92013-06-07 22:29:12 +00001779 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1780 PP.getSelectorTable(),
1781 &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +00001782
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001783 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001784 if (!Setter) {
1785 // If this reference is in an @implementation, also check for 'private'
1786 // methods.
1787 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1788 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001789 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001790 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001791 }
1792 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00001793 if (!Setter)
1794 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001795
1796 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1797 return ExprError();
1798
1799 if (Getter || Setter) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00001800 if (IsSuper)
1801 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001802 Context.PseudoObjectTy,
1803 VK_LValue, OK_ObjCProperty,
Douglas Gregor926df6c2011-06-11 01:09:30 +00001804 propertyNameLoc,
1805 receiverNameLoc,
1806 Context.getObjCInterfaceType(IFace)));
1807
John McCall12f78a62010-12-02 01:19:52 +00001808 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001809 Context.PseudoObjectTy,
1810 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +00001811 propertyNameLoc,
1812 receiverNameLoc, IFace));
Steve Naroff61f72cb2009-03-09 21:12:44 +00001813 }
1814 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1815 << &propertyName << Context.getObjCInterfaceType(IFace));
1816}
1817
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001818namespace {
1819
1820class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1821 public:
1822 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1823 // Determine whether "super" is acceptable in the current context.
1824 if (Method && Method->getClassInterface())
1825 WantObjCSuper = Method->getClassInterface()->getSuperClass();
1826 }
1827
Stephen Hines651f13c2014-04-23 16:59:28 -07001828 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001829 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1830 candidate.isKeyword("super");
1831 }
1832};
1833
1834}
1835
Douglas Gregor47bd5432010-04-14 02:46:37 +00001836Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +00001837 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +00001838 SourceLocation NameLoc,
1839 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +00001840 bool HasTrailingDot,
John McCallb3d87482010-08-24 05:47:05 +00001841 ParsedType &ReceiverType) {
1842 ReceiverType = ParsedType();
Douglas Gregor1569f952010-04-21 20:38:13 +00001843
Douglas Gregor47bd5432010-04-14 02:46:37 +00001844 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor95f42922010-10-14 22:11:03 +00001845 // messaging super. If the identifier is "super" and there is a
1846 // trailing dot, it's an instance message.
1847 if (IsSuper && S->isInObjcMethodScope())
1848 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001849
1850 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1851 LookupName(Result, S);
1852
1853 switch (Result.getResultKind()) {
1854 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +00001855 // Normal name lookup didn't find anything. If we're in an
1856 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor95f42922010-10-14 22:11:03 +00001857 // FIXME: This is a hack. Ivar lookup should be part of normal
1858 // lookup.
Douglas Gregored464422010-04-19 20:09:36 +00001859 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidisccc9e762011-11-09 00:22:48 +00001860 if (!Method->getClassInterface()) {
1861 // Fall back: let the parser try to parse it as an instance message.
1862 return ObjCInstanceMessage;
1863 }
1864
Douglas Gregored464422010-04-19 20:09:36 +00001865 ObjCInterfaceDecl *ClassDeclared;
1866 if (Method->getClassInterface()->lookupInstanceVariable(Name,
1867 ClassDeclared))
1868 return ObjCInstanceMessage;
1869 }
Douglas Gregor95f42922010-10-14 22:11:03 +00001870
Douglas Gregor47bd5432010-04-14 02:46:37 +00001871 // Break out; we'll perform typo correction below.
1872 break;
1873
1874 case LookupResult::NotFoundInCurrentInstantiation:
1875 case LookupResult::FoundOverloaded:
1876 case LookupResult::FoundUnresolvedValue:
1877 case LookupResult::Ambiguous:
1878 Result.suppressDiagnostics();
1879 return ObjCInstanceMessage;
1880
1881 case LookupResult::Found: {
Fariborz Jahanian8348de32011-02-08 00:23:07 +00001882 // If the identifier is a class or not, and there is a trailing dot,
1883 // it's an instance message.
1884 if (HasTrailingDot)
1885 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001886 // We found something. If it's a type, then we have a class
1887 // message. Otherwise, it's an instance message.
1888 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +00001889 QualType T;
1890 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1891 T = Context.getObjCInterfaceType(Class);
Fariborz Jahanian740991b2013-04-04 18:45:52 +00001892 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
Douglas Gregor1569f952010-04-21 20:38:13 +00001893 T = Context.getTypeDeclType(Type);
Fariborz Jahanian740991b2013-04-04 18:45:52 +00001894 DiagnoseUseOfDecl(Type, NameLoc);
1895 }
1896 else
Douglas Gregor1569f952010-04-21 20:38:13 +00001897 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001898
Douglas Gregor1569f952010-04-21 20:38:13 +00001899 // We have a class message, and T is the type we're
1900 // messaging. Build source-location information for it.
1901 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +00001902 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregor1569f952010-04-21 20:38:13 +00001903 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001904 }
1905 }
1906
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001907 ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00001908 if (TypoCorrection Corrected =
1909 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1910 NULL, Validator, NULL, false, NULL, false)) {
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001911 if (Corrected.isKeyword()) {
1912 // If we've found the keyword "super" (the only keyword that would be
1913 // returned by CorrectTypo), this is a send to super.
Richard Smith2d670972013-08-17 00:46:16 +00001914 diagnoseTypo(Corrected,
1915 PDiag(diag::err_unknown_receiver_suggest) << Name);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001916 return ObjCSuperMessage;
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001917 } else if (ObjCInterfaceDecl *Class =
Richard Smith2d670972013-08-17 00:46:16 +00001918 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001919 // If we found a declaration, correct when it refers to an Objective-C
1920 // class.
Richard Smith2d670972013-08-17 00:46:16 +00001921 diagnoseTypo(Corrected,
1922 PDiag(diag::err_unknown_receiver_suggest) << Name);
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001923 QualType T = Context.getObjCInterfaceType(Class);
1924 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1925 ReceiverType = CreateParsedType(T, TSInfo);
1926 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001927 }
1928 }
Richard Smith2d670972013-08-17 00:46:16 +00001929
Douglas Gregor47bd5432010-04-14 02:46:37 +00001930 // Fall back: let the parser try to parse it as an instance message.
1931 return ObjCInstanceMessage;
1932}
Steve Naroff61f72cb2009-03-09 21:12:44 +00001933
John McCall60d7b3a2010-08-24 06:29:42 +00001934ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001935 SourceLocation SuperLoc,
1936 Selector Sel,
1937 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001938 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001939 SourceLocation RBracLoc,
1940 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001941 // Determine whether we are inside a method or not.
Eli Friedmanb942cb22012-02-03 22:47:37 +00001942 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregorf95861a2010-04-21 20:01:04 +00001943 if (!Method) {
1944 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1945 return ExprError();
1946 }
Chris Lattner85a932e2008-01-04 22:32:30 +00001947
Douglas Gregorf95861a2010-04-21 20:01:04 +00001948 ObjCInterfaceDecl *Class = Method->getClassInterface();
1949 if (!Class) {
1950 Diag(SuperLoc, diag::error_no_super_class_message)
1951 << Method->getDeclName();
1952 return ExprError();
1953 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001954
Douglas Gregorf95861a2010-04-21 20:01:04 +00001955 ObjCInterfaceDecl *Super = Class->getSuperClass();
1956 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001957 // The current class does not have a superclass.
Ted Kremeneke00909a2011-01-23 17:21:34 +00001958 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
1959 << Class->getIdentifier();
Douglas Gregor2725ca82010-04-21 19:57:20 +00001960 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +00001961 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001962
Douglas Gregorf95861a2010-04-21 20:01:04 +00001963 // We are in a method whose class has a superclass, so 'super'
1964 // is acting as a keyword.
Jordan Rose535a5d02012-10-19 16:05:26 +00001965 if (Method->getSelector() == Sel)
1966 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber9a1ecf02011-08-22 17:25:57 +00001967
Jordan Rose535a5d02012-10-19 16:05:26 +00001968 if (Method->isInstanceMethod()) {
Douglas Gregorf95861a2010-04-21 20:01:04 +00001969 // Since we are in an instance method, this is an instance
1970 // message to the superclass instance.
1971 QualType SuperTy = Context.getObjCInterfaceType(Super);
1972 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall9ae2f072010-08-23 23:25:46 +00001973 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001974 Sel, /*Method=*/0,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001975 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001976 }
Douglas Gregorf95861a2010-04-21 20:01:04 +00001977
1978 // Since we are in a class method, this is a class message to
1979 // the superclass.
1980 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1981 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001982 SuperLoc, Sel, /*Method=*/0,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001983 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001984}
1985
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001986
1987ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
1988 bool isSuperReceiver,
1989 SourceLocation Loc,
1990 Selector Sel,
1991 ObjCMethodDecl *Method,
1992 MultiExprArg Args) {
1993 TypeSourceInfo *receiverTypeInfo = 0;
1994 if (!ReceiverType.isNull())
1995 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
1996
1997 return BuildClassMessage(receiverTypeInfo, ReceiverType,
1998 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
1999 Sel, Method, Loc, Loc, Loc, Args,
2000 /*isImplicit=*/true);
2001
2002}
2003
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002004static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2005 unsigned DiagID,
2006 bool (*refactor)(const ObjCMessageExpr *,
2007 const NSAPI &, edit::Commit &)) {
2008 SourceLocation MsgLoc = Msg->getExprLoc();
2009 if (S.Diags.getDiagnosticLevel(DiagID, MsgLoc) == DiagnosticsEngine::Ignored)
2010 return;
2011
2012 SourceManager &SM = S.SourceMgr;
2013 edit::Commit ECommit(SM, S.LangOpts);
2014 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2015 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2016 << Msg->getSelector() << Msg->getSourceRange();
2017 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2018 if (!ECommit.isCommitable())
2019 return;
2020 for (edit::Commit::edit_iterator
2021 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2022 const edit::Commit::Edit &Edit = *I;
2023 switch (Edit.Kind) {
2024 case edit::Commit::Act_Insert:
2025 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2026 Edit.Text,
2027 Edit.BeforePrev));
2028 break;
2029 case edit::Commit::Act_InsertFromRange:
2030 Builder.AddFixItHint(
2031 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2032 Edit.getInsertFromRange(SM),
2033 Edit.BeforePrev));
2034 break;
2035 case edit::Commit::Act_Remove:
2036 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2037 break;
2038 }
2039 }
2040 }
2041}
2042
2043static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2044 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2045 edit::rewriteObjCRedundantCallWithLiteral);
2046}
2047
Douglas Gregor2725ca82010-04-21 19:57:20 +00002048/// \brief Build an Objective-C class message expression.
2049///
2050/// This routine takes care of both normal class messages and
2051/// class messages to the superclass.
2052///
2053/// \param ReceiverTypeInfo Type source information that describes the
2054/// receiver of this message. This may be NULL, in which case we are
2055/// sending to the superclass and \p SuperLoc must be a valid source
2056/// location.
2057
2058/// \param ReceiverType The type of the object receiving the
2059/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2060/// type as that refers to. For a superclass send, this is the type of
2061/// the superclass.
2062///
2063/// \param SuperLoc The location of the "super" keyword in a
2064/// superclass message.
2065///
2066/// \param Sel The selector to which the message is being sent.
2067///
Douglas Gregorf49bb082010-04-22 17:01:48 +00002068/// \param Method The method that this class message is invoking, if
2069/// already known.
2070///
Douglas Gregor2725ca82010-04-21 19:57:20 +00002071/// \param LBracLoc The location of the opening square bracket ']'.
2072///
James Dennettefce31f2012-06-22 08:10:18 +00002073/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor2725ca82010-04-21 19:57:20 +00002074///
James Dennettefce31f2012-06-22 08:10:18 +00002075/// \param ArgsIn The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00002076ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregor0fbda682010-09-15 14:51:05 +00002077 QualType ReceiverType,
2078 SourceLocation SuperLoc,
2079 Selector Sel,
2080 ObjCMethodDecl *Method,
2081 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002082 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor0fbda682010-09-15 14:51:05 +00002083 SourceLocation RBracLoc,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002084 MultiExprArg ArgsIn,
2085 bool isImplicit) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00002086 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregor9497a732010-09-16 01:51:54 +00002087 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor0fbda682010-09-15 14:51:05 +00002088 if (LBracLoc.isInvalid()) {
2089 Diag(Loc, diag::err_missing_open_square_message_send)
2090 << FixItHint::CreateInsertion(Loc, "[");
2091 LBracLoc = Loc;
2092 }
Argyrios Kyrtzidisf4d02392013-05-01 00:24:09 +00002093 SourceLocation SelLoc;
2094 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2095 SelLoc = SelectorLocs.front();
2096 else
2097 SelLoc = Loc;
2098
Douglas Gregor92e986e2010-04-22 16:44:27 +00002099 if (ReceiverType->isDependentType()) {
2100 // If the receiver type is dependent, we can't type-check anything
2101 // at this point. Build a dependent expression.
2102 unsigned NumArgs = ArgsIn.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00002103 Expr **Args = ArgsIn.data();
Douglas Gregor92e986e2010-04-22 16:44:27 +00002104 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCallf89e55a2010-11-18 06:31:45 +00002105 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
2106 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002107 Sel, SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002108 makeArrayRef(Args, NumArgs),RBracLoc,
2109 isImplicit));
Douglas Gregor92e986e2010-04-22 16:44:27 +00002110 }
Chris Lattner15faee12010-04-12 05:38:43 +00002111
Douglas Gregor2725ca82010-04-21 19:57:20 +00002112 // Find the class to which we are sending this message.
2113 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002114 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2115 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00002116 Diag(Loc, diag::err_invalid_receiver_class_message)
2117 << ReceiverType;
2118 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +00002119 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00002120 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanian43bcdb22011-10-15 19:18:36 +00002121 // objc++ diagnoses during typename annotation.
David Blaikie4e4d0842012-03-11 07:00:24 +00002122 if (!getLangOpts().CPlusPlus)
Argyrios Kyrtzidisf4d02392013-05-01 00:24:09 +00002123 (void)DiagnoseUseOfDecl(Class, SelLoc);
Douglas Gregor2725ca82010-04-21 19:57:20 +00002124 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +00002125 if (!Method) {
Douglas Gregorb3029962011-11-14 22:10:01 +00002126 SourceRange TypeRange
2127 = SuperLoc.isValid()? SourceRange(SuperLoc)
2128 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00002129 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikie4e4d0842012-03-11 07:00:24 +00002130 (getLangOpts().ObjCAutoRefCount
Douglas Gregord10099e2012-05-04 16:32:21 +00002131 ? diag::err_arc_receiver_forward_class
2132 : diag::warn_receiver_forward_class),
2133 TypeRange)) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00002134 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorf49bb082010-04-22 17:01:48 +00002135 Method = LookupFactoryMethodInGlobalPool(Sel,
2136 SourceRange(LBracLoc, RBracLoc));
David Blaikie4e4d0842012-03-11 07:00:24 +00002137 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorf49bb082010-04-22 17:01:48 +00002138 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2139 << Method->getDeclName();
2140 }
2141 if (!Method)
2142 Method = Class->lookupClassMethod(Sel);
2143
2144 // If we have an implementation in scope, check "private" methods.
2145 if (!Method)
Anna Zakse61354b2012-07-27 19:07:44 +00002146 Method = Class->lookupPrivateClassMethod(Sel);
Douglas Gregorf49bb082010-04-22 17:01:48 +00002147
Argyrios Kyrtzidisf4d02392013-05-01 00:24:09 +00002148 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Douglas Gregorf49bb082010-04-22 17:01:48 +00002149 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +00002150 }
Mike Stump1eb44332009-09-09 15:08:12 +00002151
Douglas Gregor2725ca82010-04-21 19:57:20 +00002152 // Check the argument types and determine the result type.
2153 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00002154 ExprValueKind VK = VK_RValue;
2155
Douglas Gregor2725ca82010-04-21 19:57:20 +00002156 unsigned NumArgs = ArgsIn.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00002157 Expr **Args = ArgsIn.data();
Dmitri Gribenko416c9b32013-05-10 00:27:15 +00002158 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2159 Sel, SelectorLocs,
Fariborz Jahanian376c4322012-08-31 17:03:18 +00002160 Method, true,
Douglas Gregor926df6c2011-06-11 01:09:30 +00002161 SuperLoc.isValid(), LBracLoc, RBracLoc,
2162 ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00002163 return ExprError();
Ted Kremenek4df728e2008-06-24 15:50:53 +00002164
Stephen Hines651f13c2014-04-23 16:59:28 -07002165 if (Method && !Method->getReturnType()->isVoidType() &&
2166 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregor483dd2f2011-01-11 03:23:19 +00002167 diag::err_illegal_message_expr_incomplete_type))
2168 return ExprError();
2169
Douglas Gregor2725ca82010-04-21 19:57:20 +00002170 // Construct the appropriate ObjCMessageExpr.
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002171 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00002172 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00002173 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00002174 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002175 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00002176 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002177 RBracLoc, isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002178 else {
John McCallf89e55a2010-11-18 06:31:45 +00002179 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002180 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00002181 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002182 RBracLoc, isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002183 if (!isImplicit)
2184 checkCocoaAPI(*this, Result);
2185 }
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00002186 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +00002187}
2188
Douglas Gregor2725ca82010-04-21 19:57:20 +00002189// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +00002190// ArgExprs is optional - if it is present, the number of expressions
2191// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00002192ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor77328d12010-09-15 23:19:31 +00002193 ParsedType Receiver,
2194 Selector Sel,
2195 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002196 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor77328d12010-09-15 23:19:31 +00002197 SourceLocation RBracLoc,
2198 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00002199 TypeSourceInfo *ReceiverTypeInfo;
2200 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2201 if (ReceiverType.isNull())
2202 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002203
Mike Stump1eb44332009-09-09 15:08:12 +00002204
Douglas Gregor2725ca82010-04-21 19:57:20 +00002205 if (!ReceiverTypeInfo)
2206 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2207
2208 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +00002209 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002210 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor2725ca82010-04-21 19:57:20 +00002211}
2212
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002213ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2214 QualType ReceiverType,
2215 SourceLocation Loc,
2216 Selector Sel,
2217 ObjCMethodDecl *Method,
2218 MultiExprArg Args) {
2219 return BuildInstanceMessage(Receiver, ReceiverType,
2220 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2221 Sel, Method, Loc, Loc, Loc, Args,
2222 /*isImplicit=*/true);
2223}
2224
Douglas Gregor2725ca82010-04-21 19:57:20 +00002225/// \brief Build an Objective-C instance message expression.
2226///
2227/// This routine takes care of both normal instance messages and
2228/// instance messages to the superclass instance.
2229///
2230/// \param Receiver The expression that computes the object that will
2231/// receive this message. This may be empty, in which case we are
2232/// sending to the superclass instance and \p SuperLoc must be a valid
2233/// source location.
2234///
2235/// \param ReceiverType The (static) type of the object receiving the
2236/// message. When a \p Receiver expression is provided, this is the
2237/// same type as that expression. For a superclass instance send, this
2238/// is a pointer to the type of the superclass.
2239///
2240/// \param SuperLoc The location of the "super" keyword in a
2241/// superclass instance message.
2242///
2243/// \param Sel The selector to which the message is being sent.
2244///
Douglas Gregorf49bb082010-04-22 17:01:48 +00002245/// \param Method The method that this instance message is invoking, if
2246/// already known.
2247///
Douglas Gregor2725ca82010-04-21 19:57:20 +00002248/// \param LBracLoc The location of the opening square bracket ']'.
2249///
James Dennettefce31f2012-06-22 08:10:18 +00002250/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor2725ca82010-04-21 19:57:20 +00002251///
James Dennettefce31f2012-06-22 08:10:18 +00002252/// \param ArgsIn The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00002253ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002254 QualType ReceiverType,
2255 SourceLocation SuperLoc,
2256 Selector Sel,
2257 ObjCMethodDecl *Method,
2258 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002259 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002260 SourceLocation RBracLoc,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002261 MultiExprArg ArgsIn,
2262 bool isImplicit) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00002263 // The location of the receiver.
2264 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
Argyrios Kyrtzidisf4d02392013-05-01 00:24:09 +00002265 SourceRange RecRange =
2266 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2267 SourceLocation SelLoc;
2268 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2269 SelLoc = SelectorLocs.front();
2270 else
2271 SelLoc = Loc;
2272
Douglas Gregor0fbda682010-09-15 14:51:05 +00002273 if (LBracLoc.isInvalid()) {
2274 Diag(Loc, diag::err_missing_open_square_message_send)
2275 << FixItHint::CreateInsertion(Loc, "[");
2276 LBracLoc = Loc;
2277 }
2278
Douglas Gregor2725ca82010-04-21 19:57:20 +00002279 // If we have a receiver expression, perform appropriate promotions
2280 // and determine receiver type.
Douglas Gregor2725ca82010-04-21 19:57:20 +00002281 if (Receiver) {
John McCall5acb0c92011-10-17 18:40:02 +00002282 if (Receiver->hasPlaceholderType()) {
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00002283 ExprResult Result;
2284 if (Receiver->getType() == Context.UnknownAnyTy)
2285 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2286 else
2287 Result = CheckPlaceholderExpr(Receiver);
2288 if (Result.isInvalid()) return ExprError();
2289 Receiver = Result.take();
John McCall5acb0c92011-10-17 18:40:02 +00002290 }
2291
Douglas Gregor92e986e2010-04-22 16:44:27 +00002292 if (Receiver->isTypeDependent()) {
2293 // If the receiver is type-dependent, we can't type-check anything
2294 // at this point. Build a dependent expression.
2295 unsigned NumArgs = ArgsIn.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00002296 Expr **Args = ArgsIn.data();
Douglas Gregor92e986e2010-04-22 16:44:27 +00002297 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2298 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00002299 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002300 SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00002301 makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002302 RBracLoc, isImplicit));
Douglas Gregor92e986e2010-04-22 16:44:27 +00002303 }
2304
Douglas Gregor2725ca82010-04-21 19:57:20 +00002305 // If necessary, apply function/array conversion to the receiver.
2306 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00002307 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2308 if (Result.isInvalid())
2309 return ExprError();
2310 Receiver = Result.take();
Douglas Gregor2725ca82010-04-21 19:57:20 +00002311 ReceiverType = Receiver->getType();
John McCall2fbe92c2013-03-01 09:20:14 +00002312
2313 // If the receiver is an ObjC pointer, a block pointer, or an
2314 // __attribute__((NSObject)) pointer, we don't need to do any
2315 // special conversion in order to look up a receiver.
2316 if (ReceiverType->isObjCRetainableType()) {
2317 // do nothing
2318 } else if (!getLangOpts().ObjCAutoRefCount &&
2319 !Context.getObjCIdType().isNull() &&
2320 (ReceiverType->isPointerType() ||
2321 ReceiverType->isIntegerType())) {
2322 // Implicitly convert integers and pointers to 'id' but emit a warning.
2323 // But not in ARC.
2324 Diag(Loc, diag::warn_bad_receiver_type)
2325 << ReceiverType
2326 << Receiver->getSourceRange();
2327 if (ReceiverType->isPointerType()) {
2328 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2329 CK_CPointerToObjCPointerCast).take();
2330 } else {
2331 // TODO: specialized warning on null receivers?
2332 bool IsNull = Receiver->isNullPointerConstant(Context,
2333 Expr::NPC_ValueDependentIsNull);
2334 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2335 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2336 Kind).take();
2337 }
2338 ReceiverType = Receiver->getType();
2339 } else if (getLangOpts().CPlusPlus) {
Douglas Gregor1ce55092013-11-07 22:34:54 +00002340 // The receiver must be a complete type.
2341 if (RequireCompleteType(Loc, Receiver->getType(),
2342 diag::err_incomplete_receiver_type))
2343 return ExprError();
2344
John McCall2fbe92c2013-03-01 09:20:14 +00002345 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2346 if (result.isUsable()) {
2347 Receiver = result.take();
2348 ReceiverType = Receiver->getType();
2349 }
2350 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00002351 }
2352
John McCall2fbe92c2013-03-01 09:20:14 +00002353 // There's a somewhat weird interaction here where we assume that we
2354 // won't actually have a method unless we also don't need to do some
2355 // of the more detailed type-checking on the receiver.
2356
Douglas Gregorf49bb082010-04-22 17:01:48 +00002357 if (!Method) {
2358 // Handle messages to id.
Fariborz Jahanianba551982010-08-10 18:10:50 +00002359 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002360 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorf49bb082010-04-22 17:01:48 +00002361 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2362 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002363 SourceRange(LBracLoc, RBracLoc),
2364 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00002365 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +00002366 Method = LookupFactoryMethodInGlobalPool(Sel,
Jordy Rosed2d06552012-05-12 17:32:52 +00002367 SourceRange(LBracLoc,RBracLoc),
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002368 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00002369 } else if (ReceiverType->isObjCClassType() ||
2370 ReceiverType->isObjCQualifiedClassType()) {
2371 // Handle messages to Class.
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002372 // We allow sending a message to a qualified Class ("Class<foo>"), which
2373 // is ok as long as one of the protocols implements the selector (if not, warn).
2374 if (const ObjCObjectPointerType *QClassTy
2375 = ReceiverType->getAsObjCQualifiedClassType()) {
2376 // Search protocols for class methods.
2377 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2378 if (!Method) {
2379 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2380 // warn if instance method found for a Class message.
2381 if (Method) {
Argyrios Kyrtzidisf4d02392013-05-01 00:24:09 +00002382 Diag(SelLoc, diag::warn_instance_method_on_class_found)
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002383 << Method->getSelector() << Sel;
Ted Kremenek3306ec12012-02-27 22:55:11 +00002384 Diag(Method->getLocation(), diag::note_method_declared_at)
2385 << Method->getDeclName();
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002386 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +00002387 }
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002388 } else {
2389 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2390 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2391 // First check the public methods in the class interface.
2392 Method = ClassDecl->lookupClassMethod(Sel);
2393
2394 if (!Method)
Anna Zakse61354b2012-07-27 19:07:44 +00002395 Method = ClassDecl->lookupPrivateClassMethod(Sel);
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002396 }
Argyrios Kyrtzidisf4d02392013-05-01 00:24:09 +00002397 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002398 return ExprError();
2399 }
2400 if (!Method) {
2401 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregorc737acb2011-09-27 16:10:05 +00002402 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002403 Method = LookupFactoryMethodInGlobalPool(Sel,
2404 SourceRange(LBracLoc, RBracLoc),
2405 true);
2406 if (!Method) {
2407 // If no class (factory) method was found, check if an _instance_
2408 // method of the same name exists in the root class only.
2409 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002410 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002411 true);
2412 if (Method)
2413 if (const ObjCInterfaceDecl *ID =
2414 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2415 if (ID->getSuperClass())
Argyrios Kyrtzidisf4d02392013-05-01 00:24:09 +00002416 Diag(SelLoc, diag::warn_root_inst_method_not_found)
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002417 << Sel << SourceRange(LBracLoc, RBracLoc);
2418 }
2419 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002420 }
2421 }
2422 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002423 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +00002424 ObjCInterfaceDecl* ClassDecl = 0;
2425
2426 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2427 // long as one of the protocols implements the selector (if not, warn).
Fariborz Jahanian33e6c2d2012-06-23 18:39:57 +00002428 // And as long as message is not deprecated/unavailable (warn if it is).
Douglas Gregorf49bb082010-04-22 17:01:48 +00002429 if (const ObjCObjectPointerType *QIdTy
2430 = ReceiverType->getAsObjCQualifiedIdType()) {
2431 // Search protocols for instance methods.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00002432 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2433 if (!Method)
2434 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Argyrios Kyrtzidisf4d02392013-05-01 00:24:09 +00002435 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahanian33e6c2d2012-06-23 18:39:57 +00002436 return ExprError();
Douglas Gregorf49bb082010-04-22 17:01:48 +00002437 } else if (const ObjCObjectPointerType *OCIType
2438 = ReceiverType->getAsObjCInterfacePointerType()) {
2439 // We allow sending a message to a pointer to an interface (an object).
2440 ClassDecl = OCIType->getInterfaceDecl();
John McCallf85e1932011-06-15 23:02:42 +00002441
Douglas Gregorb3029962011-11-14 22:10:01 +00002442 // Try to complete the type. Under ARC, this is a hard error from which
2443 // we don't try to recover.
2444 const ObjCInterfaceDecl *forwardClass = 0;
2445 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002446 getLangOpts().ObjCAutoRefCount
Douglas Gregord10099e2012-05-04 16:32:21 +00002447 ? diag::err_arc_receiver_forward_instance
2448 : diag::warn_receiver_forward_instance,
2449 Receiver? Receiver->getSourceRange()
2450 : SourceRange(SuperLoc))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002451 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregorb3029962011-11-14 22:10:01 +00002452 return ExprError();
2453
2454 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanian4cc9b102012-02-03 01:02:44 +00002455 Diag(Receiver ? Receiver->getLocStart()
2456 : SuperLoc, diag::note_receiver_is_id);
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00002457 Method = 0;
2458 } else {
2459 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCallf85e1932011-06-15 23:02:42 +00002460 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00002461
Fariborz Jahanian27569b02011-03-09 22:17:12 +00002462 if (!Method)
Douglas Gregorf49bb082010-04-22 17:01:48 +00002463 // Search protocol qualifiers.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00002464 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2465
Douglas Gregorf49bb082010-04-22 17:01:48 +00002466 if (!Method) {
2467 // If we have implementations in scope, check "private" methods.
Anna Zakse61354b2012-07-27 19:07:44 +00002468 Method = ClassDecl->lookupPrivateMethod(Sel);
Douglas Gregorf49bb082010-04-22 17:01:48 +00002469
David Blaikie4e4d0842012-03-11 07:00:24 +00002470 if (!Method && getLangOpts().ObjCAutoRefCount) {
Argyrios Kyrtzidisf4d02392013-05-01 00:24:09 +00002471 Diag(SelLoc, diag::err_arc_may_not_respond)
2472 << OCIType->getPointeeType() << Sel << RecRange
Fariborz Jahanian84c75192012-11-28 01:27:44 +00002473 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
John McCallf85e1932011-06-15 23:02:42 +00002474 return ExprError();
2475 }
2476
Douglas Gregorc737acb2011-09-27 16:10:05 +00002477 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00002478 // If we still haven't found a method, look in the global pool. This
2479 // behavior isn't very desirable, however we need it for GCC
2480 // compatibility. FIXME: should we deviate??
2481 if (OCIType->qual_empty()) {
2482 Method = LookupInstanceMethodInGlobalPool(Sel,
Jordy Rosed2d06552012-05-12 17:32:52 +00002483 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00002484 if (Method && !forwardClass)
Argyrios Kyrtzidisf4d02392013-05-01 00:24:09 +00002485 Diag(SelLoc, diag::warn_maynot_respond)
2486 << OCIType->getInterfaceDecl()->getIdentifier()
2487 << Sel << RecRange;
Douglas Gregorf49bb082010-04-22 17:01:48 +00002488 }
2489 }
2490 }
Argyrios Kyrtzidisf4d02392013-05-01 00:24:09 +00002491 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
Douglas Gregorf49bb082010-04-22 17:01:48 +00002492 return ExprError();
John McCall0bcc9bc2011-09-09 06:11:02 +00002493 } else {
John McCall2fbe92c2013-03-01 09:20:14 +00002494 // Reject other random receiver types (e.g. structs).
2495 Diag(Loc, diag::err_bad_receiver_type)
2496 << ReceiverType << Receiver->getSourceRange();
2497 return ExprError();
Douglas Gregorf49bb082010-04-22 17:01:48 +00002498 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002499 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00002500 }
Mike Stump1eb44332009-09-09 15:08:12 +00002501
Stephen Hines651f13c2014-04-23 16:59:28 -07002502 FunctionScopeInfo *DIFunctionScopeInfo =
2503 (Method && Method->getMethodFamily() == OMF_init)
2504 ? getEnclosingFunction() : 0;
2505
2506 if (DIFunctionScopeInfo &&
2507 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
2508 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2509 bool isDesignatedInitChain = false;
2510 if (SuperLoc.isValid()) {
2511 if (const ObjCObjectPointerType *
2512 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2513 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
2514 // Either we know this is a designated initializer or we
2515 // conservatively assume it because we don't know for sure.
2516 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2517 ID->isDesignatedInitializer(Sel)) {
2518 isDesignatedInitChain = true;
2519 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
2520 }
2521 }
2522 }
2523 }
2524 if (!isDesignatedInitChain) {
2525 const ObjCMethodDecl *InitMethod = 0;
2526 bool isDesignated =
2527 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2528 assert(isDesignated && InitMethod);
2529 (void)isDesignated;
2530 Diag(SelLoc, SuperLoc.isValid() ?
2531 diag::warn_objc_designated_init_non_designated_init_call :
2532 diag::warn_objc_designated_init_non_super_designated_init_call);
2533 Diag(InitMethod->getLocation(),
2534 diag::note_objc_designated_init_marked_here);
2535 }
2536 }
2537
2538 if (DIFunctionScopeInfo &&
2539 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
2540 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2541 if (SuperLoc.isValid()) {
2542 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2543 } else {
2544 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
2545 }
2546 }
2547
Douglas Gregor2725ca82010-04-21 19:57:20 +00002548 // Check the message arguments.
2549 unsigned NumArgs = ArgsIn.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00002550 Expr **Args = ArgsIn.data();
Douglas Gregor2725ca82010-04-21 19:57:20 +00002551 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00002552 ExprValueKind VK = VK_RValue;
Fariborz Jahanian26005032010-12-01 01:07:24 +00002553 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2554 ReceiverType->isObjCQualifiedClassType());
Dmitri Gribenko416c9b32013-05-10 00:27:15 +00002555 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2556 Sel, SelectorLocs, Method,
Douglas Gregor926df6c2011-06-11 01:09:30 +00002557 ClassMessage, SuperLoc.isValid(),
John McCallf89e55a2010-11-18 06:31:45 +00002558 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00002559 return ExprError();
Stephen Hines651f13c2014-04-23 16:59:28 -07002560
2561 if (Method && !Method->getReturnType()->isVoidType() &&
2562 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregor483dd2f2011-01-11 03:23:19 +00002563 diag::err_illegal_message_expr_incomplete_type))
2564 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002565
John McCallf85e1932011-06-15 23:02:42 +00002566 // In ARC, forbid the user from sending messages to
2567 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikie4e4d0842012-03-11 07:00:24 +00002568 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00002569 ObjCMethodFamily family =
2570 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2571 switch (family) {
2572 case OMF_init:
2573 if (Method)
2574 checkInitMethod(Method, ReceiverType);
2575
2576 case OMF_None:
2577 case OMF_alloc:
2578 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +00002579 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +00002580 case OMF_mutableCopy:
2581 case OMF_new:
2582 case OMF_self:
2583 break;
2584
2585 case OMF_dealloc:
2586 case OMF_retain:
2587 case OMF_release:
2588 case OMF_autorelease:
2589 case OMF_retainCount:
Argyrios Kyrtzidisf4d02392013-05-01 00:24:09 +00002590 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
2591 << Sel << RecRange;
John McCallf85e1932011-06-15 23:02:42 +00002592 break;
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002593
2594 case OMF_performSelector:
2595 if (Method && NumArgs >= 1) {
2596 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2597 Selector ArgSel = SelExp->getSelector();
2598 ObjCMethodDecl *SelMethod =
2599 LookupInstanceMethodInGlobalPool(ArgSel,
2600 SelExp->getSourceRange());
2601 if (!SelMethod)
2602 SelMethod =
2603 LookupFactoryMethodInGlobalPool(ArgSel,
2604 SelExp->getSourceRange());
2605 if (SelMethod) {
2606 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2607 switch (SelFamily) {
2608 case OMF_alloc:
2609 case OMF_copy:
2610 case OMF_mutableCopy:
2611 case OMF_new:
2612 case OMF_self:
2613 case OMF_init:
2614 // Issue error, unless ns_returns_not_retained.
2615 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2616 // selector names a +1 method
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002617 Diag(SelLoc,
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002618 diag::err_arc_perform_selector_retains);
Ted Kremenek3306ec12012-02-27 22:55:11 +00002619 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2620 << SelMethod->getDeclName();
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002621 }
2622 break;
2623 default:
2624 // +0 call. OK. unless ns_returns_retained.
2625 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2626 // selector names a +1 method
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002627 Diag(SelLoc,
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002628 diag::err_arc_perform_selector_retains);
Ted Kremenek3306ec12012-02-27 22:55:11 +00002629 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2630 << SelMethod->getDeclName();
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002631 }
2632 break;
2633 }
2634 }
2635 } else {
2636 // error (may leak).
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002637 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002638 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2639 }
2640 }
2641 break;
John McCallf85e1932011-06-15 23:02:42 +00002642 }
2643 }
2644
Douglas Gregor2725ca82010-04-21 19:57:20 +00002645 // Construct the appropriate ObjCMessageExpr instance.
John McCallf85e1932011-06-15 23:02:42 +00002646 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00002647 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00002648 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00002649 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002650 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002651 makeArrayRef(Args, NumArgs), RBracLoc,
2652 isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002653 else {
John McCallf89e55a2010-11-18 06:31:45 +00002654 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002655 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002656 makeArrayRef(Args, NumArgs), RBracLoc,
2657 isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002658 if (!isImplicit)
2659 checkCocoaAPI(*this, Result);
2660 }
John McCallf85e1932011-06-15 23:02:42 +00002661
David Blaikie4e4d0842012-03-11 07:00:24 +00002662 if (getLangOpts().ObjCAutoRefCount) {
Fariborz Jahanian98795562012-04-19 23:49:39 +00002663 DiagnoseARCUseOfWeakReceiver(*this, Receiver);
Fariborz Jahanian878f8502012-04-04 20:05:25 +00002664
John McCallf85e1932011-06-15 23:02:42 +00002665 // In ARC, annotate delegate init calls.
2666 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregorc737acb2011-09-27 16:10:05 +00002667 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCallf85e1932011-06-15 23:02:42 +00002668 // Only consider init calls *directly* in init implementations,
2669 // not within blocks.
2670 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2671 if (method && method->getMethodFamily() == OMF_init) {
2672 // The implicit assignment to self means we also don't want to
2673 // consume the result.
2674 Result->setDelegateInitCall(true);
2675 return Owned(Result);
2676 }
2677 }
2678
2679 // In ARC, check for message sends which are likely to introduce
2680 // retain cycles.
2681 checkRetainCycles(Result);
Jordan Rose7fffce72012-10-11 16:06:21 +00002682
2683 if (!isImplicit && Method) {
2684 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
2685 bool IsWeak =
2686 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
2687 if (!IsWeak && Sel.isUnarySelector())
2688 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
2689
2690 if (IsWeak) {
2691 DiagnosticsEngine::Level Level =
2692 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
2693 LBracLoc);
2694 if (Level != DiagnosticsEngine::Ignored)
2695 getCurFunction()->recordUseOfWeak(Result, Prop);
2696
2697 }
2698 }
2699 }
John McCallf85e1932011-06-15 23:02:42 +00002700 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002701
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00002702 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00002703}
2704
Fariborz Jahanian48f3cc22013-01-22 18:35:43 +00002705static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
2706 if (ObjCSelectorExpr *OSE =
2707 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
2708 Selector Sel = OSE->getSelector();
2709 SourceLocation Loc = OSE->getAtLoc();
2710 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
2711 = S.ReferencedSelectors.find(Sel);
2712 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
2713 S.ReferencedSelectors.erase(Pos);
2714 }
2715}
2716
Douglas Gregor2725ca82010-04-21 19:57:20 +00002717// ActOnInstanceMessage - used for both unary and keyword messages.
2718// ArgExprs is optional - if it is present, the number of expressions
2719// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00002720ExprResult Sema::ActOnInstanceMessage(Scope *S,
2721 Expr *Receiver,
2722 Selector Sel,
2723 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002724 ArrayRef<SourceLocation> SelectorLocs,
John McCall60d7b3a2010-08-24 06:29:42 +00002725 SourceLocation RBracLoc,
2726 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00002727 if (!Receiver)
2728 return ExprError();
Argyrios Kyrtzidisdb546fa2013-02-15 18:34:15 +00002729
2730 // A ParenListExpr can show up while doing error recovery with invalid code.
2731 if (isa<ParenListExpr>(Receiver)) {
2732 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
2733 if (Result.isInvalid()) return ExprError();
2734 Receiver = Result.take();
2735 }
Fariborz Jahanian35480682013-01-22 19:05:17 +00002736
2737 if (RespondsToSelectorSel.isNull()) {
2738 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
2739 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
2740 }
2741 if (Sel == RespondsToSelectorSel)
Fariborz Jahanian48f3cc22013-01-22 18:35:43 +00002742 RemoveSelectorFromWarningCache(*this, Args[0]);
2743
John McCall9ae2f072010-08-23 23:25:46 +00002744 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00002745 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002746 LBracLoc, SelectorLocs, RBracLoc, Args);
Chris Lattner85a932e2008-01-04 22:32:30 +00002747}
Chris Lattnereca7be62008-04-07 05:30:13 +00002748
John McCallf85e1932011-06-15 23:02:42 +00002749enum ARCConversionTypeClass {
John McCall2cf031d2011-10-01 01:01:08 +00002750 /// int, void, struct A
John McCallf85e1932011-06-15 23:02:42 +00002751 ACTC_none,
John McCall2cf031d2011-10-01 01:01:08 +00002752
2753 /// id, void (^)()
John McCallf85e1932011-06-15 23:02:42 +00002754 ACTC_retainable,
John McCall2cf031d2011-10-01 01:01:08 +00002755
2756 /// id*, id***, void (^*)(),
2757 ACTC_indirectRetainable,
2758
2759 /// void* might be a normal C type, or it might a CF type.
2760 ACTC_voidPtr,
2761
2762 /// struct A*
2763 ACTC_coreFoundation
John McCallf85e1932011-06-15 23:02:42 +00002764};
John McCall2cf031d2011-10-01 01:01:08 +00002765static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2766 return (ACTC == ACTC_retainable ||
2767 ACTC == ACTC_coreFoundation ||
2768 ACTC == ACTC_voidPtr);
2769}
2770static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2771 return ACTC == ACTC_none ||
2772 ACTC == ACTC_voidPtr ||
2773 ACTC == ACTC_coreFoundation;
2774}
2775
John McCallf85e1932011-06-15 23:02:42 +00002776static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCall2cf031d2011-10-01 01:01:08 +00002777 bool isIndirect = false;
John McCallf85e1932011-06-15 23:02:42 +00002778
2779 // Ignore an outermost reference type.
John McCall2cf031d2011-10-01 01:01:08 +00002780 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCallf85e1932011-06-15 23:02:42 +00002781 type = ref->getPointeeType();
John McCall2cf031d2011-10-01 01:01:08 +00002782 isIndirect = true;
2783 }
John McCallf85e1932011-06-15 23:02:42 +00002784
2785 // Drill through pointers and arrays recursively.
2786 while (true) {
2787 if (const PointerType *ptr = type->getAs<PointerType>()) {
2788 type = ptr->getPointeeType();
John McCall2cf031d2011-10-01 01:01:08 +00002789
2790 // The first level of pointer may be the innermost pointer on a CF type.
2791 if (!isIndirect) {
2792 if (type->isVoidType()) return ACTC_voidPtr;
2793 if (type->isRecordType()) return ACTC_coreFoundation;
2794 }
John McCallf85e1932011-06-15 23:02:42 +00002795 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2796 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2797 } else {
2798 break;
2799 }
John McCall2cf031d2011-10-01 01:01:08 +00002800 isIndirect = true;
John McCallf85e1932011-06-15 23:02:42 +00002801 }
2802
John McCall2cf031d2011-10-01 01:01:08 +00002803 if (isIndirect) {
2804 if (type->isObjCARCBridgableType())
2805 return ACTC_indirectRetainable;
2806 return ACTC_none;
2807 }
2808
2809 if (type->isObjCARCBridgableType())
2810 return ACTC_retainable;
2811
2812 return ACTC_none;
John McCallf85e1932011-06-15 23:02:42 +00002813}
2814
2815namespace {
John McCall2cf031d2011-10-01 01:01:08 +00002816 /// A result from the cast checker.
2817 enum ACCResult {
2818 /// Cannot be casted.
2819 ACC_invalid,
2820
2821 /// Can be safely retained or not retained.
2822 ACC_bottom,
2823
2824 /// Can be casted at +0.
2825 ACC_plusZero,
2826
2827 /// Can be casted at +1.
2828 ACC_plusOne
2829 };
2830 ACCResult merge(ACCResult left, ACCResult right) {
2831 if (left == right) return left;
2832 if (left == ACC_bottom) return right;
2833 if (right == ACC_bottom) return left;
2834 return ACC_invalid;
2835 }
2836
2837 /// A checker which white-lists certain expressions whose conversion
2838 /// to or from retainable type would otherwise be forbidden in ARC.
2839 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2840 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2841
John McCallf85e1932011-06-15 23:02:42 +00002842 ASTContext &Context;
John McCall2cf031d2011-10-01 01:01:08 +00002843 ARCConversionTypeClass SourceClass;
2844 ARCConversionTypeClass TargetClass;
Fariborz Jahanian533b34f2012-07-27 22:37:07 +00002845 bool Diagnose;
John McCall2cf031d2011-10-01 01:01:08 +00002846
2847 static bool isCFType(QualType type) {
2848 // Someday this can use ns_bridged. For now, it has to do this.
2849 return type->isCARCBridgableType();
John McCallf85e1932011-06-15 23:02:42 +00002850 }
John McCall2cf031d2011-10-01 01:01:08 +00002851
2852 public:
2853 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
Fariborz Jahanian533b34f2012-07-27 22:37:07 +00002854 ARCConversionTypeClass target, bool diagnose)
2855 : Context(Context), SourceClass(source), TargetClass(target),
2856 Diagnose(diagnose) {}
John McCall2cf031d2011-10-01 01:01:08 +00002857
2858 using super::Visit;
2859 ACCResult Visit(Expr *e) {
2860 return super::Visit(e->IgnoreParens());
2861 }
2862
2863 ACCResult VisitStmt(Stmt *s) {
2864 return ACC_invalid;
2865 }
2866
2867 /// Null pointer constants can be casted however you please.
2868 ACCResult VisitExpr(Expr *e) {
2869 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2870 return ACC_bottom;
2871 return ACC_invalid;
2872 }
2873
2874 /// Objective-C string literals can be safely casted.
2875 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2876 // If we're casting to any retainable type, go ahead. Global
2877 // strings are immune to retains, so this is bottom.
2878 if (isAnyRetainable(TargetClass)) return ACC_bottom;
2879
2880 return ACC_invalid;
John McCallf85e1932011-06-15 23:02:42 +00002881 }
2882
John McCall2cf031d2011-10-01 01:01:08 +00002883 /// Look through certain implicit and explicit casts.
2884 ACCResult VisitCastExpr(CastExpr *e) {
John McCallf85e1932011-06-15 23:02:42 +00002885 switch (e->getCastKind()) {
2886 case CK_NullToPointer:
John McCall2cf031d2011-10-01 01:01:08 +00002887 return ACC_bottom;
2888
John McCallf85e1932011-06-15 23:02:42 +00002889 case CK_NoOp:
2890 case CK_LValueToRValue:
2891 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002892 case CK_CPointerToObjCPointerCast:
2893 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00002894 case CK_AnyPointerToBlockPointerCast:
2895 return Visit(e->getSubExpr());
John McCall2cf031d2011-10-01 01:01:08 +00002896
John McCallf85e1932011-06-15 23:02:42 +00002897 default:
John McCall2cf031d2011-10-01 01:01:08 +00002898 return ACC_invalid;
John McCallf85e1932011-06-15 23:02:42 +00002899 }
2900 }
John McCall2cf031d2011-10-01 01:01:08 +00002901
2902 /// Look through unary extension.
2903 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCallf85e1932011-06-15 23:02:42 +00002904 return Visit(e->getSubExpr());
2905 }
John McCall2cf031d2011-10-01 01:01:08 +00002906
2907 /// Ignore the LHS of a comma operator.
2908 ACCResult VisitBinComma(BinaryOperator *e) {
John McCallf85e1932011-06-15 23:02:42 +00002909 return Visit(e->getRHS());
2910 }
John McCall2cf031d2011-10-01 01:01:08 +00002911
2912 /// Conditional operators are okay if both sides are okay.
2913 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
2914 ACCResult left = Visit(e->getTrueExpr());
2915 if (left == ACC_invalid) return ACC_invalid;
2916 return merge(left, Visit(e->getFalseExpr()));
John McCallf85e1932011-06-15 23:02:42 +00002917 }
John McCall2cf031d2011-10-01 01:01:08 +00002918
John McCall4b9c2d22011-11-06 09:01:30 +00002919 /// Look through pseudo-objects.
2920 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
2921 // If we're getting here, we should always have a result.
2922 return Visit(e->getResultExpr());
2923 }
2924
John McCall2cf031d2011-10-01 01:01:08 +00002925 /// Statement expressions are okay if their result expression is okay.
2926 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCallf85e1932011-06-15 23:02:42 +00002927 return Visit(e->getSubStmt()->body_back());
2928 }
John McCallf85e1932011-06-15 23:02:42 +00002929
John McCall2cf031d2011-10-01 01:01:08 +00002930 /// Some declaration references are okay.
2931 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
2932 // References to global constants from system headers are okay.
2933 // These are things like 'kCFStringTransformToLatin'. They are
2934 // can also be assumed to be immune to retains.
2935 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
2936 if (isAnyRetainable(TargetClass) &&
2937 isAnyRetainable(SourceClass) &&
2938 var &&
2939 var->getStorageClass() == SC_Extern &&
2940 var->getType().isConstQualified() &&
2941 Context.getSourceManager().isInSystemHeader(var->getLocation())) {
2942 return ACC_bottom;
2943 }
2944
2945 // Nothing else.
2946 return ACC_invalid;
Fariborz Jahanianaf975172011-06-21 17:38:29 +00002947 }
John McCall2cf031d2011-10-01 01:01:08 +00002948
2949 /// Some calls are okay.
2950 ACCResult VisitCallExpr(CallExpr *e) {
2951 if (FunctionDecl *fn = e->getDirectCallee())
2952 if (ACCResult result = checkCallToFunction(fn))
2953 return result;
2954
2955 return super::VisitCallExpr(e);
2956 }
2957
2958 ACCResult checkCallToFunction(FunctionDecl *fn) {
2959 // Require a CF*Ref return type.
Stephen Hines651f13c2014-04-23 16:59:28 -07002960 if (!isCFType(fn->getReturnType()))
John McCall2cf031d2011-10-01 01:01:08 +00002961 return ACC_invalid;
2962
2963 if (!isAnyRetainable(TargetClass))
2964 return ACC_invalid;
2965
2966 // Honor an explicit 'not retained' attribute.
2967 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
2968 return ACC_plusZero;
2969
2970 // Honor an explicit 'retained' attribute, except that for
2971 // now we're not going to permit implicit handling of +1 results,
2972 // because it's a bit frightening.
2973 if (fn->hasAttr<CFReturnsRetainedAttr>())
Fariborz Jahanian24b2ab72012-07-27 23:55:46 +00002974 return Diagnose ? ACC_plusOne
2975 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCall2cf031d2011-10-01 01:01:08 +00002976
2977 // Recognize this specific builtin function, which is used by CFSTR.
2978 unsigned builtinID = fn->getBuiltinID();
2979 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
2980 return ACC_bottom;
2981
Fariborz Jahanian24b2ab72012-07-27 23:55:46 +00002982 // Otherwise, don't do anything implicit with an unaudited function.
2983 if (!fn->hasAttr<CFAuditedTransferAttr>())
2984 return ACC_invalid;
2985
Fariborz Jahanian533b34f2012-07-27 22:37:07 +00002986 // Otherwise, it's +0 unless it follows the create convention.
2987 if (ento::coreFoundation::followsCreateRule(fn))
2988 return Diagnose ? ACC_plusOne
2989 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCall2cf031d2011-10-01 01:01:08 +00002990
John McCall2cf031d2011-10-01 01:01:08 +00002991 return ACC_plusZero;
2992 }
2993
2994 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
2995 return checkCallToMethod(e->getMethodDecl());
2996 }
2997
2998 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
2999 ObjCMethodDecl *method;
3000 if (e->isExplicitProperty())
3001 method = e->getExplicitProperty()->getGetterMethodDecl();
3002 else
3003 method = e->getImplicitPropertyGetter();
3004 return checkCallToMethod(method);
3005 }
3006
3007 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3008 if (!method) return ACC_invalid;
3009
3010 // Check for message sends to functions returning CF types. We
3011 // just obey the Cocoa conventions with these, even though the
3012 // return type is CF.
Stephen Hines651f13c2014-04-23 16:59:28 -07003013 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
John McCall2cf031d2011-10-01 01:01:08 +00003014 return ACC_invalid;
3015
3016 // If the method is explicitly marked not-retained, it's +0.
3017 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3018 return ACC_plusZero;
3019
3020 // If the method is explicitly marked as returning retained, or its
3021 // selector follows a +1 Cocoa convention, treat it as +1.
3022 if (method->hasAttr<CFReturnsRetainedAttr>())
3023 return ACC_plusOne;
3024
3025 switch (method->getSelector().getMethodFamily()) {
3026 case OMF_alloc:
3027 case OMF_copy:
3028 case OMF_mutableCopy:
3029 case OMF_new:
3030 return ACC_plusOne;
3031
3032 default:
3033 // Otherwise, treat it as +0.
3034 return ACC_plusZero;
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00003035 }
3036 }
John McCall2cf031d2011-10-01 01:01:08 +00003037 };
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00003038}
3039
Argyrios Kyrtzidis684190b2012-06-01 00:10:47 +00003040bool Sema::isKnownName(StringRef name) {
3041 if (name.empty())
3042 return false;
3043 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003044 Sema::LookupOrdinaryName);
Argyrios Kyrtzidis684190b2012-06-01 00:10:47 +00003045 return LookupName(R, TUScope, false);
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003046}
3047
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00003048static void addFixitForObjCARCConversion(Sema &S,
3049 DiagnosticBuilder &DiagB,
3050 Sema::CheckedConversionKind CCK,
3051 SourceLocation afterLParen,
3052 QualType castType,
3053 Expr *castExpr,
Fariborz Jahanianf799ae12013-02-22 22:02:53 +00003054 Expr *realCast,
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00003055 const char *bridgeKeyword,
3056 const char *CFBridgeName) {
3057 // We handle C-style and implicit casts here.
3058 switch (CCK) {
3059 case Sema::CCK_ImplicitConversion:
3060 case Sema::CCK_CStyleCast:
Fariborz Jahanianf799ae12013-02-22 22:02:53 +00003061 case Sema::CCK_OtherCast:
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00003062 break;
3063 case Sema::CCK_FunctionalCast:
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00003064 return;
3065 }
3066
3067 if (CFBridgeName) {
Fariborz Jahanianf799ae12013-02-22 22:02:53 +00003068 if (CCK == Sema::CCK_OtherCast) {
3069 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3070 SourceRange range(NCE->getOperatorLoc(),
3071 NCE->getAngleBrackets().getEnd());
3072 SmallString<32> BridgeCall;
3073
3074 SourceManager &SM = S.getSourceManager();
3075 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3076 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3077 BridgeCall += ' ';
3078
3079 BridgeCall += CFBridgeName;
3080 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3081 }
3082 return;
3083 }
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00003084 Expr *castedE = castExpr;
3085 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3086 castedE = CCE->getSubExpr();
3087 castedE = castedE->IgnoreImpCasts();
3088 SourceRange range = castedE->getSourceRange();
Jordan Rosed880b3a2012-06-07 01:10:31 +00003089
3090 SmallString<32> BridgeCall;
3091
3092 SourceManager &SM = S.getSourceManager();
3093 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3094 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3095 BridgeCall += ' ';
3096
3097 BridgeCall += CFBridgeName;
3098
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00003099 if (isa<ParenExpr>(castedE)) {
3100 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rosed880b3a2012-06-07 01:10:31 +00003101 BridgeCall));
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00003102 } else {
Jordan Rosed880b3a2012-06-07 01:10:31 +00003103 BridgeCall += '(';
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00003104 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rosed880b3a2012-06-07 01:10:31 +00003105 BridgeCall));
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00003106 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3107 S.PP.getLocForEndOfToken(range.getEnd()),
3108 ")"));
3109 }
3110 return;
3111 }
3112
3113 if (CCK == Sema::CCK_CStyleCast) {
3114 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
Fariborz Jahanianf799ae12013-02-22 22:02:53 +00003115 } else if (CCK == Sema::CCK_OtherCast) {
3116 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3117 std::string castCode = "(";
3118 castCode += bridgeKeyword;
3119 castCode += castType.getAsString();
3120 castCode += ")";
3121 SourceRange Range(NCE->getOperatorLoc(),
3122 NCE->getAngleBrackets().getEnd());
3123 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3124 }
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00003125 } else {
3126 std::string castCode = "(";
3127 castCode += bridgeKeyword;
3128 castCode += castType.getAsString();
3129 castCode += ")";
3130 Expr *castedE = castExpr->IgnoreImpCasts();
3131 SourceRange range = castedE->getSourceRange();
3132 if (isa<ParenExpr>(castedE)) {
3133 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3134 castCode));
3135 } else {
3136 castCode += "(";
3137 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3138 castCode));
3139 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3140 S.PP.getLocForEndOfToken(range.getEnd()),
3141 ")"));
3142 }
3143 }
3144}
3145
Stephen Hines651f13c2014-04-23 16:59:28 -07003146template <typename T>
3147static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3148 TypedefNameDecl *TDNDecl = TD->getDecl();
3149 QualType QT = TDNDecl->getUnderlyingType();
3150 if (QT->isPointerType()) {
3151 QT = QT->getPointeeType();
3152 if (const RecordType *RT = QT->getAs<RecordType>())
3153 if (RecordDecl *RD = RT->getDecl())
3154 return RD->getAttr<T>();
3155 }
3156 return 0;
3157}
3158
3159static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3160 TypedefNameDecl *&TDNDecl) {
3161 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3162 TDNDecl = TD->getDecl();
3163 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3164 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3165 return ObjCBAttr;
3166 T = TDNDecl->getUnderlyingType();
3167 }
3168 return 0;
3169}
3170
John McCall5acb0c92011-10-17 18:40:02 +00003171static void
3172diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3173 QualType castType, ARCConversionTypeClass castACTC,
Fariborz Jahanianf799ae12013-02-22 22:02:53 +00003174 Expr *castExpr, Expr *realCast,
3175 ARCConversionTypeClass exprACTC,
John McCall5acb0c92011-10-17 18:40:02 +00003176 Sema::CheckedConversionKind CCK) {
John McCallf85e1932011-06-15 23:02:42 +00003177 SourceLocation loc =
John McCall2cf031d2011-10-01 01:01:08 +00003178 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCallf85e1932011-06-15 23:02:42 +00003179
John McCall5acb0c92011-10-17 18:40:02 +00003180 if (S.makeUnavailableInSystemHeader(loc,
John McCall2cf031d2011-10-01 01:01:08 +00003181 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCallf85e1932011-06-15 23:02:42 +00003182 return;
John McCall5acb0c92011-10-17 18:40:02 +00003183
3184 QualType castExprType = castExpr->getType();
Stephen Hines651f13c2014-04-23 16:59:28 -07003185 TypedefNameDecl *TDNDecl = 0;
3186 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3187 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3188 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
3189 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
3190 return;
John McCallf85e1932011-06-15 23:02:42 +00003191
John McCall71c482c2011-06-17 06:50:50 +00003192 unsigned srcKind = 0;
John McCallf85e1932011-06-15 23:02:42 +00003193 switch (exprACTC) {
John McCall2cf031d2011-10-01 01:01:08 +00003194 case ACTC_none:
3195 case ACTC_coreFoundation:
3196 case ACTC_voidPtr:
3197 srcKind = (castExprType->isPointerType() ? 1 : 0);
3198 break;
3199 case ACTC_retainable:
3200 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3201 break;
3202 case ACTC_indirectRetainable:
3203 srcKind = 4;
3204 break;
John McCallf85e1932011-06-15 23:02:42 +00003205 }
3206
John McCall5acb0c92011-10-17 18:40:02 +00003207 // Check whether this could be fixed with a bridge cast.
3208 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
3209 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCallf85e1932011-06-15 23:02:42 +00003210
John McCall5acb0c92011-10-17 18:40:02 +00003211 // Bridge from an ARC type to a CF type.
3212 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003213
John McCall5acb0c92011-10-17 18:40:02 +00003214 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3215 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3216 << 2 // of C pointer type
3217 << castExprType
3218 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3219 << castType
3220 << castRange
3221 << castExpr->getSourceRange();
Argyrios Kyrtzidis684190b2012-06-01 00:10:47 +00003222 bool br = S.isKnownName("CFBridgingRelease");
Jordan Rose2f716222012-07-31 01:07:43 +00003223 ACCResult CreateRule =
Fariborz Jahanian24b2ab72012-07-27 23:55:46 +00003224 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose2f716222012-07-31 01:07:43 +00003225 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanian24b2ab72012-07-27 23:55:46 +00003226 if (CreateRule != ACC_plusOne)
Fariborz Jahanian607f5872012-07-27 21:34:23 +00003227 {
Fariborz Jahanianf0b1a0e2013-02-22 01:22:48 +00003228 DiagnosticBuilder DiagB =
3229 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3230 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3231
Fariborz Jahanian607f5872012-07-27 21:34:23 +00003232 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf799ae12013-02-22 22:02:53 +00003233 castType, castExpr, realCast, "__bridge ", 0);
Fariborz Jahanian607f5872012-07-27 21:34:23 +00003234 }
Fariborz Jahanian74cb3902012-07-28 18:59:49 +00003235 if (CreateRule != ACC_plusZero)
Fariborz Jahanian607f5872012-07-27 21:34:23 +00003236 {
Fariborz Jahanianf0b1a0e2013-02-22 01:22:48 +00003237 DiagnosticBuilder DiagB =
3238 (CCK == Sema::CCK_OtherCast && !br) ?
3239 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3240 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3241 diag::note_arc_bridge_transfer)
3242 << castExprType << br;
3243
Fariborz Jahanian607f5872012-07-27 21:34:23 +00003244 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf799ae12013-02-22 22:02:53 +00003245 castType, castExpr, realCast, "__bridge_transfer ",
Fariborz Jahanian607f5872012-07-27 21:34:23 +00003246 br ? "CFBridgingRelease" : 0);
3247 }
John McCall5acb0c92011-10-17 18:40:02 +00003248
3249 return;
3250 }
3251
3252 // Bridge from a CF type to an ARC type.
3253 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Argyrios Kyrtzidis684190b2012-06-01 00:10:47 +00003254 bool br = S.isKnownName("CFBridgingRetain");
John McCall5acb0c92011-10-17 18:40:02 +00003255 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3256 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3257 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3258 << castExprType
3259 << 2 // to C pointer type
3260 << castType
3261 << castRange
3262 << castExpr->getSourceRange();
Fariborz Jahanian24b2ab72012-07-27 23:55:46 +00003263 ACCResult CreateRule =
3264 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose2f716222012-07-31 01:07:43 +00003265 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanian24b2ab72012-07-27 23:55:46 +00003266 if (CreateRule != ACC_plusOne)
Fariborz Jahanian607f5872012-07-27 21:34:23 +00003267 {
Fariborz Jahanianf0b1a0e2013-02-22 01:22:48 +00003268 DiagnosticBuilder DiagB =
3269 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3270 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Fariborz Jahanian607f5872012-07-27 21:34:23 +00003271 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf799ae12013-02-22 22:02:53 +00003272 castType, castExpr, realCast, "__bridge ", 0);
Fariborz Jahanian607f5872012-07-27 21:34:23 +00003273 }
Fariborz Jahanian74cb3902012-07-28 18:59:49 +00003274 if (CreateRule != ACC_plusZero)
Fariborz Jahanian607f5872012-07-27 21:34:23 +00003275 {
Fariborz Jahanianf0b1a0e2013-02-22 01:22:48 +00003276 DiagnosticBuilder DiagB =
3277 (CCK == Sema::CCK_OtherCast && !br) ?
3278 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3279 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3280 diag::note_arc_bridge_retained)
3281 << castType << br;
3282
Fariborz Jahanian607f5872012-07-27 21:34:23 +00003283 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf799ae12013-02-22 22:02:53 +00003284 castType, castExpr, realCast, "__bridge_retained ",
Fariborz Jahanian607f5872012-07-27 21:34:23 +00003285 br ? "CFBridgingRetain" : 0);
3286 }
John McCall5acb0c92011-10-17 18:40:02 +00003287
3288 return;
John McCallf85e1932011-06-15 23:02:42 +00003289 }
3290
John McCall5acb0c92011-10-17 18:40:02 +00003291 S.Diag(loc, diag::err_arc_mismatched_cast)
3292 << (CCK != Sema::CCK_ImplicitConversion)
3293 << srcKind << castExprType << castType
John McCallf85e1932011-06-15 23:02:42 +00003294 << castRange << castExpr->getSourceRange();
3295}
3296
Stephen Hines651f13c2014-04-23 16:59:28 -07003297template <typename TB>
Fariborz Jahanian749152b2013-11-16 19:16:32 +00003298static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr) {
Fariborz Jahaniane78728a2013-11-15 22:18:17 +00003299 QualType T = castExpr->getType();
3300 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3301 TypedefNameDecl *TDNDecl = TD->getDecl();
Stephen Hines651f13c2014-04-23 16:59:28 -07003302 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahanian0f3bb9e2013-11-19 00:09:48 +00003303 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
3304 NamedDecl *Target = 0;
Fariborz Jahaniane78728a2013-11-15 22:18:17 +00003305 // Check for an existing type with this name.
3306 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3307 Sema::LookupOrdinaryName);
3308 if (S.LookupName(R, S.TUScope)) {
Fariborz Jahanian9571ab12013-11-16 01:45:25 +00003309 Target = R.getFoundDecl();
3310 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3311 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3312 if (const ObjCObjectPointerType *InterfacePointerType =
3313 castType->getAsObjCInterfacePointerType()) {
3314 ObjCInterfaceDecl *CastClass
3315 = InterfacePointerType->getObjectType()->getInterface();
Stephen Hines651f13c2014-04-23 16:59:28 -07003316 if ((CastClass == ExprClass) ||
3317 (CastClass && ExprClass->isSuperClassOf(CastClass)))
Fariborz Jahanian9571ab12013-11-16 01:45:25 +00003318 return true;
3319 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
Fariborz Jahanian3daade92013-11-19 01:23:07 +00003320 << T << Target->getName() << castType->getPointeeType();
Fariborz Jahanian9571ab12013-11-16 01:45:25 +00003321 return true;
Stephen Hines651f13c2014-04-23 16:59:28 -07003322 } else if (castType->isObjCIdType() ||
3323 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3324 castType, ExprClass)))
3325 // ok to cast to 'id'.
3326 // casting to id<p-list> is ok if bridge type adopts all of
3327 // p-list protocols.
3328 return true;
3329 else {
Fariborz Jahanian00be52d2013-11-16 23:22:37 +00003330 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
Fariborz Jahanian3daade92013-11-19 01:23:07 +00003331 << T << Target->getName() << castType;
Stephen Hines651f13c2014-04-23 16:59:28 -07003332 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3333 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanian00be52d2013-11-16 23:22:37 +00003334 return true;
3335 }
Fariborz Jahaniane78728a2013-11-15 22:18:17 +00003336 }
Fariborz Jahaniane78728a2013-11-15 22:18:17 +00003337 }
Fariborz Jahanian749152b2013-11-16 19:16:32 +00003338 S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface)
Stephen Hines651f13c2014-04-23 16:59:28 -07003339 << castExpr->getType() << Parm;
Fariborz Jahanian9571ab12013-11-16 01:45:25 +00003340 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3341 if (Target)
3342 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahaniane78728a2013-11-15 22:18:17 +00003343 }
3344 return true;
3345 }
3346 T = TDNDecl->getUnderlyingType();
3347 }
3348 return false;
3349}
3350
Stephen Hines651f13c2014-04-23 16:59:28 -07003351template <typename TB>
Fariborz Jahanian749152b2013-11-16 19:16:32 +00003352static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr) {
3353 QualType T = castType;
3354 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3355 TypedefNameDecl *TDNDecl = TD->getDecl();
Stephen Hines651f13c2014-04-23 16:59:28 -07003356 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahanian0f3bb9e2013-11-19 00:09:48 +00003357 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
3358 NamedDecl *Target = 0;
Fariborz Jahanian749152b2013-11-16 19:16:32 +00003359 // Check for an existing type with this name.
3360 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3361 Sema::LookupOrdinaryName);
3362 if (S.LookupName(R, S.TUScope)) {
3363 Target = R.getFoundDecl();
3364 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3365 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3366 if (const ObjCObjectPointerType *InterfacePointerType =
3367 castExpr->getType()->getAsObjCInterfacePointerType()) {
3368 ObjCInterfaceDecl *ExprClass
3369 = InterfacePointerType->getObjectType()->getInterface();
Stephen Hines651f13c2014-04-23 16:59:28 -07003370 if ((CastClass == ExprClass) ||
3371 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian749152b2013-11-16 19:16:32 +00003372 return true;
3373 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
Fariborz Jahanian3daade92013-11-19 01:23:07 +00003374 << castExpr->getType()->getPointeeType() << T;
Fariborz Jahanian749152b2013-11-16 19:16:32 +00003375 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3376 return true;
Stephen Hines651f13c2014-04-23 16:59:28 -07003377 } else if (castExpr->getType()->isObjCIdType() ||
3378 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3379 castExpr->getType(), CastClass)))
3380 // ok to cast an 'id' expression to a CFtype.
3381 // ok to cast an 'id<plist>' expression to CFtype provided plist
3382 // adopts all of CFtype's ObjetiveC's class plist.
3383 return true;
3384 else {
Fariborz Jahanian00be52d2013-11-16 23:22:37 +00003385 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3386 << castExpr->getType() << castType;
3387 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
Stephen Hines651f13c2014-04-23 16:59:28 -07003388 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanian00be52d2013-11-16 23:22:37 +00003389 return true;
Fariborz Jahanian749152b2013-11-16 19:16:32 +00003390 }
3391 }
3392 }
3393 S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject)
3394 << castExpr->getType() << castType;
3395 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3396 if (Target)
3397 S.Diag(Target->getLocStart(), diag::note_declared_at);
3398 }
3399 return true;
3400 }
3401 T = TDNDecl->getUnderlyingType();
3402 }
3403 return false;
3404}
3405
Stephen Hines651f13c2014-04-23 16:59:28 -07003406void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
3407 // warn in presence of __bridge casting to or from a toll free bridge cast.
3408 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3409 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3410 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
3411 (void)CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr);
3412 (void)CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr);
3413 }
3414 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
3415 (void)CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr);
3416 (void)CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr);
3417 }
3418}
3419
3420
3421bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
3422 QualType DestType, QualType SrcType,
3423 ObjCInterfaceDecl *&RelatedClass,
3424 ObjCMethodDecl *&ClassMethod,
3425 ObjCMethodDecl *&InstanceMethod,
3426 TypedefNameDecl *&TDNDecl,
3427 bool CfToNs) {
3428 QualType T = CfToNs ? SrcType : DestType;
3429 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
3430 if (!ObjCBAttr)
3431 return false;
3432
3433 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
3434 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
3435 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
3436 if (!RCId)
3437 return false;
3438 NamedDecl *Target = 0;
3439 // Check for an existing type with this name.
3440 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
3441 Sema::LookupOrdinaryName);
3442 if (!LookupName(R, TUScope)) {
3443 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
3444 << SrcType << DestType;
3445 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3446 return false;
3447 }
3448 Target = R.getFoundDecl();
3449 if (Target && isa<ObjCInterfaceDecl>(Target))
3450 RelatedClass = cast<ObjCInterfaceDecl>(Target);
3451 else {
3452 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
3453 << SrcType << DestType;
3454 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3455 if (Target)
3456 Diag(Target->getLocStart(), diag::note_declared_at);
3457 return false;
3458 }
3459
3460 // Check for an existing class method with the given selector name.
3461 if (CfToNs && CMId) {
3462 Selector Sel = Context.Selectors.getUnarySelector(CMId);
3463 ClassMethod = RelatedClass->lookupMethod(Sel, false);
3464 if (!ClassMethod) {
3465 Diag(Loc, diag::err_objc_bridged_related_known_method)
3466 << SrcType << DestType << Sel << false;
3467 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3468 return false;
3469 }
3470 }
3471
3472 // Check for an existing instance method with the given selector name.
3473 if (!CfToNs && IMId) {
3474 Selector Sel = Context.Selectors.getNullarySelector(IMId);
3475 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
3476 if (!InstanceMethod) {
3477 Diag(Loc, diag::err_objc_bridged_related_known_method)
3478 << SrcType << DestType << Sel << true;
3479 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3480 return false;
3481 }
3482 }
3483 return true;
3484}
3485
3486bool
3487Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
3488 QualType DestType, QualType SrcType,
3489 Expr *&SrcExpr) {
3490 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
3491 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
3492 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
3493 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
3494 if (!CfToNs && !NsToCf)
3495 return false;
3496
3497 ObjCInterfaceDecl *RelatedClass;
3498 ObjCMethodDecl *ClassMethod = 0;
3499 ObjCMethodDecl *InstanceMethod = 0;
3500 TypedefNameDecl *TDNDecl = 0;
3501 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
3502 ClassMethod, InstanceMethod, TDNDecl, CfToNs))
3503 return false;
3504
3505 if (CfToNs) {
3506 // Implicit conversion from CF to ObjC object is needed.
3507 if (ClassMethod) {
3508 std::string ExpressionString = "[";
3509 ExpressionString += RelatedClass->getNameAsString();
3510 ExpressionString += " ";
3511 ExpressionString += ClassMethod->getSelector().getAsString();
3512 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
3513 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
3514 Diag(Loc, diag::err_objc_bridged_related_known_method)
3515 << SrcType << DestType << ClassMethod->getSelector() << false
3516 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString)
3517 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
3518 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3519 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3520
3521 QualType receiverType =
3522 Context.getObjCInterfaceType(RelatedClass);
3523 // Argument.
3524 Expr *args[] = { SrcExpr };
3525 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
3526 ClassMethod->getLocation(),
3527 ClassMethod->getSelector(), ClassMethod,
3528 MultiExprArg(args, 1));
3529 SrcExpr = msg.take();
3530 return true;
3531 }
3532 }
3533 else {
3534 // Implicit conversion from ObjC type to CF object is needed.
3535 if (InstanceMethod) {
3536 std::string ExpressionString;
3537 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
3538 if (InstanceMethod->isPropertyAccessor())
3539 if (const ObjCPropertyDecl *PDecl = InstanceMethod->findPropertyDecl()) {
3540 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
3541 ExpressionString = ".";
3542 ExpressionString += PDecl->getNameAsString();
3543 Diag(Loc, diag::err_objc_bridged_related_known_method)
3544 << SrcType << DestType << InstanceMethod->getSelector() << true
3545 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3546 }
3547 if (ExpressionString.empty()) {
3548 // Provide a fixit: [ObjectExpr InstanceMethod]
3549 ExpressionString = " ";
3550 ExpressionString += InstanceMethod->getSelector().getAsString();
3551 ExpressionString += "]";
3552
3553 Diag(Loc, diag::err_objc_bridged_related_known_method)
3554 << SrcType << DestType << InstanceMethod->getSelector() << true
3555 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[")
3556 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3557 }
3558 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3559 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3560
3561 ExprResult msg =
3562 BuildInstanceMessageImplicit(SrcExpr, SrcType,
3563 InstanceMethod->getLocation(),
3564 InstanceMethod->getSelector(),
3565 InstanceMethod, None);
3566 SrcExpr = msg.take();
3567 return true;
3568 }
3569 }
3570 return false;
3571}
3572
John McCall5acb0c92011-10-17 18:40:02 +00003573Sema::ARCConversionResult
3574Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanian01ad0482013-07-31 21:40:51 +00003575 Expr *&castExpr, CheckedConversionKind CCK,
3576 bool DiagnoseCFAudited) {
John McCall5acb0c92011-10-17 18:40:02 +00003577 QualType castExprType = castExpr->getType();
3578
3579 // For the purposes of the classification, we assume reference types
3580 // will bind to temporaries.
3581 QualType effCastType = castType;
3582 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
3583 effCastType = ref->getPointeeType();
3584
3585 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
3586 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00003587 if (exprACTC == castACTC) {
3588 // check for viablity and report error if casting an rvalue to a
3589 // life-time qualifier.
Fariborz Jahanianfc2eff52011-10-29 00:06:10 +00003590 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00003591 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanianfc2eff52011-10-29 00:06:10 +00003592 (castType != castExprType)) {
3593 const Type *DT = castType.getTypePtr();
3594 QualType QDT = castType;
3595 // We desugar some types but not others. We ignore those
3596 // that cannot happen in a cast; i.e. auto, and those which
3597 // should not be de-sugared; i.e typedef.
3598 if (const ParenType *PT = dyn_cast<ParenType>(DT))
3599 QDT = PT->desugar();
3600 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
3601 QDT = TP->desugar();
3602 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
3603 QDT = AT->desugar();
3604 if (QDT != castType &&
3605 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
3606 SourceLocation loc =
3607 (castRange.isValid() ? castRange.getBegin()
3608 : castExpr->getExprLoc());
3609 Diag(loc, diag::err_arc_nolifetime_behavior);
3610 }
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00003611 }
3612 return ACR_okay;
3613 }
3614
John McCall5acb0c92011-10-17 18:40:02 +00003615 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
3616
3617 // Allow all of these types to be cast to integer types (but not
3618 // vice-versa).
3619 if (castACTC == ACTC_none && castType->isIntegralType(Context))
3620 return ACR_okay;
3621
3622 // Allow casts between pointers to lifetime types (e.g., __strong id*)
3623 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
3624 // must be explicit.
3625 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
3626 return ACR_okay;
3627 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
3628 CCK != CCK_ImplicitConversion)
3629 return ACR_okay;
Fariborz Jahaniane78728a2013-11-15 22:18:17 +00003630
3631 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation &&
3632 (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast))
Stephen Hines651f13c2014-04-23 16:59:28 -07003633 if (CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr) ||
3634 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr))
Fariborz Jahanian749152b2013-11-16 19:16:32 +00003635 return ACR_okay;
3636
3637 if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3638 (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast))
Stephen Hines651f13c2014-04-23 16:59:28 -07003639 if (CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr) ||
3640 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr))
Fariborz Jahaniane78728a2013-11-15 22:18:17 +00003641 return ACR_okay;
3642
John McCall5acb0c92011-10-17 18:40:02 +00003643
Fariborz Jahanian533b34f2012-07-27 22:37:07 +00003644 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
John McCall5acb0c92011-10-17 18:40:02 +00003645 // For invalid casts, fall through.
3646 case ACC_invalid:
3647 break;
3648
3649 // Do nothing for both bottom and +0.
3650 case ACC_bottom:
3651 case ACC_plusZero:
3652 return ACR_okay;
3653
3654 // If the result is +1, consume it here.
3655 case ACC_plusOne:
3656 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
3657 CK_ARCConsumeObject, castExpr,
3658 0, VK_RValue);
3659 ExprNeedsCleanups = true;
3660 return ACR_okay;
3661 }
3662
3663 // If this is a non-implicit cast from id or block type to a
3664 // CoreFoundation type, delay complaining in case the cast is used
3665 // in an acceptable context.
3666 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
3667 CCK != CCK_ImplicitConversion)
3668 return ACR_unbridged;
3669
Stephen Hines651f13c2014-04-23 16:59:28 -07003670 // Do not issue bridge cast" diagnostic when implicit casting a cstring
3671 // to 'NSString *'. Let caller issue a normal mismatched diagnostic with
3672 // suitable fix-it.
3673 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
3674 ConversionToObjCStringLiteralCheck(castType, castExpr))
3675 return ACR_okay;
3676
Fariborz Jahanian01ad0482013-07-31 21:40:51 +00003677 // Do not issue "bridge cast" diagnostic when implicit casting
3678 // a retainable object to a CF type parameter belonging to an audited
3679 // CF API function. Let caller issue a normal type mismatched diagnostic
3680 // instead.
3681 if (!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
3682 castACTC != ACTC_coreFoundation)
3683 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3684 castExpr, castExpr, exprACTC, CCK);
John McCall5acb0c92011-10-17 18:40:02 +00003685 return ACR_okay;
3686}
3687
3688/// Given that we saw an expression with the ARCUnbridgedCastTy
3689/// placeholder type, complain bitterly.
3690void Sema::diagnoseARCUnbridgedCast(Expr *e) {
3691 // We expect the spurious ImplicitCastExpr to already have been stripped.
3692 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3693 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
3694
3695 SourceRange castRange;
3696 QualType castType;
3697 CheckedConversionKind CCK;
3698
3699 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
3700 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
3701 castType = cast->getTypeAsWritten();
3702 CCK = CCK_CStyleCast;
3703 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
3704 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
3705 castType = cast->getTypeAsWritten();
3706 CCK = CCK_OtherCast;
3707 } else {
3708 castType = cast->getType();
3709 CCK = CCK_ImplicitConversion;
3710 }
3711
3712 ARCConversionTypeClass castACTC =
3713 classifyTypeForARCConversion(castType.getNonReferenceType());
3714
3715 Expr *castExpr = realCast->getSubExpr();
3716 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
3717
3718 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
Fariborz Jahanianf799ae12013-02-22 22:02:53 +00003719 castExpr, realCast, ACTC_retainable, CCK);
John McCall5acb0c92011-10-17 18:40:02 +00003720}
3721
3722/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
3723/// type, remove the placeholder cast.
3724Expr *Sema::stripARCUnbridgedCast(Expr *e) {
3725 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3726
3727 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
3728 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
3729 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
3730 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
3731 assert(uo->getOpcode() == UO_Extension);
3732 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
3733 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
3734 sub->getValueKind(), sub->getObjectKind(),
3735 uo->getOperatorLoc());
3736 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
3737 assert(!gse->isResultDependent());
3738
3739 unsigned n = gse->getNumAssocs();
3740 SmallVector<Expr*, 4> subExprs(n);
3741 SmallVector<TypeSourceInfo*, 4> subTypes(n);
3742 for (unsigned i = 0; i != n; ++i) {
3743 subTypes[i] = gse->getAssocTypeSourceInfo(i);
3744 Expr *sub = gse->getAssocExpr(i);
3745 if (i == gse->getResultIndex())
3746 sub = stripARCUnbridgedCast(sub);
3747 subExprs[i] = sub;
3748 }
3749
3750 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
3751 gse->getControllingExpr(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003752 subTypes, subExprs,
3753 gse->getDefaultLoc(),
John McCall5acb0c92011-10-17 18:40:02 +00003754 gse->getRParenLoc(),
3755 gse->containsUnexpandedParameterPack(),
3756 gse->getResultIndex());
3757 } else {
3758 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
3759 return cast<ImplicitCastExpr>(e)->getSubExpr();
3760 }
3761}
3762
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00003763bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
3764 QualType exprType) {
3765 QualType canCastType =
3766 Context.getCanonicalType(castType).getUnqualifiedType();
3767 QualType canExprType =
3768 Context.getCanonicalType(exprType).getUnqualifiedType();
3769 if (isa<ObjCObjectPointerType>(canCastType) &&
3770 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
3771 canExprType->isObjCObjectPointerType()) {
3772 if (const ObjCObjectPointerType *ObjT =
3773 canExprType->getAs<ObjCObjectPointerType>())
Richard Smitha8eaf002012-08-23 06:16:52 +00003774 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
3775 return !ObjI->isArcWeakrefUnavailable();
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00003776 }
3777 return true;
3778}
3779
John McCall7e5e5f42011-07-07 06:58:02 +00003780/// Look for an ObjCReclaimReturnedObject cast and destroy it.
3781static Expr *maybeUndoReclaimObject(Expr *e) {
3782 // For now, we just undo operands that are *immediately* reclaim
3783 // expressions, which prevents the vast majority of potential
3784 // problems here. To catch them all, we'd need to rebuild arbitrary
3785 // value-propagating subexpressions --- we can't reliably rebuild
3786 // in-place because of expression sharing.
3787 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall33e56f32011-09-10 06:18:15 +00003788 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall7e5e5f42011-07-07 06:58:02 +00003789 return ice->getSubExpr();
3790
3791 return e;
3792}
3793
John McCallf85e1932011-06-15 23:02:42 +00003794ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
3795 ObjCBridgeCastKind Kind,
3796 SourceLocation BridgeKeywordLoc,
3797 TypeSourceInfo *TSInfo,
3798 Expr *SubExpr) {
John McCall4906cf92011-08-26 00:48:42 +00003799 ExprResult SubResult = UsualUnaryConversions(SubExpr);
3800 if (SubResult.isInvalid()) return ExprError();
3801 SubExpr = SubResult.take();
3802
John McCallf85e1932011-06-15 23:02:42 +00003803 QualType T = TSInfo->getType();
3804 QualType FromType = SubExpr->getType();
3805
John McCall1d9b3b22011-09-09 05:25:32 +00003806 CastKind CK;
3807
John McCallf85e1932011-06-15 23:02:42 +00003808 bool MustConsume = false;
3809 if (T->isDependentType() || SubExpr->isTypeDependent()) {
3810 // Okay: we'll build a dependent expression type.
John McCall1d9b3b22011-09-09 05:25:32 +00003811 CK = CK_Dependent;
John McCallf85e1932011-06-15 23:02:42 +00003812 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
3813 // Casting CF -> id
John McCall1d9b3b22011-09-09 05:25:32 +00003814 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
3815 : CK_CPointerToObjCPointerCast);
John McCallf85e1932011-06-15 23:02:42 +00003816 switch (Kind) {
3817 case OBC_Bridge:
3818 break;
3819
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003820 case OBC_BridgeRetained: {
Argyrios Kyrtzidis684190b2012-06-01 00:10:47 +00003821 bool br = isKnownName("CFBridgingRelease");
John McCallf85e1932011-06-15 23:02:42 +00003822 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3823 << 2
3824 << FromType
3825 << (T->isBlockPointerType()? 1 : 0)
3826 << T
3827 << SubExpr->getSourceRange()
3828 << Kind;
3829 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3830 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
3831 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003832 << FromType << br
John McCallf85e1932011-06-15 23:02:42 +00003833 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003834 br ? "CFBridgingRelease "
3835 : "__bridge_transfer ");
John McCallf85e1932011-06-15 23:02:42 +00003836
3837 Kind = OBC_Bridge;
3838 break;
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003839 }
John McCallf85e1932011-06-15 23:02:42 +00003840
3841 case OBC_BridgeTransfer:
3842 // We must consume the Objective-C object produced by the cast.
3843 MustConsume = true;
3844 break;
3845 }
3846 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
3847 // Okay: id -> CF
John McCall1d9b3b22011-09-09 05:25:32 +00003848 CK = CK_BitCast;
John McCallf85e1932011-06-15 23:02:42 +00003849 switch (Kind) {
3850 case OBC_Bridge:
John McCall7e5e5f42011-07-07 06:58:02 +00003851 // Reclaiming a value that's going to be __bridge-casted to CF
3852 // is very dangerous, so we don't do it.
3853 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCallf85e1932011-06-15 23:02:42 +00003854 break;
3855
3856 case OBC_BridgeRetained:
3857 // Produce the object before casting it.
3858 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall33e56f32011-09-10 06:18:15 +00003859 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00003860 SubExpr, 0, VK_RValue);
3861 break;
3862
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003863 case OBC_BridgeTransfer: {
Argyrios Kyrtzidis684190b2012-06-01 00:10:47 +00003864 bool br = isKnownName("CFBridgingRetain");
John McCallf85e1932011-06-15 23:02:42 +00003865 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3866 << (FromType->isBlockPointerType()? 1 : 0)
3867 << FromType
3868 << 2
3869 << T
3870 << SubExpr->getSourceRange()
3871 << Kind;
3872
3873 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3874 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
3875 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003876 << T << br
3877 << FixItHint::CreateReplacement(BridgeKeywordLoc,
3878 br ? "CFBridgingRetain " : "__bridge_retained");
John McCallf85e1932011-06-15 23:02:42 +00003879
3880 Kind = OBC_Bridge;
3881 break;
3882 }
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003883 }
John McCallf85e1932011-06-15 23:02:42 +00003884 } else {
3885 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
3886 << FromType << T << Kind
3887 << SubExpr->getSourceRange()
3888 << TSInfo->getTypeLoc().getSourceRange();
3889 return ExprError();
3890 }
3891
John McCall1d9b3b22011-09-09 05:25:32 +00003892 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCallf85e1932011-06-15 23:02:42 +00003893 BridgeKeywordLoc,
3894 TSInfo, SubExpr);
3895
3896 if (MustConsume) {
3897 ExprNeedsCleanups = true;
John McCall33e56f32011-09-10 06:18:15 +00003898 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
John McCallf85e1932011-06-15 23:02:42 +00003899 0, VK_RValue);
3900 }
3901
3902 return Result;
3903}
3904
3905ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
3906 SourceLocation LParenLoc,
3907 ObjCBridgeCastKind Kind,
3908 SourceLocation BridgeKeywordLoc,
3909 ParsedType Type,
3910 SourceLocation RParenLoc,
3911 Expr *SubExpr) {
3912 TypeSourceInfo *TSInfo = 0;
3913 QualType T = GetTypeFromParser(Type, &TSInfo);
Stephen Hines651f13c2014-04-23 16:59:28 -07003914 if (Kind == OBC_Bridge)
3915 CheckTollFreeBridgeCast(T, SubExpr);
John McCallf85e1932011-06-15 23:02:42 +00003916 if (!TSInfo)
3917 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
3918 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
3919 SubExpr);
3920}