blob: 5fab2a147879af744418eb49c2d559347c6afada [file] [log] [blame]
Chris Lattnerda463fe2007-12-12 07:09:47 +00001//===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnerda463fe2007-12-12 07:09:47 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for Objective C declarations.
10//
11//===----------------------------------------------------------------------===//
12
Mehdi Amini9670f842016-07-18 19:02:11 +000013#include "TypeLocBuilder.h"
John McCall31168b02011-06-15 23:02:42 +000014#include "clang/AST/ASTConsumer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/DeclObjC.h"
Steve Naroff157599f2009-03-03 14:49:36 +000018#include "clang/AST/Expr.h"
John McCall31168b02011-06-15 23:02:42 +000019#include "clang/AST/ExprObjC.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000020#include "clang/AST/RecursiveASTVisitor.h"
John McCall31168b02011-06-15 23:02:42 +000021#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Sema/DeclSpec.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Sema/Lookup.h"
24#include "clang/Sema/Scope.h"
25#include "clang/Sema/ScopeInfo.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000026#include "clang/Sema/SemaInternal.h"
Douglas Gregor85f3f952015-07-07 03:57:15 +000027#include "llvm/ADT/DenseMap.h"
John McCalla1e130b2010-08-25 07:03:20 +000028#include "llvm/ADT/DenseSet.h"
29
Chris Lattnerda463fe2007-12-12 07:09:47 +000030using namespace clang;
31
John McCall31168b02011-06-15 23:02:42 +000032/// Check whether the given method, which must be in the 'init'
33/// family, is a valid member of that family.
34///
35/// \param receiverTypeIfCall - if null, check this as if declaring it;
36/// if non-null, check this as if making a call to it with the given
37/// receiver type
38///
39/// \return true to indicate that there was an error and appropriate
40/// actions were taken
41bool Sema::checkInitMethod(ObjCMethodDecl *method,
42 QualType receiverTypeIfCall) {
43 if (method->isInvalidDecl()) return true;
44
45 // This castAs is safe: methods that don't return an object
46 // pointer won't be inferred as inits and will reject an explicit
47 // objc_method_family(init).
48
49 // We ignore protocols here. Should we? What about Class?
50
Alp Toker314cc812014-01-25 16:55:45 +000051 const ObjCObjectType *result =
52 method->getReturnType()->castAs<ObjCObjectPointerType>()->getObjectType();
John McCall31168b02011-06-15 23:02:42 +000053
54 if (result->isObjCId()) {
55 return false;
56 } else if (result->isObjCClass()) {
57 // fall through: always an error
58 } else {
59 ObjCInterfaceDecl *resultClass = result->getInterface();
60 assert(resultClass && "unexpected object type!");
61
62 // It's okay for the result type to still be a forward declaration
63 // if we're checking an interface declaration.
Douglas Gregordc9166c2011-12-15 20:29:51 +000064 if (!resultClass->hasDefinition()) {
John McCall31168b02011-06-15 23:02:42 +000065 if (receiverTypeIfCall.isNull() &&
66 !isa<ObjCImplementationDecl>(method->getDeclContext()))
67 return false;
68
69 // Otherwise, we try to compare class types.
70 } else {
71 // If this method was declared in a protocol, we can't check
72 // anything unless we have a receiver type that's an interface.
Craig Topperc3ec1492014-05-26 06:22:03 +000073 const ObjCInterfaceDecl *receiverClass = nullptr;
John McCall31168b02011-06-15 23:02:42 +000074 if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
75 if (receiverTypeIfCall.isNull())
76 return false;
77
78 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
79 ->getInterfaceDecl();
80
81 // This can be null for calls to e.g. id<Foo>.
82 if (!receiverClass) return false;
83 } else {
84 receiverClass = method->getClassInterface();
85 assert(receiverClass && "method not associated with a class!");
86 }
87
88 // If either class is a subclass of the other, it's fine.
89 if (receiverClass->isSuperClassOf(resultClass) ||
90 resultClass->isSuperClassOf(receiverClass))
91 return false;
92 }
93 }
94
95 SourceLocation loc = method->getLocation();
96
97 // If we're in a system header, and this is not a call, just make
98 // the method unusable.
99 if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
John McCallc6af8c62015-10-28 05:03:19 +0000100 method->addAttr(UnavailableAttr::CreateImplicit(Context, "",
101 UnavailableAttr::IR_ARCInitReturnsUnrelated, loc));
John McCall31168b02011-06-15 23:02:42 +0000102 return true;
103 }
104
105 // Otherwise, it's an error.
106 Diag(loc, diag::err_arc_init_method_unrelated_result_type);
107 method->setInvalidDecl();
108 return true;
109}
110
Akira Hatanakaa6b5e002018-07-28 04:06:13 +0000111/// Issue a warning if the parameter of the overridden method is non-escaping
112/// but the parameter of the overriding method is not.
113static bool diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD,
114 Sema &S) {
115 if (OldD->hasAttr<NoEscapeAttr>() && !NewD->hasAttr<NoEscapeAttr>()) {
116 S.Diag(NewD->getLocation(), diag::warn_overriding_method_missing_noescape);
117 S.Diag(OldD->getLocation(), diag::note_overridden_marked_noescape);
118 return false;
119 }
120
121 return true;
122}
123
124/// Produce additional diagnostics if a category conforms to a protocol that
125/// defines a method taking a non-escaping parameter.
126static void diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD,
127 const ObjCCategoryDecl *CD,
128 const ObjCProtocolDecl *PD, Sema &S) {
129 if (!diagnoseNoescape(NewD, OldD, S))
130 S.Diag(CD->getLocation(), diag::note_cat_conform_to_noescape_prot)
131 << CD->IsClassExtension() << PD
132 << cast<ObjCMethodDecl>(NewD->getDeclContext());
133}
134
Fangrui Song6907ce22018-07-30 19:24:48 +0000135void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
Douglas Gregor66a8ca02013-01-15 22:43:08 +0000136 const ObjCMethodDecl *Overridden) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000137 if (Overridden->hasRelatedResultType() &&
Douglas Gregor33823722011-06-11 01:09:30 +0000138 !NewMethod->hasRelatedResultType()) {
139 // This can only happen when the method follows a naming convention that
140 // implies a related result type, and the original (overridden) method has
141 // a suitable return type, but the new (overriding) method does not have
142 // a suitable return type.
Alp Toker314cc812014-01-25 16:55:45 +0000143 QualType ResultType = NewMethod->getReturnType();
Aaron Ballman41b10ac2014-08-01 13:20:09 +0000144 SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange();
Fangrui Song6907ce22018-07-30 19:24:48 +0000145
Douglas Gregor33823722011-06-11 01:09:30 +0000146 // Figure out which class this method is part of, if any.
Fangrui Song6907ce22018-07-30 19:24:48 +0000147 ObjCInterfaceDecl *CurrentClass
Douglas Gregor33823722011-06-11 01:09:30 +0000148 = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
149 if (!CurrentClass) {
150 DeclContext *DC = NewMethod->getDeclContext();
151 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
152 CurrentClass = Cat->getClassInterface();
153 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
154 CurrentClass = Impl->getClassInterface();
155 else if (ObjCCategoryImplDecl *CatImpl
156 = dyn_cast<ObjCCategoryImplDecl>(DC))
157 CurrentClass = CatImpl->getClassInterface();
158 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000159
Douglas Gregor33823722011-06-11 01:09:30 +0000160 if (CurrentClass) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000161 Diag(NewMethod->getLocation(),
Douglas Gregor33823722011-06-11 01:09:30 +0000162 diag::warn_related_result_type_compatibility_class)
163 << Context.getObjCInterfaceType(CurrentClass)
164 << ResultType
165 << ResultTypeRange;
166 } else {
Fangrui Song6907ce22018-07-30 19:24:48 +0000167 Diag(NewMethod->getLocation(),
Douglas Gregor33823722011-06-11 01:09:30 +0000168 diag::warn_related_result_type_compatibility_protocol)
169 << ResultType
170 << ResultTypeRange;
171 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000172
Douglas Gregorbab8a962011-09-08 01:46:34 +0000173 if (ObjCMethodFamily Family = Overridden->getMethodFamily())
Fangrui Song6907ce22018-07-30 19:24:48 +0000174 Diag(Overridden->getLocation(),
John McCall5ec7e7d2013-03-19 07:04:25 +0000175 diag::note_related_result_type_family)
176 << /*overridden method*/ 0
Douglas Gregorbab8a962011-09-08 01:46:34 +0000177 << Family;
178 else
Fangrui Song6907ce22018-07-30 19:24:48 +0000179 Diag(Overridden->getLocation(),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000180 diag::note_related_result_type_overridden);
Douglas Gregor33823722011-06-11 01:09:30 +0000181 }
Akira Hatanaka7d85b8f2017-09-20 05:39:18 +0000182
183 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
184 Overridden->hasAttr<NSReturnsRetainedAttr>())) {
185 Diag(NewMethod->getLocation(),
Alex Lorenz26d282f2018-01-03 23:52:42 +0000186 getLangOpts().ObjCAutoRefCount
187 ? diag::err_nsreturns_retained_attribute_mismatch
188 : diag::warn_nsreturns_retained_attribute_mismatch)
189 << 1;
Akira Hatanaka7d85b8f2017-09-20 05:39:18 +0000190 Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
191 }
192 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
193 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
194 Diag(NewMethod->getLocation(),
Alex Lorenz26d282f2018-01-03 23:52:42 +0000195 getLangOpts().ObjCAutoRefCount
196 ? diag::err_nsreturns_retained_attribute_mismatch
197 : diag::warn_nsreturns_retained_attribute_mismatch)
198 << 0;
Akira Hatanaka7d85b8f2017-09-20 05:39:18 +0000199 Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
200 }
201
202 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
203 oe = Overridden->param_end();
204 for (ObjCMethodDecl::param_iterator ni = NewMethod->param_begin(),
205 ne = NewMethod->param_end();
206 ni != ne && oi != oe; ++ni, ++oi) {
207 const ParmVarDecl *oldDecl = (*oi);
208 ParmVarDecl *newDecl = (*ni);
209 if (newDecl->hasAttr<NSConsumedAttr>() !=
210 oldDecl->hasAttr<NSConsumedAttr>()) {
Alex Lorenz26d282f2018-01-03 23:52:42 +0000211 Diag(newDecl->getLocation(),
212 getLangOpts().ObjCAutoRefCount
213 ? diag::err_nsconsumed_attribute_mismatch
214 : diag::warn_nsconsumed_attribute_mismatch);
Akira Hatanaka7d85b8f2017-09-20 05:39:18 +0000215 Diag(oldDecl->getLocation(), diag::note_previous_decl) << "parameter";
Fariborz Jahanianac8dbf02011-09-27 22:35:36 +0000216 }
Akira Hatanaka98a49332017-09-22 00:41:05 +0000217
Akira Hatanakaa6b5e002018-07-28 04:06:13 +0000218 diagnoseNoescape(newDecl, oldDecl, *this);
Fariborz Jahanianac8dbf02011-09-27 22:35:36 +0000219 }
Douglas Gregor33823722011-06-11 01:09:30 +0000220}
221
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000222/// Check a method declaration for compatibility with the Objective-C
John McCall31168b02011-06-15 23:02:42 +0000223/// ARC conventions.
John McCalle48f3892013-04-04 01:38:37 +0000224bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
John McCall31168b02011-06-15 23:02:42 +0000225 ObjCMethodFamily family = method->getMethodFamily();
226 switch (family) {
227 case OMF_None:
Nico Weber1fb82662011-08-28 22:35:17 +0000228 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +0000229 case OMF_retain:
230 case OMF_release:
231 case OMF_autorelease:
232 case OMF_retainCount:
233 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +0000234 case OMF_initialize:
John McCalld2930c22011-07-22 02:45:48 +0000235 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +0000236 return false;
237
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000238 case OMF_dealloc:
Alp Toker314cc812014-01-25 16:55:45 +0000239 if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
Aaron Ballman41b10ac2014-08-01 13:20:09 +0000240 SourceRange ResultTypeRange = method->getReturnTypeSourceRange();
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000241 if (ResultTypeRange.isInvalid())
Richard Smithf8812672016-12-02 22:38:31 +0000242 Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
Alp Toker314cc812014-01-25 16:55:45 +0000243 << method->getReturnType()
244 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000245 else
Richard Smithf8812672016-12-02 22:38:31 +0000246 Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
Alp Toker314cc812014-01-25 16:55:45 +0000247 << method->getReturnType()
248 << FixItHint::CreateReplacement(ResultTypeRange, "void");
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000249 return true;
250 }
251 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000252
John McCall31168b02011-06-15 23:02:42 +0000253 case OMF_init:
254 // If the method doesn't obey the init rules, don't bother annotating it.
John McCalle48f3892013-04-04 01:38:37 +0000255 if (checkInitMethod(method, QualType()))
John McCall31168b02011-06-15 23:02:42 +0000256 return true;
257
Aaron Ballman36a53502014-01-16 13:03:14 +0000258 method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
John McCall31168b02011-06-15 23:02:42 +0000259
260 // Don't add a second copy of this attribute, but otherwise don't
261 // let it be suppressed.
262 if (method->hasAttr<NSReturnsRetainedAttr>())
263 return false;
264 break;
265
266 case OMF_alloc:
267 case OMF_copy:
268 case OMF_mutableCopy:
269 case OMF_new:
270 if (method->hasAttr<NSReturnsRetainedAttr>() ||
271 method->hasAttr<NSReturnsNotRetainedAttr>() ||
272 method->hasAttr<NSReturnsAutoreleasedAttr>())
273 return false;
274 break;
275 }
276
Aaron Ballman36a53502014-01-16 13:03:14 +0000277 method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
John McCall31168b02011-06-15 23:02:42 +0000278 return false;
279}
280
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000281static void DiagnoseObjCImplementedDeprecations(Sema &S, const NamedDecl *ND,
282 SourceLocation ImplLoc) {
283 if (!ND)
284 return;
285 bool IsCategory = false;
Alex Lorenzf4d4cfb2018-05-03 01:12:06 +0000286 StringRef RealizedPlatform;
287 AvailabilityResult Availability = ND->getAvailability(
288 /*Message=*/nullptr, /*EnclosingVersion=*/VersionTuple(),
289 &RealizedPlatform);
Alex Lorenze1088dc2017-07-13 16:37:11 +0000290 if (Availability != AR_Deprecated) {
Eric Christopher7aba9782017-07-14 01:42:57 +0000291 if (isa<ObjCMethodDecl>(ND)) {
Alex Lorenze1088dc2017-07-13 16:37:11 +0000292 if (Availability != AR_Unavailable)
293 return;
Alex Lorenzf4d4cfb2018-05-03 01:12:06 +0000294 if (RealizedPlatform.empty())
295 RealizedPlatform = S.Context.getTargetInfo().getPlatformName();
296 // Warn about implementing unavailable methods, unless the unavailable
297 // is for an app extension.
298 if (RealizedPlatform.endswith("_app_extension"))
299 return;
Alex Lorenze1088dc2017-07-13 16:37:11 +0000300 S.Diag(ImplLoc, diag::warn_unavailable_def);
301 S.Diag(ND->getLocation(), diag::note_method_declared_at)
302 << ND->getDeclName();
303 return;
304 }
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000305 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND)) {
306 if (!CD->getClassInterface()->isDeprecated())
307 return;
308 ND = CD->getClassInterface();
309 IsCategory = true;
310 } else
311 return;
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000312 }
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000313 S.Diag(ImplLoc, diag::warn_deprecated_def)
314 << (isa<ObjCMethodDecl>(ND)
315 ? /*Method*/ 0
316 : isa<ObjCCategoryDecl>(ND) || IsCategory ? /*Category*/ 2
317 : /*Class*/ 1);
318 if (isa<ObjCMethodDecl>(ND))
319 S.Diag(ND->getLocation(), diag::note_method_declared_at)
320 << ND->getDeclName();
321 else
322 S.Diag(ND->getLocation(), diag::note_previous_decl)
323 << (isa<ObjCCategoryDecl>(ND) ? "category" : "class");
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000324}
325
Fariborz Jahanianbd0642f2011-08-31 17:37:55 +0000326/// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
327/// pool.
328void Sema::AddAnyMethodToGlobalPool(Decl *D) {
329 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
Fangrui Song6907ce22018-07-30 19:24:48 +0000330
Fariborz Jahanianbd0642f2011-08-31 17:37:55 +0000331 // If we don't have a valid method decl, simply return.
332 if (!MDecl)
333 return;
334 if (MDecl->isInstanceMethod())
335 AddInstanceMethodToGlobalPool(MDecl, true);
336 else
337 AddFactoryMethodToGlobalPool(MDecl, true);
338}
339
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000340/// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
341/// has explicit ownership attribute; false otherwise.
342static bool
343HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
344 QualType T = Param->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000345
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000346 if (const PointerType *PT = T->getAs<PointerType>()) {
347 T = PT->getPointeeType();
348 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
349 T = RT->getPointeeType();
350 } else {
351 return true;
352 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000353
354 // If we have a lifetime qualifier, but it's local, we must have
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000355 // inferred it. So, it is implicit.
356 return !T.getLocalQualifiers().hasObjCLifetime();
357}
358
Fariborz Jahanian18d0a5d2012-08-08 23:41:08 +0000359/// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
360/// and user declared, in the method definition's AST.
361void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
Akira Hatanakaac57af32019-04-17 23:14:44 +0000362 ImplicitlyRetainedSelfLocs.clear();
Craig Topperc3ec1492014-05-26 06:22:03 +0000363 assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
John McCall48871652010-08-21 09:40:31 +0000364 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
Fangrui Song6907ce22018-07-30 19:24:48 +0000365
Leonard Chanbf5fe2d2018-12-06 00:10:36 +0000366 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
367
Steve Naroff542cd5d2008-07-25 17:57:26 +0000368 // If we don't have a valid method decl, simply return.
369 if (!MDecl)
370 return;
Steve Naroff1d2538c2007-12-18 01:30:32 +0000371
Akira Hatanakaff6c4f32018-04-12 06:01:41 +0000372 QualType ResultType = MDecl->getReturnType();
373 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
374 !MDecl->isInvalidDecl() &&
375 RequireCompleteType(MDecl->getLocation(), ResultType,
376 diag::err_func_def_incomplete_result))
377 MDecl->setInvalidDecl();
378
Chris Lattnerda463fe2007-12-12 07:09:47 +0000379 // Allow all of Sema to see that we are entering a method definition.
Douglas Gregor91f84212008-12-11 16:49:14 +0000380 PushDeclContext(FnBodyScope, MDecl);
Douglas Gregor9a28e842010-03-01 23:15:13 +0000381 PushFunctionScope();
Fangrui Song6907ce22018-07-30 19:24:48 +0000382
Chris Lattnerda463fe2007-12-12 07:09:47 +0000383 // Create Decl objects for each parameter, entrring them in the scope for
384 // binding to their use.
Chris Lattnerda463fe2007-12-12 07:09:47 +0000385
386 // Insert the invisible arguments, self and _cmd!
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000387 MDecl->createImplicitParams(Context, MDecl->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000388
Daniel Dunbar279d1cc2008-08-26 06:07:48 +0000389 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
390 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000391
Reid Kleckner5a115802013-06-24 14:38:26 +0000392 // The ObjC parser requires parameter names so there's no need to check.
David Majnemer59f77922016-06-24 04:05:48 +0000393 CheckParmsForFunctionDef(MDecl->parameters(),
Reid Kleckner5a115802013-06-24 14:38:26 +0000394 /*CheckParameterNames=*/false);
395
Chris Lattner58258242008-04-10 02:22:51 +0000396 // Introduce all of the other parameters into this scope.
David Majnemer59f77922016-06-24 04:05:48 +0000397 for (auto *Param : MDecl->parameters()) {
Fariborz Jahanianb3e87122010-09-17 22:07:07 +0000398 if (!Param->isInvalidDecl() &&
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000399 getLangOpts().ObjCAutoRefCount &&
400 !HasExplicitOwnershipAttr(*this, Param))
401 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
402 Param->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000403
Aaron Ballman43b68be2014-03-07 17:50:17 +0000404 if (Param->getIdentifier())
405 PushOnScopeChains(Param, FnBodyScope);
Fariborz Jahanianb3e87122010-09-17 22:07:07 +0000406 }
John McCall31168b02011-06-15 23:02:42 +0000407
408 // In ARC, disallow definition of retain/release/autorelease/retainCount
David Blaikiebbafb8a2012-03-11 07:00:24 +0000409 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +0000410 switch (MDecl->getMethodFamily()) {
411 case OMF_retain:
412 case OMF_retainCount:
413 case OMF_release:
414 case OMF_autorelease:
415 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
Fariborz Jahanian39d1c422013-05-16 19:08:44 +0000416 << 0 << MDecl->getSelector();
John McCall31168b02011-06-15 23:02:42 +0000417 break;
418
419 case OMF_None:
420 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +0000421 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +0000422 case OMF_alloc:
423 case OMF_init:
424 case OMF_mutableCopy:
425 case OMF_copy:
426 case OMF_new:
427 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +0000428 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +0000429 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +0000430 break;
431 }
432 }
433
Nico Weber715abaf2011-08-22 17:25:57 +0000434 // Warn on deprecated methods under -Wdeprecated-implementations,
435 // and prepare for warning on missing super calls.
436 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000437 ObjCMethodDecl *IMD =
Fariborz Jahanian566fff02012-09-07 23:46:23 +0000438 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
Fangrui Song6907ce22018-07-30 19:24:48 +0000439
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000440 if (IMD) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000441 ObjCImplDecl *ImplDeclOfMethodDef =
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000442 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
Fangrui Song6907ce22018-07-30 19:24:48 +0000443 ObjCContainerDecl *ContDeclOfMethodDecl =
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000444 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
Craig Topperc3ec1492014-05-26 06:22:03 +0000445 ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000446 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
447 ImplDeclOfMethodDecl = OID->getImplementation();
Fariborz Jahanianed39e7c2014-03-18 16:25:22 +0000448 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
449 if (CD->IsClassExtension()) {
450 if (ObjCInterfaceDecl *OID = CD->getClassInterface())
451 ImplDeclOfMethodDecl = OID->getImplementation();
452 } else
453 ImplDeclOfMethodDecl = CD->getImplementation();
Fariborz Jahanian19a08bb2014-03-18 00:10:37 +0000454 }
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000455 // No need to issue deprecated warning if deprecated mehod in class/category
456 // is being implemented in its own implementation (no overriding is involved).
Fariborz Jahanianed39e7c2014-03-18 16:25:22 +0000457 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000458 DiagnoseObjCImplementedDeprecations(*this, IMD, MDecl->getLocation());
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000459 }
Nico Weber715abaf2011-08-22 17:25:57 +0000460
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000461 if (MDecl->getMethodFamily() == OMF_init) {
462 if (MDecl->isDesignatedInitializerForTheInterface()) {
463 getCurFunction()->ObjCIsDesignatedInit = true;
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +0000464 getCurFunction()->ObjCWarnForNoDesignatedInitChain =
Craig Topperc3ec1492014-05-26 06:22:03 +0000465 IC->getSuperClass() != nullptr;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000466 } else if (IC->hasDesignatedInitializers()) {
467 getCurFunction()->ObjCIsSecondaryInit = true;
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +0000468 getCurFunction()->ObjCWarnForNoInitDelegation = true;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000469 }
470 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +0000471
Nico Weber1fb82662011-08-28 22:35:17 +0000472 // If this is "dealloc" or "finalize", set some bit here.
Nico Weber715abaf2011-08-22 17:25:57 +0000473 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
474 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
475 // Only do this if the current class actually has a superclass.
Jordan Rosed03d99d2013-03-05 01:27:54 +0000476 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
Jordan Rose2afd6612012-10-19 16:05:26 +0000477 ObjCMethodFamily Family = MDecl->getMethodFamily();
478 if (Family == OMF_dealloc) {
479 if (!(getLangOpts().ObjCAutoRefCount ||
480 getLangOpts().getGC() == LangOptions::GCOnly))
481 getCurFunction()->ObjCShouldCallSuper = true;
482
483 } else if (Family == OMF_finalize) {
484 if (Context.getLangOpts().getGC() != LangOptions::NonGC)
485 getCurFunction()->ObjCShouldCallSuper = true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000486
Fariborz Jahaniance4bbb22013-11-05 00:28:21 +0000487 } else {
Jordan Rose2afd6612012-10-19 16:05:26 +0000488 const ObjCMethodDecl *SuperMethod =
Jordan Rosed03d99d2013-03-05 01:27:54 +0000489 SuperClass->lookupMethod(MDecl->getSelector(),
490 MDecl->isInstanceMethod());
Fangrui Song6907ce22018-07-30 19:24:48 +0000491 getCurFunction()->ObjCShouldCallSuper =
Jordan Rose2afd6612012-10-19 16:05:26 +0000492 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
Fariborz Jahaniand6876b22012-09-10 18:04:25 +0000493 }
Nico Weber1fb82662011-08-28 22:35:17 +0000494 }
Nico Weber715abaf2011-08-22 17:25:57 +0000495 }
Chris Lattnerda463fe2007-12-12 07:09:47 +0000496}
497
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000498namespace {
499
500// Callback to only accept typo corrections that are Objective-C classes.
501// If an ObjCInterfaceDecl* is given to the constructor, then the validation
502// function will reject corrections to that class.
Bruno Ricci70ad3962019-03-25 17:08:51 +0000503class ObjCInterfaceValidatorCCC final : public CorrectionCandidateCallback {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000504 public:
Craig Topperc3ec1492014-05-26 06:22:03 +0000505 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000506 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
507 : CurrentIDecl(IDecl) {}
508
Craig Toppere14c0f82014-03-12 04:55:44 +0000509 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000510 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
511 return ID && !declaresSameEntity(ID, CurrentIDecl);
512 }
513
Bruno Ricci70ad3962019-03-25 17:08:51 +0000514 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000515 return std::make_unique<ObjCInterfaceValidatorCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +0000516 }
517
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000518 private:
519 ObjCInterfaceDecl *CurrentIDecl;
520};
521
Hans Wennborgdcfba332015-10-06 23:40:43 +0000522} // end anonymous namespace
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000523
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +0000524static void diagnoseUseOfProtocols(Sema &TheSema,
525 ObjCContainerDecl *CD,
526 ObjCProtocolDecl *const *ProtoRefs,
527 unsigned NumProtoRefs,
528 const SourceLocation *ProtoLocs) {
529 assert(ProtoRefs);
530 // Diagnose availability in the context of the ObjC container.
531 Sema::ContextRAII SavedContext(TheSema, CD);
532 for (unsigned i = 0; i < NumProtoRefs; ++i) {
Alex Lorenzcdd596f2017-07-07 09:15:29 +0000533 (void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i],
534 /*UnknownObjCClass=*/nullptr,
535 /*ObjCPropertyAccess=*/false,
536 /*AvoidPartialAvailabilityChecks=*/true);
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +0000537 }
538}
539
Douglas Gregore9d95f12015-07-07 03:57:35 +0000540void Sema::
541ActOnSuperClassOfClassInterface(Scope *S,
542 SourceLocation AtInterfaceLoc,
543 ObjCInterfaceDecl *IDecl,
544 IdentifierInfo *ClassName,
545 SourceLocation ClassLoc,
546 IdentifierInfo *SuperName,
547 SourceLocation SuperLoc,
548 ArrayRef<ParsedType> SuperTypeArgs,
549 SourceRange SuperTypeArgsRange) {
550 // Check if a different kind of symbol declared in this scope.
551 NamedDecl *PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
552 LookupOrdinaryName);
553
554 if (!PrevDecl) {
555 // Try to correct for a typo in the superclass name without correcting
556 // to the class we're defining.
Bruno Ricci70ad3962019-03-25 17:08:51 +0000557 ObjCInterfaceValidatorCCC CCC(IDecl);
Douglas Gregore9d95f12015-07-07 03:57:35 +0000558 if (TypoCorrection Corrected = CorrectTypo(
Bruno Ricci70ad3962019-03-25 17:08:51 +0000559 DeclarationNameInfo(SuperName, SuperLoc), LookupOrdinaryName,
560 TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
Douglas Gregore9d95f12015-07-07 03:57:35 +0000561 diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
562 << SuperName << ClassName);
563 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
564 }
565 }
566
567 if (declaresSameEntity(PrevDecl, IDecl)) {
568 Diag(SuperLoc, diag::err_recursive_superclass)
569 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
570 IDecl->setEndOfDefinitionLoc(ClassLoc);
571 } else {
572 ObjCInterfaceDecl *SuperClassDecl =
573 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
574 QualType SuperClassType;
575
576 // Diagnose classes that inherit from deprecated classes.
577 if (SuperClassDecl) {
578 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
579 SuperClassType = Context.getObjCInterfaceType(SuperClassDecl);
580 }
581
Hans Wennborgdcfba332015-10-06 23:40:43 +0000582 if (PrevDecl && !SuperClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +0000583 // The previous declaration was not a class decl. Check if we have a
584 // typedef. If we do, get the underlying class type.
585 if (const TypedefNameDecl *TDecl =
586 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
587 QualType T = TDecl->getUnderlyingType();
588 if (T->isObjCObjectType()) {
589 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
590 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
591 SuperClassType = Context.getTypeDeclType(TDecl);
592
593 // This handles the following case:
594 // @interface NewI @end
595 // typedef NewI DeprI __attribute__((deprecated("blah")))
596 // @interface SI : DeprI /* warn here */ @end
597 (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
598 }
599 }
600 }
601
602 // This handles the following case:
603 //
604 // typedef int SuperClass;
605 // @interface MyClass : SuperClass {} @end
606 //
607 if (!SuperClassDecl) {
608 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
609 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
610 }
611 }
612
613 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
614 if (!SuperClassDecl)
615 Diag(SuperLoc, diag::err_undef_superclass)
616 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
617 else if (RequireCompleteType(SuperLoc,
618 SuperClassType,
619 diag::err_forward_superclass,
620 SuperClassDecl->getDeclName(),
621 ClassName,
622 SourceRange(AtInterfaceLoc, ClassLoc))) {
Hans Wennborgdcfba332015-10-06 23:40:43 +0000623 SuperClassDecl = nullptr;
Douglas Gregore9d95f12015-07-07 03:57:35 +0000624 SuperClassType = QualType();
625 }
626 }
627
628 if (SuperClassType.isNull()) {
629 assert(!SuperClassDecl && "Failed to set SuperClassType?");
630 return;
631 }
632
633 // Handle type arguments on the superclass.
634 TypeSourceInfo *SuperClassTInfo = nullptr;
Fangrui Song6907ce22018-07-30 19:24:48 +0000635 if (!SuperTypeArgs.empty()) {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000636 TypeResult fullSuperClassType = actOnObjCTypeArgsAndProtocolQualifiers(
637 S,
638 SuperLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +0000639 CreateParsedType(SuperClassType,
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000640 nullptr),
641 SuperTypeArgsRange.getBegin(),
642 SuperTypeArgs,
643 SuperTypeArgsRange.getEnd(),
644 SourceLocation(),
645 { },
646 { },
647 SourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +0000648 if (!fullSuperClassType.isUsable())
649 return;
650
Fangrui Song6907ce22018-07-30 19:24:48 +0000651 SuperClassType = GetTypeFromParser(fullSuperClassType.get(),
Douglas Gregore9d95f12015-07-07 03:57:35 +0000652 &SuperClassTInfo);
653 }
654
655 if (!SuperClassTInfo) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000656 SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType,
Douglas Gregore9d95f12015-07-07 03:57:35 +0000657 SuperLoc);
658 }
659
660 IDecl->setSuperClass(SuperClassTInfo);
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000661 IDecl->setEndOfDefinitionLoc(SuperClassTInfo->getTypeLoc().getEndLoc());
Douglas Gregore9d95f12015-07-07 03:57:35 +0000662 }
663}
664
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000665DeclResult Sema::actOnObjCTypeParam(Scope *S,
666 ObjCTypeParamVariance variance,
667 SourceLocation varianceLoc,
668 unsigned index,
Douglas Gregore83b9562015-07-07 03:57:53 +0000669 IdentifierInfo *paramName,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000670 SourceLocation paramLoc,
671 SourceLocation colonLoc,
672 ParsedType parsedTypeBound) {
673 // If there was an explicitly-provided type bound, check it.
674 TypeSourceInfo *typeBoundInfo = nullptr;
675 if (parsedTypeBound) {
676 // The type bound can be any Objective-C pointer type.
677 QualType typeBound = GetTypeFromParser(parsedTypeBound, &typeBoundInfo);
678 if (typeBound->isObjCObjectPointerType()) {
679 // okay
680 } else if (typeBound->isObjCObjectType()) {
681 // The user forgot the * on an Objective-C pointer type, e.g.,
682 // "T : NSView".
Craig Topper07fa1762015-11-15 02:31:46 +0000683 SourceLocation starLoc = getLocForEndOfToken(
Douglas Gregor85f3f952015-07-07 03:57:15 +0000684 typeBoundInfo->getTypeLoc().getEndLoc());
685 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
686 diag::err_objc_type_param_bound_missing_pointer)
687 << typeBound << paramName
688 << FixItHint::CreateInsertion(starLoc, " *");
689
690 // Create a new type location builder so we can update the type
691 // location information we have.
692 TypeLocBuilder builder;
693 builder.pushFullCopy(typeBoundInfo->getTypeLoc());
694
695 // Create the Objective-C pointer type.
696 typeBound = Context.getObjCObjectPointerType(typeBound);
697 ObjCObjectPointerTypeLoc newT
698 = builder.push<ObjCObjectPointerTypeLoc>(typeBound);
699 newT.setStarLoc(starLoc);
700
701 // Form the new type source information.
702 typeBoundInfo = builder.getTypeSourceInfo(Context, typeBound);
703 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +0000704 // Not a valid type bound.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000705 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
706 diag::err_objc_type_param_bound_nonobject)
707 << typeBound << paramName;
708
709 // Forget the bound; we'll default to id later.
710 typeBoundInfo = nullptr;
711 }
Douglas Gregore83b9562015-07-07 03:57:53 +0000712
John McCall69975252015-09-23 22:14:21 +0000713 // Type bounds cannot have qualifiers (even indirectly) or explicit
714 // nullability.
Douglas Gregore83b9562015-07-07 03:57:53 +0000715 if (typeBoundInfo) {
John McCall69975252015-09-23 22:14:21 +0000716 QualType typeBound = typeBoundInfo->getType();
717 TypeLoc qual = typeBoundInfo->getTypeLoc().findExplicitQualifierLoc();
718 if (qual || typeBound.hasQualifiers()) {
719 bool diagnosed = false;
720 SourceRange rangeToRemove;
721 if (qual) {
722 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
723 rangeToRemove = attr.getLocalSourceRange();
724 if (attr.getTypePtr()->getImmediateNullability()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000725 Diag(attr.getBeginLoc(),
John McCall69975252015-09-23 22:14:21 +0000726 diag::err_objc_type_param_bound_explicit_nullability)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000727 << paramName << typeBound
728 << FixItHint::CreateRemoval(rangeToRemove);
John McCall69975252015-09-23 22:14:21 +0000729 diagnosed = true;
730 }
731 }
732 }
733
734 if (!diagnosed) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000735 Diag(qual ? qual.getBeginLoc()
736 : typeBoundInfo->getTypeLoc().getBeginLoc(),
737 diag::err_objc_type_param_bound_qualified)
738 << paramName << typeBound
739 << typeBound.getQualifiers().getAsString()
740 << FixItHint::CreateRemoval(rangeToRemove);
John McCall69975252015-09-23 22:14:21 +0000741 }
742
743 // If the type bound has qualifiers other than CVR, we need to strip
744 // them or we'll probably assert later when trying to apply new
745 // qualifiers.
746 Qualifiers quals = typeBound.getQualifiers();
747 quals.removeCVRQualifiers();
748 if (!quals.empty()) {
749 typeBoundInfo =
750 Context.getTrivialTypeSourceInfo(typeBound.getUnqualifiedType());
751 }
Douglas Gregore83b9562015-07-07 03:57:53 +0000752 }
753 }
Douglas Gregor85f3f952015-07-07 03:57:15 +0000754 }
755
756 // If there was no explicit type bound (or we removed it due to an error),
757 // use 'id' instead.
758 if (!typeBoundInfo) {
759 colonLoc = SourceLocation();
760 typeBoundInfo = Context.getTrivialTypeSourceInfo(Context.getObjCIdType());
761 }
762
763 // Create the type parameter.
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000764 return ObjCTypeParamDecl::Create(Context, CurContext, variance, varianceLoc,
765 index, paramLoc, paramName, colonLoc,
766 typeBoundInfo);
Douglas Gregor85f3f952015-07-07 03:57:15 +0000767}
768
769ObjCTypeParamList *Sema::actOnObjCTypeParamList(Scope *S,
770 SourceLocation lAngleLoc,
771 ArrayRef<Decl *> typeParamsIn,
772 SourceLocation rAngleLoc) {
773 // We know that the array only contains Objective-C type parameters.
774 ArrayRef<ObjCTypeParamDecl *>
775 typeParams(
776 reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()),
777 typeParamsIn.size());
778
779 // Diagnose redeclarations of type parameters.
780 // We do this now because Objective-C type parameters aren't pushed into
781 // scope until later (after the instance variable block), but we want the
782 // diagnostics to occur right after we parse the type parameter list.
783 llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams;
784 for (auto typeParam : typeParams) {
785 auto known = knownParams.find(typeParam->getIdentifier());
786 if (known != knownParams.end()) {
787 Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl)
788 << typeParam->getIdentifier()
789 << SourceRange(known->second->getLocation());
790
791 typeParam->setInvalidDecl();
792 } else {
793 knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam));
794
795 // Push the type parameter into scope.
796 PushOnScopeChains(typeParam, S, /*AddToContext=*/false);
797 }
798 }
799
800 // Create the parameter list.
801 return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc);
802}
803
804void Sema::popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList) {
805 for (auto typeParam : *typeParamList) {
806 if (!typeParam->isInvalidDecl()) {
807 S->RemoveDecl(typeParam);
808 IdResolver.RemoveDecl(typeParam);
809 }
810 }
811}
812
813namespace {
814 /// The context in which an Objective-C type parameter list occurs, for use
815 /// in diagnostics.
816 enum class TypeParamListContext {
817 ForwardDeclaration,
818 Definition,
819 Category,
820 Extension
821 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000822} // end anonymous namespace
Douglas Gregor85f3f952015-07-07 03:57:15 +0000823
824/// Check consistency between two Objective-C type parameter lists, e.g.,
NAKAMURA Takumi4c3ab452015-07-08 02:35:56 +0000825/// between a category/extension and an \@interface or between an \@class and an
826/// \@interface.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000827static bool checkTypeParamListConsistency(Sema &S,
828 ObjCTypeParamList *prevTypeParams,
829 ObjCTypeParamList *newTypeParams,
830 TypeParamListContext newContext) {
831 // If the sizes don't match, complain about that.
832 if (prevTypeParams->size() != newTypeParams->size()) {
833 SourceLocation diagLoc;
834 if (newTypeParams->size() > prevTypeParams->size()) {
835 diagLoc = newTypeParams->begin()[prevTypeParams->size()]->getLocation();
836 } else {
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000837 diagLoc = S.getLocForEndOfToken(newTypeParams->back()->getEndLoc());
Douglas Gregor85f3f952015-07-07 03:57:15 +0000838 }
839
840 S.Diag(diagLoc, diag::err_objc_type_param_arity_mismatch)
841 << static_cast<unsigned>(newContext)
842 << (newTypeParams->size() > prevTypeParams->size())
843 << prevTypeParams->size()
844 << newTypeParams->size();
845
846 return true;
847 }
848
849 // Match up the type parameters.
850 for (unsigned i = 0, n = prevTypeParams->size(); i != n; ++i) {
851 ObjCTypeParamDecl *prevTypeParam = prevTypeParams->begin()[i];
852 ObjCTypeParamDecl *newTypeParam = newTypeParams->begin()[i];
853
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000854 // Check for consistency of the variance.
855 if (newTypeParam->getVariance() != prevTypeParam->getVariance()) {
856 if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant &&
857 newContext != TypeParamListContext::Definition) {
858 // When the new type parameter is invariant and is not part
859 // of the definition, just propagate the variance.
860 newTypeParam->setVariance(prevTypeParam->getVariance());
Fangrui Song6907ce22018-07-30 19:24:48 +0000861 } else if (prevTypeParam->getVariance()
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000862 == ObjCTypeParamVariance::Invariant &&
863 !(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) &&
864 cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext())
865 ->getDefinition() == prevTypeParam->getDeclContext())) {
866 // When the old parameter is invariant and was not part of the
867 // definition, just ignore the difference because it doesn't
868 // matter.
869 } else {
870 {
871 // Diagnose the conflict and update the second declaration.
872 SourceLocation diagLoc = newTypeParam->getVarianceLoc();
873 if (diagLoc.isInvalid())
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000874 diagLoc = newTypeParam->getBeginLoc();
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000875
876 auto diag = S.Diag(diagLoc,
877 diag::err_objc_type_param_variance_conflict)
878 << static_cast<unsigned>(newTypeParam->getVariance())
879 << newTypeParam->getDeclName()
880 << static_cast<unsigned>(prevTypeParam->getVariance())
881 << prevTypeParam->getDeclName();
882 switch (prevTypeParam->getVariance()) {
883 case ObjCTypeParamVariance::Invariant:
884 diag << FixItHint::CreateRemoval(newTypeParam->getVarianceLoc());
885 break;
886
887 case ObjCTypeParamVariance::Covariant:
888 case ObjCTypeParamVariance::Contravariant: {
889 StringRef newVarianceStr
890 = prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant
891 ? "__covariant"
892 : "__contravariant";
893 if (newTypeParam->getVariance()
894 == ObjCTypeParamVariance::Invariant) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000895 diag << FixItHint::CreateInsertion(newTypeParam->getBeginLoc(),
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000896 (newVarianceStr + " ").str());
897 } else {
898 diag << FixItHint::CreateReplacement(newTypeParam->getVarianceLoc(),
899 newVarianceStr);
900 }
901 }
902 }
903 }
904
905 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
906 << prevTypeParam->getDeclName();
907
908 // Override the variance.
909 newTypeParam->setVariance(prevTypeParam->getVariance());
910 }
911 }
912
Douglas Gregor85f3f952015-07-07 03:57:15 +0000913 // If the bound types match, there's nothing to do.
914 if (S.Context.hasSameType(prevTypeParam->getUnderlyingType(),
915 newTypeParam->getUnderlyingType()))
916 continue;
917
918 // If the new type parameter's bound was explicit, complain about it being
919 // different from the original.
920 if (newTypeParam->hasExplicitBound()) {
921 SourceRange newBoundRange = newTypeParam->getTypeSourceInfo()
922 ->getTypeLoc().getSourceRange();
923 S.Diag(newBoundRange.getBegin(), diag::err_objc_type_param_bound_conflict)
924 << newTypeParam->getUnderlyingType()
925 << newTypeParam->getDeclName()
926 << prevTypeParam->hasExplicitBound()
927 << prevTypeParam->getUnderlyingType()
928 << (newTypeParam->getDeclName() == prevTypeParam->getDeclName())
929 << prevTypeParam->getDeclName()
930 << FixItHint::CreateReplacement(
931 newBoundRange,
932 prevTypeParam->getUnderlyingType().getAsString(
933 S.Context.getPrintingPolicy()));
934
935 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
936 << prevTypeParam->getDeclName();
937
938 // Override the new type parameter's bound type with the previous type,
939 // so that it's consistent.
940 newTypeParam->setTypeSourceInfo(
941 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
942 continue;
943 }
944
945 // The new type parameter got the implicit bound of 'id'. That's okay for
946 // categories and extensions (overwrite it later), but not for forward
947 // declarations and @interfaces, because those must be standalone.
948 if (newContext == TypeParamListContext::ForwardDeclaration ||
949 newContext == TypeParamListContext::Definition) {
950 // Diagnose this problem for forward declarations and definitions.
951 SourceLocation insertionLoc
Craig Topper07fa1762015-11-15 02:31:46 +0000952 = S.getLocForEndOfToken(newTypeParam->getLocation());
Douglas Gregor85f3f952015-07-07 03:57:15 +0000953 std::string newCode
954 = " : " + prevTypeParam->getUnderlyingType().getAsString(
955 S.Context.getPrintingPolicy());
956 S.Diag(newTypeParam->getLocation(),
957 diag::err_objc_type_param_bound_missing)
958 << prevTypeParam->getUnderlyingType()
959 << newTypeParam->getDeclName()
960 << (newContext == TypeParamListContext::ForwardDeclaration)
961 << FixItHint::CreateInsertion(insertionLoc, newCode);
962
963 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
964 << prevTypeParam->getDeclName();
965 }
966
967 // Update the new type parameter's bound to match the previous one.
968 newTypeParam->setTypeSourceInfo(
969 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
970 }
971
972 return false;
973}
974
Erich Keanec480f302018-07-12 21:09:05 +0000975Decl *Sema::ActOnStartClassInterface(
976 Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
977 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
978 IdentifierInfo *SuperName, SourceLocation SuperLoc,
979 ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
980 Decl *const *ProtoRefs, unsigned NumProtoRefs,
981 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
982 const ParsedAttributesView &AttrList) {
Chris Lattnerda463fe2007-12-12 07:09:47 +0000983 assert(ClassName && "Missing class identifier");
Mike Stump11289f42009-09-09 15:08:12 +0000984
Chris Lattnerda463fe2007-12-12 07:09:47 +0000985 // Check for another declaration kind with the same name.
Richard Smithbecb92d2017-10-10 22:33:17 +0000986 NamedDecl *PrevDecl =
987 LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
988 forRedeclarationInCurContext());
Douglas Gregor5101c242008-12-05 18:15:24 +0000989
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000990 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +0000991 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Chris Lattner0369c572008-11-23 23:12:31 +0000992 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +0000993 }
Mike Stump11289f42009-09-09 15:08:12 +0000994
Douglas Gregordc9166c2011-12-15 20:29:51 +0000995 // Create a declaration to describe this @interface.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +0000996 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidisdd710632013-06-18 21:26:33 +0000997
998 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
999 // A previous decl with a different name is because of
1000 // @compatibility_alias, for example:
1001 // \code
1002 // @class NewImage;
1003 // @compatibility_alias OldImage NewImage;
1004 // \endcode
1005 // A lookup for 'OldImage' will return the 'NewImage' decl.
1006 //
1007 // In such a case use the real declaration name, instead of the alias one,
1008 // otherwise we will break IdentifierResolver and redecls-chain invariants.
1009 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
1010 // has been aliased.
1011 ClassName = PrevIDecl->getIdentifier();
1012 }
1013
Douglas Gregor85f3f952015-07-07 03:57:15 +00001014 // If there was a forward declaration with type parameters, check
1015 // for consistency.
1016 if (PrevIDecl) {
1017 if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) {
1018 if (typeParamList) {
1019 // Both have type parameter lists; check for consistency.
Fangrui Song6907ce22018-07-30 19:24:48 +00001020 if (checkTypeParamListConsistency(*this, prevTypeParamList,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001021 typeParamList,
1022 TypeParamListContext::Definition)) {
1023 typeParamList = nullptr;
1024 }
1025 } else {
1026 Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first)
1027 << ClassName;
1028 Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl)
1029 << ClassName;
1030
1031 // Clone the type parameter list.
1032 SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams;
1033 for (auto typeParam : *prevTypeParamList) {
1034 clonedTypeParams.push_back(
1035 ObjCTypeParamDecl::Create(
1036 Context,
1037 CurContext,
Douglas Gregor1ac1b632015-07-07 03:58:54 +00001038 typeParam->getVariance(),
1039 SourceLocation(),
Douglas Gregore83b9562015-07-07 03:57:53 +00001040 typeParam->getIndex(),
Douglas Gregor85f3f952015-07-07 03:57:15 +00001041 SourceLocation(),
1042 typeParam->getIdentifier(),
1043 SourceLocation(),
1044 Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType())));
1045 }
1046
Fangrui Song6907ce22018-07-30 19:24:48 +00001047 typeParamList = ObjCTypeParamList::create(Context,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001048 SourceLocation(),
1049 clonedTypeParams,
1050 SourceLocation());
1051 }
1052 }
1053 }
1054
Douglas Gregordc9166c2011-12-15 20:29:51 +00001055 ObjCInterfaceDecl *IDecl
1056 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001057 typeParamList, PrevIDecl, ClassLoc);
Douglas Gregordc9166c2011-12-15 20:29:51 +00001058 if (PrevIDecl) {
1059 // Class already seen. Was it a definition?
1060 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
1061 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
1062 << PrevIDecl->getDeclName();
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001063 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregordc9166c2011-12-15 20:29:51 +00001064 IDecl->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00001065 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001066 }
Erich Keanec480f302018-07-12 21:09:05 +00001067
1068 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001069 AddPragmaAttributes(TUScope, IDecl);
Douglas Gregordc9166c2011-12-15 20:29:51 +00001070 PushOnScopeChains(IDecl, TUScope);
Mike Stump11289f42009-09-09 15:08:12 +00001071
Fangrui Song6907ce22018-07-30 19:24:48 +00001072 // Start the definition of this class. If we're in a redefinition case, there
Douglas Gregordc9166c2011-12-15 20:29:51 +00001073 // may already be a definition, so we'll end up adding to it.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001074 if (!IDecl->hasDefinition())
1075 IDecl->startDefinition();
Fangrui Song6907ce22018-07-30 19:24:48 +00001076
Chris Lattnerda463fe2007-12-12 07:09:47 +00001077 if (SuperName) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001078 // Diagnose availability in the context of the @interface.
1079 ContextRAII SavedContext(*this, IDecl);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001080
Fangrui Song6907ce22018-07-30 19:24:48 +00001081 ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl,
1082 ClassName, ClassLoc,
1083 SuperName, SuperLoc, SuperTypeArgs,
Douglas Gregore9d95f12015-07-07 03:57:35 +00001084 SuperTypeArgsRange);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001085 } else { // we have a root class.
Douglas Gregor16408322011-12-15 22:34:59 +00001086 IDecl->setEndOfDefinitionLoc(ClassLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001087 }
Mike Stump11289f42009-09-09 15:08:12 +00001088
Sebastian Redle7c1fe62010-08-13 00:28:03 +00001089 // Check then save referenced protocols.
Chris Lattnerdf59f5a2008-07-26 04:13:19 +00001090 if (NumProtoRefs) {
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001091 diagnoseUseOfProtocols(*this, IDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1092 NumProtoRefs, ProtoLocs);
Roman Divackye6377112012-09-06 15:59:27 +00001093 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001094 ProtoLocs, Context);
Douglas Gregor16408322011-12-15 22:34:59 +00001095 IDecl->setEndOfDefinitionLoc(EndProtoLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001096 }
Mike Stump11289f42009-09-09 15:08:12 +00001097
Anders Carlssona6b508a2008-11-04 16:57:32 +00001098 CheckObjCDeclScope(IDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001099 return ActOnObjCContainerStartDefinition(IDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001100}
1101
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001102/// ActOnTypedefedProtocols - this action finds protocol list as part of the
1103/// typedef'ed use for a qualified super class and adds them to the list
1104/// of the protocols.
1105void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
Argyrios Kyrtzidisf95a0002016-11-09 02:47:07 +00001106 SmallVectorImpl<SourceLocation> &ProtocolLocs,
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001107 IdentifierInfo *SuperName,
1108 SourceLocation SuperLoc) {
1109 if (!SuperName)
1110 return;
1111 NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
1112 LookupOrdinaryName);
1113 if (!IDecl)
1114 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001115
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001116 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
1117 QualType T = TDecl->getUnderlyingType();
1118 if (T->isObjCObjectType())
Argyrios Kyrtzidisf95a0002016-11-09 02:47:07 +00001119 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>()) {
Benjamin Kramerf9890422015-02-17 16:48:30 +00001120 ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
Argyrios Kyrtzidisf95a0002016-11-09 02:47:07 +00001121 // FIXME: Consider whether this should be an invalid loc since the loc
1122 // is not actually pointing to a protocol name reference but to the
1123 // typedef reference. Note that the base class name loc is also pointing
1124 // at the typedef.
1125 ProtocolLocs.append(OPT->getNumProtocols(), SuperLoc);
1126 }
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001127 }
1128}
1129
Richard Smithac4e36d2012-08-08 23:32:13 +00001130/// ActOnCompatibilityAlias - this action is called after complete parsing of
James Dennett634962f2012-06-14 21:40:34 +00001131/// a \@compatibility_alias declaration. It sets up the alias relationships.
Richard Smithac4e36d2012-08-08 23:32:13 +00001132Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
1133 IdentifierInfo *AliasName,
1134 SourceLocation AliasLocation,
1135 IdentifierInfo *ClassName,
1136 SourceLocation ClassLocation) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00001137 // Look for previous declaration of alias name
Richard Smithbecb92d2017-10-10 22:33:17 +00001138 NamedDecl *ADecl =
1139 LookupSingleName(TUScope, AliasName, AliasLocation, LookupOrdinaryName,
1140 forRedeclarationInCurContext());
Chris Lattnerda463fe2007-12-12 07:09:47 +00001141 if (ADecl) {
Eli Friedmanfd6b3f82013-06-21 01:49:53 +00001142 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
Chris Lattnerd0685032008-11-23 23:20:13 +00001143 Diag(ADecl->getLocation(), diag::note_previous_declaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001144 return nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001145 }
1146 // Check for class declaration
Richard Smithbecb92d2017-10-10 22:33:17 +00001147 NamedDecl *CDeclU =
1148 LookupSingleName(TUScope, ClassName, ClassLocation, LookupOrdinaryName,
1149 forRedeclarationInCurContext());
Richard Smithdda56e42011-04-15 14:24:37 +00001150 if (const TypedefNameDecl *TDecl =
1151 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001152 QualType T = TDecl->getUnderlyingType();
John McCall8b07ec22010-05-15 11:32:37 +00001153 if (T->isObjCObjectType()) {
1154 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001155 ClassName = IDecl->getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001156 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
Richard Smithbecb92d2017-10-10 22:33:17 +00001157 LookupOrdinaryName,
1158 forRedeclarationInCurContext());
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001159 }
1160 }
1161 }
Chris Lattner219b3e92008-03-16 21:17:37 +00001162 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
Craig Topperc3ec1492014-05-26 06:22:03 +00001163 if (!CDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001164 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
Chris Lattner219b3e92008-03-16 21:17:37 +00001165 if (CDeclU)
Chris Lattnerd0685032008-11-23 23:20:13 +00001166 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001167 return nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001168 }
Mike Stump11289f42009-09-09 15:08:12 +00001169
Chris Lattner219b3e92008-03-16 21:17:37 +00001170 // Everything checked out, instantiate a new alias declaration AST.
Mike Stump11289f42009-09-09 15:08:12 +00001171 ObjCCompatibleAliasDecl *AliasDecl =
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001172 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001173
Anders Carlssona6b508a2008-11-04 16:57:32 +00001174 if (!CheckObjCDeclScope(AliasDecl))
Douglas Gregor38feed82009-04-24 02:57:34 +00001175 PushOnScopeChains(AliasDecl, TUScope);
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001176
John McCall48871652010-08-21 09:40:31 +00001177 return AliasDecl;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001178}
1179
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001180bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
Steve Naroff41d09ad2009-03-05 15:22:01 +00001181 IdentifierInfo *PName,
1182 SourceLocation &Ploc, SourceLocation PrevLoc,
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001183 const ObjCList<ObjCProtocolDecl> &PList) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001184
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001185 bool res = false;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001186 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
1187 E = PList.end(); I != E; ++I) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001188 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
1189 Ploc)) {
Steve Naroff41d09ad2009-03-05 15:22:01 +00001190 if (PDecl->getIdentifier() == PName) {
1191 Diag(Ploc, diag::err_protocol_has_circular_dependency);
1192 Diag(PrevLoc, diag::note_previous_definition);
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001193 res = true;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001194 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001195
Douglas Gregore6e48b12012-01-01 19:29:29 +00001196 if (!PDecl->hasDefinition())
1197 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00001198
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001199 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
1200 PDecl->getLocation(), PDecl->getReferencedProtocols()))
1201 res = true;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001202 }
1203 }
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001204 return res;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001205}
1206
Erich Keanec480f302018-07-12 21:09:05 +00001207Decl *Sema::ActOnStartProtocolInterface(
1208 SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
1209 SourceLocation ProtocolLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs,
1210 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
1211 const ParsedAttributesView &AttrList) {
Fariborz Jahaniancadf7c52011-05-12 22:04:39 +00001212 bool err = false;
Daniel Dunbar26e2ab42008-09-26 04:48:09 +00001213 // FIXME: Deal with AttrList.
Chris Lattnerda463fe2007-12-12 07:09:47 +00001214 assert(ProtocolName && "Missing protocol identifier");
Douglas Gregor32c17572012-01-01 20:30:41 +00001215 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
Richard Smithbecb92d2017-10-10 22:33:17 +00001216 forRedeclarationInCurContext());
Craig Topperc3ec1492014-05-26 06:22:03 +00001217 ObjCProtocolDecl *PDecl = nullptr;
1218 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
Douglas Gregor32c17572012-01-01 20:30:41 +00001219 // If we already have a definition, complain.
1220 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
1221 Diag(Def->getLocation(), diag::note_previous_definition);
Mike Stump11289f42009-09-09 15:08:12 +00001222
Douglas Gregor32c17572012-01-01 20:30:41 +00001223 // Create a new protocol that is completely distinct from previous
1224 // declarations, and do not make this protocol available for name lookup.
1225 // That way, we'll end up completely ignoring the duplicate.
1226 // FIXME: Can we turn this into an error?
1227 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
1228 ProtocolLoc, AtProtoInterfaceLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +00001229 /*PrevDecl=*/nullptr);
Bruno Cardoso Lopes7dcf23e2018-06-30 00:49:27 +00001230
1231 // If we are using modules, add the decl to the context in order to
1232 // serialize something meaningful.
1233 if (getLangOpts().Modules)
1234 PushOnScopeChains(PDecl, TUScope);
Douglas Gregor32c17572012-01-01 20:30:41 +00001235 PDecl->startDefinition();
1236 } else {
1237 if (PrevDecl) {
1238 // Check for circular dependencies among protocol declarations. This can
1239 // only happen if this protocol was forward-declared.
Argyrios Kyrtzidis95dfc122011-11-13 22:08:30 +00001240 ObjCList<ObjCProtocolDecl> PList;
1241 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
1242 err = CheckForwardProtocolDeclarationForCircularDependency(
Douglas Gregor32c17572012-01-01 20:30:41 +00001243 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
Argyrios Kyrtzidis95dfc122011-11-13 22:08:30 +00001244 }
Douglas Gregor32c17572012-01-01 20:30:41 +00001245
1246 // Create the new declaration.
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001247 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
Argyrios Kyrtzidis1f4bee52011-10-17 19:48:06 +00001248 ProtocolLoc, AtProtoInterfaceLoc,
Douglas Gregor05a1f4d2012-01-01 22:06:18 +00001249 /*PrevDecl=*/PrevDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00001250
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001251 PushOnScopeChains(PDecl, TUScope);
Douglas Gregore6e48b12012-01-01 19:29:29 +00001252 PDecl->startDefinition();
Chris Lattnerf87ca0a2008-03-16 01:23:04 +00001253 }
Erich Keanec480f302018-07-12 21:09:05 +00001254
1255 ProcessDeclAttributeList(TUScope, PDecl, AttrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001256 AddPragmaAttributes(TUScope, PDecl);
1257
Douglas Gregor32c17572012-01-01 20:30:41 +00001258 // Merge attributes from previous declarations.
1259 if (PrevDecl)
1260 mergeDeclAttributes(PDecl, PrevDecl);
1261
Fariborz Jahaniancadf7c52011-05-12 22:04:39 +00001262 if (!err && NumProtoRefs ) {
Chris Lattneracc04a92008-03-16 20:19:15 +00001263 /// Check then save referenced protocols.
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001264 diagnoseUseOfProtocols(*this, PDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1265 NumProtoRefs, ProtoLocs);
Roman Divackye6377112012-09-06 15:59:27 +00001266 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001267 ProtoLocs, Context);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001268 }
Mike Stump11289f42009-09-09 15:08:12 +00001269
1270 CheckObjCDeclScope(PDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001271 return ActOnObjCContainerStartDefinition(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001272}
1273
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001274static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
1275 ObjCProtocolDecl *&UndefinedProtocol) {
1276 if (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()) {
1277 UndefinedProtocol = PDecl;
1278 return true;
1279 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001280
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001281 for (auto *PI : PDecl->protocols())
1282 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
1283 UndefinedProtocol = PI;
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001284 return true;
1285 }
1286 return false;
1287}
1288
Chris Lattnerda463fe2007-12-12 07:09:47 +00001289/// FindProtocolDeclaration - This routine looks up protocols and
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00001290/// issues an error if they are not declared. It returns list of
1291/// protocol declarations in its 'Protocols' argument.
Chris Lattnerda463fe2007-12-12 07:09:47 +00001292void
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001293Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
Craig Toppera9247eb2015-10-22 04:59:56 +00001294 ArrayRef<IdentifierLocPair> ProtocolId,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001295 SmallVectorImpl<Decl *> &Protocols) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001296 for (const IdentifierLocPair &Pair : ProtocolId) {
1297 ObjCProtocolDecl *PDecl = LookupProtocol(Pair.first, Pair.second);
Chris Lattner9c1842b2008-07-26 03:47:43 +00001298 if (!PDecl) {
Bruno Ricci70ad3962019-03-25 17:08:51 +00001299 DeclFilterCCC<ObjCProtocolDecl> CCC{};
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001300 TypoCorrection Corrected = CorrectTypo(
Bruno Ricci70ad3962019-03-25 17:08:51 +00001301 DeclarationNameInfo(Pair.first, Pair.second), LookupObjCProtocolName,
1302 TUScope, nullptr, CCC, CTK_ErrorRecovery);
Richard Smithf9b15102013-08-17 00:46:16 +00001303 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
1304 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
Craig Toppera9247eb2015-10-22 04:59:56 +00001305 << Pair.first);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001306 }
1307
1308 if (!PDecl) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001309 Diag(Pair.second, diag::err_undeclared_protocol) << Pair.first;
Chris Lattner9c1842b2008-07-26 03:47:43 +00001310 continue;
1311 }
Fariborz Jahanianada44a22013-04-09 17:52:29 +00001312 // If this is a forward protocol declaration, get its definition.
1313 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
1314 PDecl = PDecl->getDefinition();
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001315
1316 // For an objc container, delay protocol reference checking until after we
1317 // can set the objc decl as the availability context, otherwise check now.
1318 if (!ForObjCContainer) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001319 (void)DiagnoseUseOfDecl(PDecl, Pair.second);
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001320 }
Chris Lattner9c1842b2008-07-26 03:47:43 +00001321
1322 // If this is a forward declaration and we are supposed to warn in this
1323 // case, do it.
Douglas Gregoreed49792013-01-17 00:38:46 +00001324 // FIXME: Recover nicely in the hidden case.
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001325 ObjCProtocolDecl *UndefinedProtocol;
Fangrui Song6907ce22018-07-30 19:24:48 +00001326
Douglas Gregoreed49792013-01-17 00:38:46 +00001327 if (WarnOnDeclarations &&
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001328 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001329 Diag(Pair.second, diag::warn_undef_protocolref) << Pair.first;
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001330 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
1331 << UndefinedProtocol;
1332 }
John McCall48871652010-08-21 09:40:31 +00001333 Protocols.push_back(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001334 }
1335}
1336
Benjamin Kramer8b851d02015-07-13 20:42:13 +00001337namespace {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001338// Callback to only accept typo corrections that are either
1339// Objective-C protocols or valid Objective-C type arguments.
Bruno Ricci70ad3962019-03-25 17:08:51 +00001340class ObjCTypeArgOrProtocolValidatorCCC final
1341 : public CorrectionCandidateCallback {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001342 ASTContext &Context;
1343 Sema::LookupNameKind LookupKind;
1344 public:
1345 ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context,
1346 Sema::LookupNameKind lookupKind)
1347 : Context(context), LookupKind(lookupKind) { }
1348
1349 bool ValidateCandidate(const TypoCorrection &candidate) override {
1350 // If we're allowed to find protocols and we have a protocol, accept it.
1351 if (LookupKind != Sema::LookupOrdinaryName) {
1352 if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>())
1353 return true;
1354 }
1355
1356 // If we're allowed to find type names and we have one, accept it.
1357 if (LookupKind != Sema::LookupObjCProtocolName) {
1358 // If we have a type declaration, we might accept this result.
1359 if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) {
1360 // If we found a tag declaration outside of C++, skip it. This
1361 // can happy because we look for any name when there is no
1362 // bias to protocol or type names.
1363 if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus)
1364 return false;
1365
1366 // Make sure the type is something we would accept as a type
1367 // argument.
1368 auto type = Context.getTypeDeclType(typeDecl);
1369 if (type->isObjCObjectPointerType() ||
1370 type->isBlockPointerType() ||
1371 type->isDependentType() ||
1372 type->isObjCObjectType())
1373 return true;
1374
1375 return false;
1376 }
1377
1378 // If we have an Objective-C class type, accept it; there will
1379 // be another fix to add the '*'.
1380 if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>())
1381 return true;
1382
1383 return false;
1384 }
1385
1386 return false;
1387 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00001388
1389 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001390 return std::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +00001391 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00001392};
Benjamin Kramer8b851d02015-07-13 20:42:13 +00001393} // end anonymous namespace
Douglas Gregore9d95f12015-07-07 03:57:35 +00001394
Bruno Cardoso Lopesc54768f2016-04-13 20:59:07 +00001395void Sema::DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
1396 SourceLocation ProtocolLoc,
1397 IdentifierInfo *TypeArgId,
1398 SourceLocation TypeArgLoc,
1399 bool SelectProtocolFirst) {
1400 Diag(TypeArgLoc, diag::err_objc_type_args_and_protocols)
1401 << SelectProtocolFirst << TypeArgId << ProtocolId
1402 << SourceRange(ProtocolLoc);
1403}
1404
Douglas Gregore9d95f12015-07-07 03:57:35 +00001405void Sema::actOnObjCTypeArgsOrProtocolQualifiers(
1406 Scope *S,
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001407 ParsedType baseType,
Douglas Gregore9d95f12015-07-07 03:57:35 +00001408 SourceLocation lAngleLoc,
1409 ArrayRef<IdentifierInfo *> identifiers,
1410 ArrayRef<SourceLocation> identifierLocs,
1411 SourceLocation rAngleLoc,
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001412 SourceLocation &typeArgsLAngleLoc,
1413 SmallVectorImpl<ParsedType> &typeArgs,
1414 SourceLocation &typeArgsRAngleLoc,
1415 SourceLocation &protocolLAngleLoc,
1416 SmallVectorImpl<Decl *> &protocols,
1417 SourceLocation &protocolRAngleLoc,
Douglas Gregore9d95f12015-07-07 03:57:35 +00001418 bool warnOnIncompleteProtocols) {
1419 // Local function that updates the declaration specifiers with
1420 // protocol information.
Douglas Gregore9d95f12015-07-07 03:57:35 +00001421 unsigned numProtocolsResolved = 0;
1422 auto resolvedAsProtocols = [&] {
1423 assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols");
Fangrui Song6907ce22018-07-30 19:24:48 +00001424
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001425 // Determine whether the base type is a parameterized class, in
1426 // which case we want to warn about typos such as
1427 // "NSArray<NSObject>" (that should be NSArray<NSObject *>).
1428 ObjCInterfaceDecl *baseClass = nullptr;
1429 QualType base = GetTypeFromParser(baseType, nullptr);
1430 bool allAreTypeNames = false;
1431 SourceLocation firstClassNameLoc;
1432 if (!base.isNull()) {
1433 if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) {
1434 baseClass = objcObjectType->getInterface();
1435 if (baseClass) {
1436 if (auto typeParams = baseClass->getTypeParamList()) {
1437 if (typeParams->size() == numProtocolsResolved) {
1438 // Note that we should be looking for type names, too.
1439 allAreTypeNames = true;
1440 }
1441 }
1442 }
1443 }
1444 }
1445
Douglas Gregore9d95f12015-07-07 03:57:35 +00001446 for (unsigned i = 0, n = protocols.size(); i != n; ++i) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001447 ObjCProtocolDecl *&proto
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001448 = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001449 // For an objc container, delay protocol reference checking until after we
1450 // can set the objc decl as the availability context, otherwise check now.
1451 if (!warnOnIncompleteProtocols) {
1452 (void)DiagnoseUseOfDecl(proto, identifierLocs[i]);
1453 }
1454
1455 // If this is a forward protocol declaration, get its definition.
1456 if (!proto->isThisDeclarationADefinition() && proto->getDefinition())
1457 proto = proto->getDefinition();
1458
1459 // If this is a forward declaration and we are supposed to warn in this
1460 // case, do it.
1461 // FIXME: Recover nicely in the hidden case.
1462 ObjCProtocolDecl *forwardDecl = nullptr;
1463 if (warnOnIncompleteProtocols &&
1464 NestedProtocolHasNoDefinition(proto, forwardDecl)) {
1465 Diag(identifierLocs[i], diag::warn_undef_protocolref)
1466 << proto->getDeclName();
1467 Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined)
1468 << forwardDecl;
1469 }
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001470
1471 // If everything this far has been a type name (and we care
1472 // about such things), check whether this name refers to a type
1473 // as well.
1474 if (allAreTypeNames) {
1475 if (auto *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1476 LookupOrdinaryName)) {
1477 if (isa<ObjCInterfaceDecl>(decl)) {
1478 if (firstClassNameLoc.isInvalid())
1479 firstClassNameLoc = identifierLocs[i];
1480 } else if (!isa<TypeDecl>(decl)) {
1481 // Not a type.
1482 allAreTypeNames = false;
1483 }
1484 } else {
1485 allAreTypeNames = false;
1486 }
1487 }
1488 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001489
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001490 // All of the protocols listed also have type names, and at least
1491 // one is an Objective-C class name. Check whether all of the
1492 // protocol conformances are declared by the base class itself, in
1493 // which case we warn.
1494 if (allAreTypeNames && firstClassNameLoc.isValid()) {
1495 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> knownProtocols;
1496 Context.CollectInheritedProtocols(baseClass, knownProtocols);
1497 bool allProtocolsDeclared = true;
1498 for (auto proto : protocols) {
1499 if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) {
1500 allProtocolsDeclared = false;
1501 break;
1502 }
1503 }
1504
1505 if (allProtocolsDeclared) {
1506 Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type)
1507 << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc)
Craig Topper07fa1762015-11-15 02:31:46 +00001508 << FixItHint::CreateInsertion(getLocForEndOfToken(firstClassNameLoc),
1509 " *");
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001510 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00001511 }
1512
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001513 protocolLAngleLoc = lAngleLoc;
1514 protocolRAngleLoc = rAngleLoc;
1515 assert(protocols.size() == identifierLocs.size());
Douglas Gregore9d95f12015-07-07 03:57:35 +00001516 };
1517
1518 // Attempt to resolve all of the identifiers as protocols.
1519 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1520 ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]);
1521 protocols.push_back(proto);
1522 if (proto)
1523 ++numProtocolsResolved;
1524 }
1525
1526 // If all of the names were protocols, these were protocol qualifiers.
1527 if (numProtocolsResolved == identifiers.size())
1528 return resolvedAsProtocols();
1529
1530 // Attempt to resolve all of the identifiers as type names or
1531 // Objective-C class names. The latter is technically ill-formed,
1532 // but is probably something like \c NSArray<NSView *> missing the
1533 // \c*.
1534 typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl;
1535 SmallVector<TypeOrClassDecl, 4> typeDecls;
1536 unsigned numTypeDeclsResolved = 0;
1537 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1538 NamedDecl *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1539 LookupOrdinaryName);
1540 if (!decl) {
1541 typeDecls.push_back(TypeOrClassDecl());
1542 continue;
1543 }
1544
1545 if (auto typeDecl = dyn_cast<TypeDecl>(decl)) {
1546 typeDecls.push_back(typeDecl);
1547 ++numTypeDeclsResolved;
1548 continue;
1549 }
1550
1551 if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) {
1552 typeDecls.push_back(objcClass);
1553 ++numTypeDeclsResolved;
1554 continue;
1555 }
1556
1557 typeDecls.push_back(TypeOrClassDecl());
1558 }
1559
1560 AttributeFactory attrFactory;
1561
1562 // Local function that forms a reference to the given type or
1563 // Objective-C class declaration.
Fangrui Song6907ce22018-07-30 19:24:48 +00001564 auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc)
Douglas Gregore9d95f12015-07-07 03:57:35 +00001565 -> TypeResult {
1566 // Form declaration specifiers. They simply refer to the type.
1567 DeclSpec DS(attrFactory);
1568 const char* prevSpec; // unused
1569 unsigned diagID; // unused
1570 QualType type;
1571 if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>())
1572 type = Context.getTypeDeclType(actualTypeDecl);
1573 else
1574 type = Context.getObjCInterfaceType(typeDecl.get<ObjCInterfaceDecl *>());
1575 TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc);
1576 ParsedType parsedType = CreateParsedType(type, parsedTSInfo);
1577 DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID,
1578 parsedType, Context.getPrintingPolicy());
1579 // Use the identifier location for the type source range.
1580 DS.SetRangeStart(loc);
1581 DS.SetRangeEnd(loc);
1582
1583 // Form the declarator.
Faisal Vali421b2d12017-12-29 05:41:00 +00001584 Declarator D(DS, DeclaratorContext::TypeNameContext);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001585
1586 // If we have a typedef of an Objective-C class type that is missing a '*',
1587 // add the '*'.
1588 if (type->getAs<ObjCInterfaceType>()) {
Craig Topper07fa1762015-11-15 02:31:46 +00001589 SourceLocation starLoc = getLocForEndOfToken(loc);
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001590 D.AddTypeInfo(DeclaratorChunk::getPointer(/*TypeQuals=*/0, starLoc,
Douglas Gregore9d95f12015-07-07 03:57:35 +00001591 SourceLocation(),
1592 SourceLocation(),
1593 SourceLocation(),
Andrey Bokhanko45d41322016-05-11 18:38:21 +00001594 SourceLocation(),
Douglas Gregore9d95f12015-07-07 03:57:35 +00001595 SourceLocation()),
Hans Wennborgdcfba332015-10-06 23:40:43 +00001596 starLoc);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001597
1598 // Diagnose the missing '*'.
1599 Diag(loc, diag::err_objc_type_arg_missing_star)
1600 << type
1601 << FixItHint::CreateInsertion(starLoc, " *");
1602 }
1603
1604 // Convert this to a type.
1605 return ActOnTypeName(S, D);
1606 };
1607
1608 // Local function that updates the declaration specifiers with
1609 // type argument information.
1610 auto resolvedAsTypeDecls = [&] {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001611 // We did not resolve these as protocols.
1612 protocols.clear();
1613
Douglas Gregore9d95f12015-07-07 03:57:35 +00001614 assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl");
1615 // Map type declarations to type arguments.
Douglas Gregore9d95f12015-07-07 03:57:35 +00001616 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1617 // Map type reference to a type.
1618 TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]);
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001619 if (!type.isUsable()) {
1620 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001621 return;
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001622 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00001623
1624 typeArgs.push_back(type.get());
1625 }
1626
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001627 typeArgsLAngleLoc = lAngleLoc;
1628 typeArgsRAngleLoc = rAngleLoc;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001629 };
1630
1631 // If all of the identifiers can be resolved as type names or
1632 // Objective-C class names, we have type arguments.
1633 if (numTypeDeclsResolved == identifiers.size())
1634 return resolvedAsTypeDecls();
1635
1636 // Error recovery: some names weren't found, or we have a mix of
1637 // type and protocol names. Go resolve all of the unresolved names
1638 // and complain if we can't find a consistent answer.
1639 LookupNameKind lookupKind = LookupAnyName;
1640 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1641 // If we already have a protocol or type. Check whether it is the
1642 // right thing.
1643 if (protocols[i] || typeDecls[i]) {
1644 // If we haven't figured out whether we want types or protocols
1645 // yet, try to figure it out from this name.
1646 if (lookupKind == LookupAnyName) {
1647 // If this name refers to both a protocol and a type (e.g., \c
1648 // NSObject), don't conclude anything yet.
1649 if (protocols[i] && typeDecls[i])
1650 continue;
1651
1652 // Otherwise, let this name decide whether we'll be correcting
1653 // toward types or protocols.
1654 lookupKind = protocols[i] ? LookupObjCProtocolName
1655 : LookupOrdinaryName;
1656 continue;
1657 }
1658
1659 // If we want protocols and we have a protocol, there's nothing
1660 // more to do.
1661 if (lookupKind == LookupObjCProtocolName && protocols[i])
1662 continue;
1663
1664 // If we want types and we have a type declaration, there's
1665 // nothing more to do.
1666 if (lookupKind == LookupOrdinaryName && typeDecls[i])
1667 continue;
1668
1669 // We have a conflict: some names refer to protocols and others
1670 // refer to types.
Bruno Cardoso Lopesc54768f2016-04-13 20:59:07 +00001671 DiagnoseTypeArgsAndProtocols(identifiers[0], identifierLocs[0],
1672 identifiers[i], identifierLocs[i],
1673 protocols[i] != nullptr);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001674
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001675 protocols.clear();
1676 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001677 return;
1678 }
1679
1680 // Perform typo correction on the name.
Bruno Ricci70ad3962019-03-25 17:08:51 +00001681 ObjCTypeArgOrProtocolValidatorCCC CCC(Context, lookupKind);
1682 TypoCorrection corrected =
1683 CorrectTypo(DeclarationNameInfo(identifiers[i], identifierLocs[i]),
1684 lookupKind, S, nullptr, CCC, CTK_ErrorRecovery);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001685 if (corrected) {
1686 // Did we find a protocol?
1687 if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) {
1688 diagnoseTypo(corrected,
1689 PDiag(diag::err_undeclared_protocol_suggest)
1690 << identifiers[i]);
1691 lookupKind = LookupObjCProtocolName;
1692 protocols[i] = proto;
1693 ++numProtocolsResolved;
1694 continue;
1695 }
1696
1697 // Did we find a type?
1698 if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) {
1699 diagnoseTypo(corrected,
1700 PDiag(diag::err_unknown_typename_suggest)
1701 << identifiers[i]);
1702 lookupKind = LookupOrdinaryName;
1703 typeDecls[i] = typeDecl;
1704 ++numTypeDeclsResolved;
1705 continue;
1706 }
1707
1708 // Did we find an Objective-C class?
1709 if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1710 diagnoseTypo(corrected,
1711 PDiag(diag::err_unknown_type_or_class_name_suggest)
1712 << identifiers[i] << true);
1713 lookupKind = LookupOrdinaryName;
1714 typeDecls[i] = objcClass;
1715 ++numTypeDeclsResolved;
1716 continue;
1717 }
1718 }
1719
1720 // We couldn't find anything.
1721 Diag(identifierLocs[i],
1722 (lookupKind == LookupAnyName ? diag::err_objc_type_arg_missing
1723 : lookupKind == LookupObjCProtocolName ? diag::err_undeclared_protocol
1724 : diag::err_unknown_typename))
1725 << identifiers[i];
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001726 protocols.clear();
1727 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001728 return;
1729 }
1730
1731 // If all of the names were (corrected to) protocols, these were
1732 // protocol qualifiers.
1733 if (numProtocolsResolved == identifiers.size())
1734 return resolvedAsProtocols();
1735
1736 // Otherwise, all of the names were (corrected to) types.
1737 assert(numTypeDeclsResolved == identifiers.size() && "Not all types?");
1738 return resolvedAsTypeDecls();
1739}
1740
Fariborz Jahanianabf63e7b2009-03-02 19:06:08 +00001741/// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001742/// a class method in its extension.
1743///
Mike Stump11289f42009-09-09 15:08:12 +00001744void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001745 ObjCInterfaceDecl *ID) {
1746 if (!ID)
1747 return; // Possibly due to previous error
1748
1749 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
Aaron Ballmanaff18c02014-03-13 19:03:34 +00001750 for (auto *MD : ID->methods())
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001751 MethodMap[MD->getSelector()] = MD;
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001752
1753 if (MethodMap.empty())
1754 return;
Aaron Ballmanaff18c02014-03-13 19:03:34 +00001755 for (const auto *Method : CAT->methods()) {
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001756 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
Fariborz Jahanian83d674e2014-03-17 17:46:10 +00001757 if (PrevMethod &&
1758 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
1759 !MatchTwoMethodDeclarations(Method, PrevMethod)) {
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001760 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1761 << Method->getDeclName();
1762 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1763 }
1764 }
1765}
1766
James Dennett634962f2012-06-14 21:40:34 +00001767/// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
Douglas Gregorf6102672012-01-01 21:23:57 +00001768Sema::DeclGroupPtrTy
Chris Lattnerda463fe2007-12-12 07:09:47 +00001769Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
Craig Topper0f723bb2015-10-22 05:00:01 +00001770 ArrayRef<IdentifierLocPair> IdentList,
Erich Keanec480f302018-07-12 21:09:05 +00001771 const ParsedAttributesView &attrList) {
Douglas Gregorf6102672012-01-01 21:23:57 +00001772 SmallVector<Decl *, 8> DeclsInGroup;
Craig Topper0f723bb2015-10-22 05:00:01 +00001773 for (const IdentifierLocPair &IdentPair : IdentList) {
1774 IdentifierInfo *Ident = IdentPair.first;
1775 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentPair.second,
Richard Smithbecb92d2017-10-10 22:33:17 +00001776 forRedeclarationInCurContext());
Douglas Gregor32c17572012-01-01 20:30:41 +00001777 ObjCProtocolDecl *PDecl
Fangrui Song6907ce22018-07-30 19:24:48 +00001778 = ObjCProtocolDecl::Create(Context, CurContext, Ident,
Craig Topper0f723bb2015-10-22 05:00:01 +00001779 IdentPair.second, AtProtocolLoc,
Douglas Gregor05a1f4d2012-01-01 22:06:18 +00001780 PrevDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00001781
Douglas Gregor32c17572012-01-01 20:30:41 +00001782 PushOnScopeChains(PDecl, TUScope);
Douglas Gregorf6102672012-01-01 21:23:57 +00001783 CheckObjCDeclScope(PDecl);
Erich Keanec480f302018-07-12 21:09:05 +00001784
1785 ProcessDeclAttributeList(TUScope, PDecl, attrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001786 AddPragmaAttributes(TUScope, PDecl);
1787
Douglas Gregor32c17572012-01-01 20:30:41 +00001788 if (PrevDecl)
1789 mergeDeclAttributes(PDecl, PrevDecl);
1790
Douglas Gregorf6102672012-01-01 21:23:57 +00001791 DeclsInGroup.push_back(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001792 }
Mike Stump11289f42009-09-09 15:08:12 +00001793
Richard Smith3beb7c62017-01-12 02:27:38 +00001794 return BuildDeclaratorGroup(DeclsInGroup);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001795}
1796
Erich Keanec480f302018-07-12 21:09:05 +00001797Decl *Sema::ActOnStartCategoryInterface(
1798 SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
1799 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
1800 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
1801 Decl *const *ProtoRefs, unsigned NumProtoRefs,
1802 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
1803 const ParsedAttributesView &AttrList) {
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001804 ObjCCategoryDecl *CDecl;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001805 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
Ted Kremenek514ff702010-02-23 19:39:46 +00001806
1807 /// Check that class of this category is already completely declared.
Douglas Gregor4123a862011-11-14 22:10:01 +00001808
Fangrui Song6907ce22018-07-30 19:24:48 +00001809 if (!IDecl
Douglas Gregor4123a862011-11-14 22:10:01 +00001810 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001811 diag::err_category_forward_interface,
Craig Topperc3ec1492014-05-26 06:22:03 +00001812 CategoryName == nullptr)) {
Ted Kremenek514ff702010-02-23 19:39:46 +00001813 // Create an invalid ObjCCategoryDecl to serve as context for
1814 // the enclosing method declarations. We mark the decl invalid
1815 // to make it clear that this isn't a valid AST.
1816 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001817 ClassLoc, CategoryLoc, CategoryName,
1818 IDecl, typeParamList);
Ted Kremenek514ff702010-02-23 19:39:46 +00001819 CDecl->setInvalidDecl();
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00001820 CurContext->addDecl(CDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00001821
Douglas Gregor4123a862011-11-14 22:10:01 +00001822 if (!IDecl)
1823 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001824 return ActOnObjCContainerStartDefinition(CDecl);
Ted Kremenek514ff702010-02-23 19:39:46 +00001825 }
1826
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001827 if (!CategoryName && IDecl->getImplementation()) {
1828 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
Fangrui Song6907ce22018-07-30 19:24:48 +00001829 Diag(IDecl->getImplementation()->getLocation(),
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001830 diag::note_implementation_declared);
Ted Kremenek514ff702010-02-23 19:39:46 +00001831 }
1832
Fariborz Jahanian30a42922010-02-15 21:55:26 +00001833 if (CategoryName) {
1834 /// Check for duplicate interface declaration for this category
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001835 if (ObjCCategoryDecl *Previous
1836 = IDecl->FindCategoryDeclaration(CategoryName)) {
1837 // Class extensions can be declared multiple times, categories cannot.
1838 Diag(CategoryLoc, diag::warn_dup_category_def)
1839 << ClassName << CategoryName;
1840 Diag(Previous->getLocation(), diag::note_previous_definition);
Chris Lattner9018ca82009-02-16 21:26:43 +00001841 }
1842 }
Chris Lattner9018ca82009-02-16 21:26:43 +00001843
Douglas Gregor85f3f952015-07-07 03:57:15 +00001844 // If we have a type parameter list, check it.
1845 if (typeParamList) {
1846 if (auto prevTypeParamList = IDecl->getTypeParamList()) {
1847 if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList,
1848 CategoryName
1849 ? TypeParamListContext::Category
1850 : TypeParamListContext::Extension))
1851 typeParamList = nullptr;
1852 } else {
1853 Diag(typeParamList->getLAngleLoc(),
1854 diag::err_objc_parameterized_category_nonclass)
1855 << (CategoryName != nullptr)
1856 << ClassName
1857 << typeParamList->getSourceRange();
1858
1859 typeParamList = nullptr;
1860 }
1861 }
1862
Argyrios Kyrtzidis3a5094b2011-08-30 19:43:26 +00001863 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001864 ClassLoc, CategoryLoc, CategoryName, IDecl,
1865 typeParamList);
Argyrios Kyrtzidis3a5094b2011-08-30 19:43:26 +00001866 // FIXME: PushOnScopeChains?
1867 CurContext->addDecl(CDecl);
1868
Alex Lorenza9c966d2018-02-23 23:49:43 +00001869 // Process the attributes before looking at protocols to ensure that the
1870 // availability attribute is attached to the category to provide availability
1871 // checking for protocol uses.
Erich Keanec480f302018-07-12 21:09:05 +00001872 ProcessDeclAttributeList(TUScope, CDecl, AttrList);
Alex Lorenza9c966d2018-02-23 23:49:43 +00001873 AddPragmaAttributes(TUScope, CDecl);
1874
Chris Lattnerda463fe2007-12-12 07:09:47 +00001875 if (NumProtoRefs) {
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001876 diagnoseUseOfProtocols(*this, CDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1877 NumProtoRefs, ProtoLocs);
1878 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001879 ProtoLocs, Context);
Fariborz Jahanian092cd6e2009-10-05 20:41:32 +00001880 // Protocols in the class extension belong to the class.
Fariborz Jahanian30a42922010-02-15 21:55:26 +00001881 if (CDecl->IsClassExtension())
Fangrui Song6907ce22018-07-30 19:24:48 +00001882 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
1883 NumProtoRefs, Context);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001884 }
Mike Stump11289f42009-09-09 15:08:12 +00001885
Anders Carlssona6b508a2008-11-04 16:57:32 +00001886 CheckObjCDeclScope(CDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001887 return ActOnObjCContainerStartDefinition(CDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001888}
1889
1890/// ActOnStartCategoryImplementation - Perform semantic checks on the
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001891/// category implementation declaration and build an ObjCCategoryImplDecl
Chris Lattnerda463fe2007-12-12 07:09:47 +00001892/// object.
John McCall48871652010-08-21 09:40:31 +00001893Decl *Sema::ActOnStartCategoryImplementation(
Chris Lattnerda463fe2007-12-12 07:09:47 +00001894 SourceLocation AtCatImplLoc,
1895 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Erik Pilkingtonc5a05832019-04-11 17:55:30 +00001896 IdentifierInfo *CatName, SourceLocation CatLoc,
1897 const ParsedAttributesView &Attrs) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001898 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
Craig Topperc3ec1492014-05-26 06:22:03 +00001899 ObjCCategoryDecl *CatIDecl = nullptr;
Argyrios Kyrtzidis4af2cb32012-03-02 19:14:29 +00001900 if (IDecl && IDecl->hasDefinition()) {
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001901 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
1902 if (!CatIDecl) {
1903 // Category @implementation with no corresponding @interface.
1904 // Create and install one.
Argyrios Kyrtzidis41fc05c2011-11-23 20:27:26 +00001905 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
1906 ClassLoc, CatLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001907 CatName, IDecl,
1908 /*typeParamList=*/nullptr);
Argyrios Kyrtzidis41fc05c2011-11-23 20:27:26 +00001909 CatIDecl->setImplicit();
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001910 }
1911 }
1912
Mike Stump11289f42009-09-09 15:08:12 +00001913 ObjCCategoryImplDecl *CDecl =
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001914 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
Argyrios Kyrtzidis4996f5f2011-12-09 00:31:40 +00001915 ClassLoc, AtCatImplLoc, CatLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001916 /// Check that class of this category is already completely declared.
Douglas Gregor4123a862011-11-14 22:10:01 +00001917 if (!IDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001918 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
John McCalld2930c22011-07-22 02:45:48 +00001919 CDecl->setInvalidDecl();
Douglas Gregor4123a862011-11-14 22:10:01 +00001920 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1921 diag::err_undef_interface)) {
1922 CDecl->setInvalidDecl();
John McCalld2930c22011-07-22 02:45:48 +00001923 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001924
Erik Pilkingtonc5a05832019-04-11 17:55:30 +00001925 ProcessDeclAttributeList(TUScope, CDecl, Attrs);
1926 AddPragmaAttributes(TUScope, CDecl);
1927
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001928 // FIXME: PushOnScopeChains?
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001929 CurContext->addDecl(CDecl);
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001930
Douglas Gregor24ae22c2016-04-01 23:23:52 +00001931 // If the interface has the objc_runtime_visible attribute, we
1932 // cannot implement a category for it.
1933 if (IDecl && IDecl->hasAttr<ObjCRuntimeVisibleAttr>()) {
1934 Diag(ClassLoc, diag::err_objc_runtime_visible_category)
1935 << IDecl->getDeclName();
1936 }
1937
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001938 /// Check that CatName, category name, is not used in another implementation.
1939 if (CatIDecl) {
1940 if (CatIDecl->getImplementation()) {
1941 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
1942 << CatName;
1943 Diag(CatIDecl->getImplementation()->getLocation(),
1944 diag::note_previous_definition);
Argyrios Kyrtzidis0f6d5ca2013-05-30 18:53:21 +00001945 CDecl->setInvalidDecl();
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001946 } else {
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001947 CatIDecl->setImplementation(CDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00001948 // Warn on implementating category of deprecated class under
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001949 // -Wdeprecated-implementations flag.
Alex Lorenzf81d97e2017-07-13 16:35:59 +00001950 DiagnoseObjCImplementedDeprecations(*this, CatIDecl,
1951 CDecl->getLocation());
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001952 }
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001953 }
Mike Stump11289f42009-09-09 15:08:12 +00001954
Anders Carlssona6b508a2008-11-04 16:57:32 +00001955 CheckObjCDeclScope(CDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001956 return ActOnObjCContainerStartDefinition(CDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001957}
1958
John McCall48871652010-08-21 09:40:31 +00001959Decl *Sema::ActOnStartClassImplementation(
Chris Lattnerda463fe2007-12-12 07:09:47 +00001960 SourceLocation AtClassImplLoc,
1961 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001962 IdentifierInfo *SuperClassname,
Erik Pilkingtonc5a05832019-04-11 17:55:30 +00001963 SourceLocation SuperClassLoc,
1964 const ParsedAttributesView &Attrs) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001965 ObjCInterfaceDecl *IDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001966 // Check for another declaration kind with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00001967 NamedDecl *PrevDecl
Douglas Gregorb8eaf292010-04-15 23:40:53 +00001968 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00001969 forRedeclarationInCurContext());
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001970 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001971 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Chris Lattner0369c572008-11-23 23:12:31 +00001972 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor1c283312010-08-11 12:19:30 +00001973 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
Richard Smithdb0ac552015-12-18 22:40:25 +00001974 // FIXME: This will produce an error if the definition of the interface has
1975 // been imported from a module but is not visible.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00001976 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1977 diag::warn_undef_interface);
Douglas Gregor40f7a002010-01-04 17:27:12 +00001978 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001979 // We did not find anything with the name ClassName; try to correct for
Douglas Gregor40f7a002010-01-04 17:27:12 +00001980 // typos in the class name.
Bruno Ricci70ad3962019-03-25 17:08:51 +00001981 ObjCInterfaceValidatorCCC CCC{};
1982 TypoCorrection Corrected =
1983 CorrectTypo(DeclarationNameInfo(ClassName, ClassLoc),
1984 LookupOrdinaryName, TUScope, nullptr, CCC, CTK_NonError);
Richard Smithf9b15102013-08-17 00:46:16 +00001985 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1986 // Suggest the (potentially) correct interface name. Don't provide a
1987 // code-modification hint or use the typo name for recovery, because
1988 // this is just a warning. The program may actually be correct.
1989 diagnoseTypo(Corrected,
1990 PDiag(diag::warn_undef_interface_suggest) << ClassName,
1991 /*ErrorRecovery*/false);
Douglas Gregor40f7a002010-01-04 17:27:12 +00001992 } else {
1993 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
1994 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001995 }
Mike Stump11289f42009-09-09 15:08:12 +00001996
Chris Lattnerda463fe2007-12-12 07:09:47 +00001997 // Check that super class name is valid class name
Craig Topperc3ec1492014-05-26 06:22:03 +00001998 ObjCInterfaceDecl *SDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001999 if (SuperClassname) {
2000 // Check if a different kind of symbol declared in this scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002001 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
2002 LookupOrdinaryName);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002003 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002004 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
2005 << SuperClassname;
Chris Lattner0369c572008-11-23 23:12:31 +00002006 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002007 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002008 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidis3b60cff2012-03-13 01:09:36 +00002009 if (SDecl && !SDecl->hasDefinition())
Craig Topperc3ec1492014-05-26 06:22:03 +00002010 SDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002011 if (!SDecl)
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002012 Diag(SuperClassLoc, diag::err_undef_superclass)
2013 << SuperClassname << ClassName;
Douglas Gregor0b144e12011-12-15 00:29:59 +00002014 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00002015 // This implementation and its interface do not have the same
2016 // super class.
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002017 Diag(SuperClassLoc, diag::err_conflicting_super_class)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002018 << SDecl->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002019 Diag(SDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002020 }
2021 }
2022 }
Mike Stump11289f42009-09-09 15:08:12 +00002023
Chris Lattnerda463fe2007-12-12 07:09:47 +00002024 if (!IDecl) {
2025 // Legacy case of @implementation with no corresponding @interface.
2026 // Build, chain & install the interface decl into the identifier.
Daniel Dunbar73a73f52008-08-20 18:02:42 +00002027
Mike Stump87c57ac2009-05-16 07:39:55 +00002028 // FIXME: Do we support attributes on the @implementation? If so we should
2029 // copy them over.
Mike Stump11289f42009-09-09 15:08:12 +00002030 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00002031 ClassName, /*typeParamList=*/nullptr,
2032 /*PrevDecl=*/nullptr, ClassLoc,
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002033 true);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002034 AddPragmaAttributes(TUScope, IDecl);
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002035 IDecl->startDefinition();
Douglas Gregor16408322011-12-15 22:34:59 +00002036 if (SDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00002037 IDecl->setSuperClass(Context.getTrivialTypeSourceInfo(
2038 Context.getObjCInterfaceType(SDecl),
2039 SuperClassLoc));
Douglas Gregor16408322011-12-15 22:34:59 +00002040 IDecl->setEndOfDefinitionLoc(SuperClassLoc);
2041 } else {
2042 IDecl->setEndOfDefinitionLoc(ClassLoc);
2043 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002044
Douglas Gregorac345a32009-04-24 00:16:12 +00002045 PushOnScopeChains(IDecl, TUScope);
Douglas Gregor1c283312010-08-11 12:19:30 +00002046 } else {
2047 // Mark the interface as being completed, even if it was just as
2048 // @class ....;
2049 // declaration; the user cannot reopen it.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002050 if (!IDecl->hasDefinition())
2051 IDecl->startDefinition();
Chris Lattnerda463fe2007-12-12 07:09:47 +00002052 }
Mike Stump11289f42009-09-09 15:08:12 +00002053
2054 ObjCImplementationDecl* IMPDecl =
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00002055 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
Argyrios Kyrtzidisfac31622013-05-03 18:05:44 +00002056 ClassLoc, AtClassImplLoc, SuperClassLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002057
Erik Pilkingtonc5a05832019-04-11 17:55:30 +00002058 ProcessDeclAttributeList(TUScope, IMPDecl, Attrs);
2059 AddPragmaAttributes(TUScope, IMPDecl);
2060
Anders Carlssona6b508a2008-11-04 16:57:32 +00002061 if (CheckObjCDeclScope(IMPDecl))
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00002062 return ActOnObjCContainerStartDefinition(IMPDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002063
Chris Lattnerda463fe2007-12-12 07:09:47 +00002064 // Check that there is no duplicate implementation of this class.
Douglas Gregor1c283312010-08-11 12:19:30 +00002065 if (IDecl->getImplementation()) {
2066 // FIXME: Don't leak everything!
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002067 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
Argyrios Kyrtzidis43cee9352009-07-21 00:06:04 +00002068 Diag(IDecl->getImplementation()->getLocation(),
2069 diag::note_previous_definition);
Argyrios Kyrtzidis0f6d5ca2013-05-30 18:53:21 +00002070 IMPDecl->setInvalidDecl();
Douglas Gregor1c283312010-08-11 12:19:30 +00002071 } else { // add it to the list.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002072 IDecl->setImplementation(IMPDecl);
Douglas Gregor79947a22009-04-24 00:11:27 +00002073 PushOnScopeChains(IMPDecl, TUScope);
Fangrui Song6907ce22018-07-30 19:24:48 +00002074 // Warn on implementating deprecated class under
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00002075 // -Wdeprecated-implementations flag.
Alex Lorenzf81d97e2017-07-13 16:35:59 +00002076 DiagnoseObjCImplementedDeprecations(*this, IDecl, IMPDecl->getLocation());
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002077 }
Douglas Gregor24ae22c2016-04-01 23:23:52 +00002078
2079 // If the superclass has the objc_runtime_visible attribute, we
2080 // cannot implement a subclass of it.
2081 if (IDecl->getSuperClass() &&
2082 IDecl->getSuperClass()->hasAttr<ObjCRuntimeVisibleAttr>()) {
2083 Diag(ClassLoc, diag::err_objc_runtime_visible_subclass)
2084 << IDecl->getDeclName()
2085 << IDecl->getSuperClass()->getDeclName();
2086 }
2087
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00002088 return ActOnObjCContainerStartDefinition(IMPDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002089}
2090
Argyrios Kyrtzidis2e85c5f2012-02-23 21:11:20 +00002091Sema::DeclGroupPtrTy
2092Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
2093 SmallVector<Decl *, 64> DeclsInGroup;
2094 DeclsInGroup.reserve(Decls.size() + 1);
2095
2096 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
2097 Decl *Dcl = Decls[i];
2098 if (!Dcl)
2099 continue;
2100 if (Dcl->getDeclContext()->isFileContext())
2101 Dcl->setTopLevelDeclInObjCContainer();
2102 DeclsInGroup.push_back(Dcl);
2103 }
2104
2105 DeclsInGroup.push_back(ObjCImpDecl);
2106
Richard Smith3beb7c62017-01-12 02:27:38 +00002107 return BuildDeclaratorGroup(DeclsInGroup);
Argyrios Kyrtzidis2e85c5f2012-02-23 21:11:20 +00002108}
2109
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002110void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
2111 ObjCIvarDecl **ivars, unsigned numIvars,
Chris Lattnerda463fe2007-12-12 07:09:47 +00002112 SourceLocation RBrace) {
2113 assert(ImpDecl && "missing implementation decl");
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002114 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
Chris Lattnerda463fe2007-12-12 07:09:47 +00002115 if (!IDecl)
2116 return;
James Dennett634962f2012-06-14 21:40:34 +00002117 /// Check case of non-existing \@interface decl.
2118 /// (legacy objective-c \@implementation decl without an \@interface decl).
Chris Lattnerda463fe2007-12-12 07:09:47 +00002119 /// Add implementations's ivar to the synthesize class's ivar list.
Steve Naroffaac654a2009-04-20 20:09:33 +00002120 if (IDecl->isImplicitInterfaceDecl()) {
Douglas Gregor16408322011-12-15 22:34:59 +00002121 IDecl->setEndOfDefinitionLoc(RBrace);
Fariborz Jahanian20912d62010-02-17 17:00:07 +00002122 // Add ivar's to class's DeclContext.
2123 for (unsigned i = 0, e = numIvars; i != e; ++i) {
Fariborz Jahanianc0309cd2010-02-17 18:10:54 +00002124 ivars[i]->setLexicalDeclContext(ImpDecl);
Richard Smith05afe5e2012-03-13 03:12:56 +00002125 IDecl->makeDeclVisibleInContext(ivars[i]);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00002126 ImpDecl->addDecl(ivars[i]);
Fariborz Jahanian20912d62010-02-17 17:00:07 +00002127 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002128
Chris Lattnerda463fe2007-12-12 07:09:47 +00002129 return;
2130 }
2131 // If implementation has empty ivar list, just return.
2132 if (numIvars == 0)
2133 return;
Mike Stump11289f42009-09-09 15:08:12 +00002134
Chris Lattnerda463fe2007-12-12 07:09:47 +00002135 assert(ivars && "missing @implementation ivars");
John McCall5fb5df92012-06-20 06:18:46 +00002136 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002137 if (ImpDecl->getSuperClass())
2138 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
2139 for (unsigned i = 0; i < numIvars; i++) {
2140 ObjCIvarDecl* ImplIvar = ivars[i];
Fangrui Song6907ce22018-07-30 19:24:48 +00002141 if (const ObjCIvarDecl *ClsIvar =
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002142 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002143 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002144 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2145 continue;
2146 }
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00002147 // Check class extensions (unnamed categories) for duplicate ivars.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002148 for (const auto *CDecl : IDecl->visible_extensions()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002149 if (const ObjCIvarDecl *ClsExtIvar =
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00002150 CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002151 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00002152 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
2153 continue;
2154 }
2155 }
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002156 // Instance ivar to Implementation's DeclContext.
2157 ImplIvar->setLexicalDeclContext(ImpDecl);
Richard Smith05afe5e2012-03-13 03:12:56 +00002158 IDecl->makeDeclVisibleInContext(ImplIvar);
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002159 ImpDecl->addDecl(ImplIvar);
2160 }
2161 return;
2162 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002163 // Check interface's Ivar list against those in the implementation.
2164 // names and types must match.
2165 //
Chris Lattnerda463fe2007-12-12 07:09:47 +00002166 unsigned j = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002167 ObjCInterfaceDecl::ivar_iterator
Chris Lattner061227a2007-12-12 17:58:05 +00002168 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
2169 for (; numIvars > 0 && IVI != IVE; ++IVI) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002170 ObjCIvarDecl* ImplIvar = ivars[j++];
David Blaikie40ed2972012-06-06 20:45:41 +00002171 ObjCIvarDecl* ClsIvar = *IVI;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002172 assert (ImplIvar && "missing implementation ivar");
2173 assert (ClsIvar && "missing class ivar");
Mike Stump11289f42009-09-09 15:08:12 +00002174
Steve Naroff157599f2009-03-03 14:49:36 +00002175 // First, make sure the types match.
Richard Smithcaf33902011-10-10 18:28:20 +00002176 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
Chris Lattner3b054132008-11-19 05:08:23 +00002177 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002178 << ImplIvar->getIdentifier()
2179 << ImplIvar->getType() << ClsIvar->getType();
Chris Lattner0369c572008-11-23 23:12:31 +00002180 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
Richard Smithcaf33902011-10-10 18:28:20 +00002181 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
2182 ImplIvar->getBitWidthValue(Context) !=
2183 ClsIvar->getBitWidthValue(Context)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002184 Diag(ImplIvar->getBitWidth()->getBeginLoc(),
2185 diag::err_conflicting_ivar_bitwidth)
2186 << ImplIvar->getIdentifier();
2187 Diag(ClsIvar->getBitWidth()->getBeginLoc(),
Richard Smithcaf33902011-10-10 18:28:20 +00002188 diag::note_previous_definition);
Mike Stump11289f42009-09-09 15:08:12 +00002189 }
Steve Naroff157599f2009-03-03 14:49:36 +00002190 // Make sure the names are identical.
2191 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002192 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002193 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
Chris Lattner0369c572008-11-23 23:12:31 +00002194 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002195 }
2196 --numIvars;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002197 }
Mike Stump11289f42009-09-09 15:08:12 +00002198
Chris Lattner0f29d982007-12-12 18:11:49 +00002199 if (numIvars > 0)
Alp Tokerfff06742013-12-02 03:50:21 +00002200 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
Chris Lattner0f29d982007-12-12 18:11:49 +00002201 else if (IVI != IVE)
Alp Tokerfff06742013-12-02 03:50:21 +00002202 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002203}
2204
Ted Kremenekf87decd2013-12-13 05:58:44 +00002205static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
2206 ObjCMethodDecl *method,
2207 bool &IncompleteImpl,
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002208 unsigned DiagID,
Craig Topperc3ec1492014-05-26 06:22:03 +00002209 NamedDecl *NeededFor = nullptr) {
Fariborz Jahanian9fc39c42011-06-24 20:31:37 +00002210 // No point warning no definition of method which is 'unavailable'.
Erik Pilkingtonecce5c92018-07-07 01:50:20 +00002211 if (method->getAvailability() == AR_Unavailable)
Fariborz Jahanian9fc39c42011-06-24 20:31:37 +00002212 return;
Erik Pilkingtonecce5c92018-07-07 01:50:20 +00002213
Ted Kremenek65d63572013-03-27 00:02:21 +00002214 // FIXME: For now ignore 'IncompleteImpl'.
2215 // Previously we grouped all unimplemented methods under a single
2216 // warning, but some users strongly voiced that they would prefer
2217 // separate warnings. We will give that approach a try, as that
2218 // matches what we do with protocols.
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002219 {
2220 const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
2221 B << method;
2222 if (NeededFor)
2223 B << NeededFor;
2224 }
Ted Kremenek65d63572013-03-27 00:02:21 +00002225
2226 // Issue a note to the original declaration.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002227 SourceLocation MethodLoc = method->getBeginLoc();
Ted Kremenek65d63572013-03-27 00:02:21 +00002228 if (MethodLoc.isValid())
Ted Kremenekf87decd2013-12-13 05:58:44 +00002229 S.Diag(MethodLoc, diag::note_method_declared_at) << method;
Steve Naroff15833ed2008-02-10 21:38:56 +00002230}
2231
David Chisnallb62d15c2010-10-25 17:23:52 +00002232/// Determines if type B can be substituted for type A. Returns true if we can
Fangrui Song6907ce22018-07-30 19:24:48 +00002233/// guarantee that anything that the user will do to an object of type A can
2234/// also be done to an object of type B. This is trivially true if the two
David Chisnallb62d15c2010-10-25 17:23:52 +00002235/// types are the same, or if B is a subclass of A. It becomes more complex
2236/// in cases where protocols are involved.
2237///
2238/// Object types in Objective-C describe the minimum requirements for an
2239/// object, rather than providing a complete description of a type. For
2240/// example, if A is a subclass of B, then B* may refer to an instance of A.
2241/// The principle of substitutability means that we may use an instance of A
2242/// anywhere that we may use an instance of B - it will implement all of the
Fangrui Song6907ce22018-07-30 19:24:48 +00002243/// ivars of B and all of the methods of B.
David Chisnallb62d15c2010-10-25 17:23:52 +00002244///
Fangrui Song6907ce22018-07-30 19:24:48 +00002245/// This substitutability is important when type checking methods, because
David Chisnallb62d15c2010-10-25 17:23:52 +00002246/// the implementation may have stricter type definitions than the interface.
2247/// The interface specifies minimum requirements, but the implementation may
Fangrui Song6907ce22018-07-30 19:24:48 +00002248/// have more accurate ones. For example, a method may privately accept
David Chisnallb62d15c2010-10-25 17:23:52 +00002249/// instances of B, but only publish that it accepts instances of A. Any
2250/// object passed to it will be type checked against B, and so will implicitly
2251/// by a valid A*. Similarly, a method may return a subclass of the class that
2252/// it is declared as returning.
2253///
2254/// This is most important when considering subclassing. A method in a
2255/// subclass must accept any object as an argument that its superclass's
2256/// implementation accepts. It may, however, accept a more general type
2257/// without breaking substitutability (i.e. you can still use the subclass
2258/// anywhere that you can use the superclass, but not vice versa). The
2259/// converse requirement applies to return types: the return type for a
2260/// subclass method must be a valid object of the kind that the superclass
2261/// advertises, but it may be specified more accurately. This avoids the need
2262/// for explicit down-casting by callers.
2263///
Fangrui Song6907ce22018-07-30 19:24:48 +00002264/// Note: This is a stricter requirement than for assignment.
John McCall071df462010-10-28 02:34:38 +00002265static bool isObjCTypeSubstitutable(ASTContext &Context,
2266 const ObjCObjectPointerType *A,
2267 const ObjCObjectPointerType *B,
2268 bool rejectId) {
2269 // Reject a protocol-unqualified id.
2270 if (rejectId && B->isObjCIdType()) return false;
David Chisnallb62d15c2010-10-25 17:23:52 +00002271
2272 // If B is a qualified id, then A must also be a qualified id and it must
2273 // implement all of the protocols in B. It may not be a qualified class.
2274 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
2275 // stricter definition so it is not substitutable for id<A>.
2276 if (B->isObjCQualifiedIdType()) {
2277 return A->isObjCQualifiedIdType() &&
John McCall071df462010-10-28 02:34:38 +00002278 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
2279 QualType(B,0),
2280 false);
David Chisnallb62d15c2010-10-25 17:23:52 +00002281 }
2282
2283 /*
2284 // id is a special type that bypasses type checking completely. We want a
2285 // warning when it is used in one place but not another.
2286 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
2287
2288
2289 // If B is a qualified id, then A must also be a qualified id (which it isn't
2290 // if we've got this far)
2291 if (B->isObjCQualifiedIdType()) return false;
2292 */
2293
2294 // Now we know that A and B are (potentially-qualified) class types. The
2295 // normal rules for assignment apply.
John McCall071df462010-10-28 02:34:38 +00002296 return Context.canAssignObjCInterfaces(A, B);
David Chisnallb62d15c2010-10-25 17:23:52 +00002297}
2298
John McCall071df462010-10-28 02:34:38 +00002299static SourceRange getTypeRange(TypeSourceInfo *TSI) {
2300 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
2301}
2302
Douglas Gregor813a0662015-06-19 18:14:38 +00002303/// Determine whether two set of Objective-C declaration qualifiers conflict.
2304static bool objcModifiersConflict(Decl::ObjCDeclQualifier x,
2305 Decl::ObjCDeclQualifier y) {
2306 return (x & ~Decl::OBJC_TQ_CSNullability) !=
2307 (y & ~Decl::OBJC_TQ_CSNullability);
2308}
2309
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002310static bool CheckMethodOverrideReturn(Sema &S,
John McCall071df462010-10-28 02:34:38 +00002311 ObjCMethodDecl *MethodImpl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002312 ObjCMethodDecl *MethodDecl,
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002313 bool IsProtocolMethodDecl,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002314 bool IsOverridingMode,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002315 bool Warn) {
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002316 if (IsProtocolMethodDecl &&
Douglas Gregor813a0662015-06-19 18:14:38 +00002317 objcModifiersConflict(MethodDecl->getObjCDeclQualifier(),
2318 MethodImpl->getObjCDeclQualifier())) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002319 if (Warn) {
Alp Toker314cc812014-01-25 16:55:45 +00002320 S.Diag(MethodImpl->getLocation(),
2321 (IsOverridingMode
2322 ? diag::warn_conflicting_overriding_ret_type_modifiers
2323 : diag::warn_conflicting_ret_type_modifiers))
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002324 << MethodImpl->getDeclName()
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002325 << MethodImpl->getReturnTypeSourceRange();
Alp Toker314cc812014-01-25 16:55:45 +00002326 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002327 << MethodDecl->getReturnTypeSourceRange();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002328 }
2329 else
2330 return false;
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002331 }
Douglas Gregor813a0662015-06-19 18:14:38 +00002332 if (Warn && IsOverridingMode &&
2333 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2334 !S.Context.hasSameNullabilityTypeQualifier(MethodImpl->getReturnType(),
2335 MethodDecl->getReturnType(),
2336 false)) {
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002337 auto nullabilityMethodImpl =
2338 *MethodImpl->getReturnType()->getNullability(S.Context);
2339 auto nullabilityMethodDecl =
2340 *MethodDecl->getReturnType()->getNullability(S.Context);
Douglas Gregor813a0662015-06-19 18:14:38 +00002341 S.Diag(MethodImpl->getLocation(),
2342 diag::warn_conflicting_nullability_attr_overriding_ret_types)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002343 << DiagNullabilityKind(
2344 nullabilityMethodImpl,
2345 ((MethodImpl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2346 != 0))
2347 << DiagNullabilityKind(
2348 nullabilityMethodDecl,
2349 ((MethodDecl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2350 != 0));
Douglas Gregor813a0662015-06-19 18:14:38 +00002351 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2352 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002353
Alp Toker314cc812014-01-25 16:55:45 +00002354 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
2355 MethodDecl->getReturnType()))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002356 return true;
2357 if (!Warn)
2358 return false;
John McCall071df462010-10-28 02:34:38 +00002359
Fangrui Song6907ce22018-07-30 19:24:48 +00002360 unsigned DiagID =
2361 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002362 : diag::warn_conflicting_ret_types;
John McCall071df462010-10-28 02:34:38 +00002363
2364 // Mismatches between ObjC pointers go into a different warning
2365 // category, and sometimes they're even completely whitelisted.
2366 if (const ObjCObjectPointerType *ImplPtrTy =
Alp Toker314cc812014-01-25 16:55:45 +00002367 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
John McCall071df462010-10-28 02:34:38 +00002368 if (const ObjCObjectPointerType *IfacePtrTy =
Alp Toker314cc812014-01-25 16:55:45 +00002369 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
John McCall071df462010-10-28 02:34:38 +00002370 // Allow non-matching return types as long as they don't violate
2371 // the principle of substitutability. Specifically, we permit
2372 // return types that are subclasses of the declared return type,
2373 // or that are more-qualified versions of the declared type.
2374 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002375 return false;
John McCall071df462010-10-28 02:34:38 +00002376
Fangrui Song6907ce22018-07-30 19:24:48 +00002377 DiagID =
2378 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002379 : diag::warn_non_covariant_ret_types;
John McCall071df462010-10-28 02:34:38 +00002380 }
2381 }
2382
2383 S.Diag(MethodImpl->getLocation(), DiagID)
Alp Toker314cc812014-01-25 16:55:45 +00002384 << MethodImpl->getDeclName() << MethodDecl->getReturnType()
2385 << MethodImpl->getReturnType()
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002386 << MethodImpl->getReturnTypeSourceRange();
Alp Toker314cc812014-01-25 16:55:45 +00002387 S.Diag(MethodDecl->getLocation(), IsOverridingMode
2388 ? diag::note_previous_declaration
2389 : diag::note_previous_definition)
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002390 << MethodDecl->getReturnTypeSourceRange();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002391 return false;
John McCall071df462010-10-28 02:34:38 +00002392}
2393
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002394static bool CheckMethodOverrideParam(Sema &S,
John McCall071df462010-10-28 02:34:38 +00002395 ObjCMethodDecl *MethodImpl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002396 ObjCMethodDecl *MethodDecl,
John McCall071df462010-10-28 02:34:38 +00002397 ParmVarDecl *ImplVar,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002398 ParmVarDecl *IfaceVar,
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002399 bool IsProtocolMethodDecl,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002400 bool IsOverridingMode,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002401 bool Warn) {
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002402 if (IsProtocolMethodDecl &&
Douglas Gregor813a0662015-06-19 18:14:38 +00002403 objcModifiersConflict(ImplVar->getObjCDeclQualifier(),
2404 IfaceVar->getObjCDeclQualifier())) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002405 if (Warn) {
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002406 if (IsOverridingMode)
Fangrui Song6907ce22018-07-30 19:24:48 +00002407 S.Diag(ImplVar->getLocation(),
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002408 diag::warn_conflicting_overriding_param_modifiers)
2409 << getTypeRange(ImplVar->getTypeSourceInfo())
2410 << MethodImpl->getDeclName();
Fangrui Song6907ce22018-07-30 19:24:48 +00002411 else S.Diag(ImplVar->getLocation(),
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002412 diag::warn_conflicting_param_modifiers)
2413 << getTypeRange(ImplVar->getTypeSourceInfo())
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002414 << MethodImpl->getDeclName();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002415 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
Fangrui Song6907ce22018-07-30 19:24:48 +00002416 << getTypeRange(IfaceVar->getTypeSourceInfo());
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002417 }
2418 else
2419 return false;
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002420 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002421
John McCall071df462010-10-28 02:34:38 +00002422 QualType ImplTy = ImplVar->getType();
2423 QualType IfaceTy = IfaceVar->getType();
Douglas Gregor813a0662015-06-19 18:14:38 +00002424 if (Warn && IsOverridingMode &&
2425 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2426 !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) {
Douglas Gregor813a0662015-06-19 18:14:38 +00002427 S.Diag(ImplVar->getLocation(),
2428 diag::warn_conflicting_nullability_attr_overriding_param_types)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002429 << DiagNullabilityKind(
2430 *ImplTy->getNullability(S.Context),
2431 ((ImplVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2432 != 0))
2433 << DiagNullabilityKind(
2434 *IfaceTy->getNullability(S.Context),
2435 ((IfaceVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2436 != 0));
2437 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration);
Douglas Gregor813a0662015-06-19 18:14:38 +00002438 }
John McCall071df462010-10-28 02:34:38 +00002439 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002440 return true;
Manman Renc5705ba2016-09-13 17:41:05 +00002441
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002442 if (!Warn)
2443 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00002444 unsigned DiagID =
2445 IsOverridingMode ? diag::warn_conflicting_overriding_param_types
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002446 : diag::warn_conflicting_param_types;
John McCall071df462010-10-28 02:34:38 +00002447
2448 // Mismatches between ObjC pointers go into a different warning
2449 // category, and sometimes they're even completely whitelisted.
2450 if (const ObjCObjectPointerType *ImplPtrTy =
2451 ImplTy->getAs<ObjCObjectPointerType>()) {
2452 if (const ObjCObjectPointerType *IfacePtrTy =
2453 IfaceTy->getAs<ObjCObjectPointerType>()) {
2454 // Allow non-matching argument types as long as they don't
2455 // violate the principle of substitutability. Specifically, the
2456 // implementation must accept any objects that the superclass
2457 // accepts, however it may also accept others.
2458 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002459 return false;
John McCall071df462010-10-28 02:34:38 +00002460
Fangrui Song6907ce22018-07-30 19:24:48 +00002461 DiagID =
2462 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002463 : diag::warn_non_contravariant_param_types;
John McCall071df462010-10-28 02:34:38 +00002464 }
2465 }
2466
2467 S.Diag(ImplVar->getLocation(), DiagID)
2468 << getTypeRange(ImplVar->getTypeSourceInfo())
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002469 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
Fangrui Song6907ce22018-07-30 19:24:48 +00002470 S.Diag(IfaceVar->getLocation(),
2471 (IsOverridingMode ? diag::note_previous_declaration
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002472 : diag::note_previous_definition))
John McCall071df462010-10-28 02:34:38 +00002473 << getTypeRange(IfaceVar->getTypeSourceInfo());
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002474 return false;
John McCall071df462010-10-28 02:34:38 +00002475}
John McCall31168b02011-06-15 23:02:42 +00002476
2477/// In ARC, check whether the conventional meanings of the two methods
2478/// match. If they don't, it's a hard error.
2479static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
2480 ObjCMethodDecl *decl) {
2481 ObjCMethodFamily implFamily = impl->getMethodFamily();
2482 ObjCMethodFamily declFamily = decl->getMethodFamily();
2483 if (implFamily == declFamily) return false;
2484
2485 // Since conventions are sorted by selector, the only possibility is
2486 // that the types differ enough to cause one selector or the other
2487 // to fall out of the family.
2488 assert(implFamily == OMF_None || declFamily == OMF_None);
2489
2490 // No further diagnostics required on invalid declarations.
2491 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
2492
2493 const ObjCMethodDecl *unmatched = impl;
2494 ObjCMethodFamily family = declFamily;
2495 unsigned errorID = diag::err_arc_lost_method_convention;
2496 unsigned noteID = diag::note_arc_lost_method_convention;
2497 if (declFamily == OMF_None) {
2498 unmatched = decl;
2499 family = implFamily;
2500 errorID = diag::err_arc_gained_method_convention;
2501 noteID = diag::note_arc_gained_method_convention;
2502 }
2503
2504 // Indexes into a %select clause in the diagnostic.
2505 enum FamilySelector {
2506 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
2507 };
2508 FamilySelector familySelector = FamilySelector();
2509
2510 switch (family) {
2511 case OMF_None: llvm_unreachable("logic error, no method convention");
2512 case OMF_retain:
2513 case OMF_release:
2514 case OMF_autorelease:
2515 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +00002516 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002517 case OMF_retainCount:
2518 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002519 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002520 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00002521 // Mismatches for these methods don't change ownership
2522 // conventions, so we don't care.
2523 return false;
2524
2525 case OMF_init: familySelector = F_init; break;
2526 case OMF_alloc: familySelector = F_alloc; break;
2527 case OMF_copy: familySelector = F_copy; break;
2528 case OMF_mutableCopy: familySelector = F_mutableCopy; break;
2529 case OMF_new: familySelector = F_new; break;
2530 }
2531
2532 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
2533 ReasonSelector reasonSelector;
2534
2535 // The only reason these methods don't fall within their families is
2536 // due to unusual result types.
Alp Toker314cc812014-01-25 16:55:45 +00002537 if (unmatched->getReturnType()->isObjCObjectPointerType()) {
John McCall31168b02011-06-15 23:02:42 +00002538 reasonSelector = R_UnrelatedReturn;
2539 } else {
2540 reasonSelector = R_NonObjectReturn;
2541 }
2542
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00002543 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
2544 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
John McCall31168b02011-06-15 23:02:42 +00002545
2546 return true;
2547}
John McCall071df462010-10-28 02:34:38 +00002548
Fariborz Jahanian7988d7d2008-12-05 18:18:52 +00002549void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002550 ObjCMethodDecl *MethodDecl,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002551 bool IsProtocolMethodDecl) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002552 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002553 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
2554 return;
2555
Fangrui Song6907ce22018-07-30 19:24:48 +00002556 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2557 IsProtocolMethodDecl, false,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002558 true);
Mike Stump11289f42009-09-09 15:08:12 +00002559
Chris Lattner67f35b02009-04-11 19:58:42 +00002560 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002561 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2562 EF = MethodDecl->param_end();
2563 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002564 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002565 IsProtocolMethodDecl, false, true);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002566 }
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002567
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002568 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002569 Diag(ImpMethodDecl->getLocation(),
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002570 diag::warn_conflicting_variadic);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002571 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002572 }
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002573}
2574
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002575void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2576 ObjCMethodDecl *Overridden,
2577 bool IsProtocolMethodDecl) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002578
2579 CheckMethodOverrideReturn(*this, Method, Overridden,
2580 IsProtocolMethodDecl, true,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002581 true);
Fangrui Song6907ce22018-07-30 19:24:48 +00002582
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002583 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002584 IF = Overridden->param_begin(), EM = Method->param_end(),
2585 EF = Overridden->param_end();
2586 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002587 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
2588 IsProtocolMethodDecl, true, true);
2589 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002590
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002591 if (Method->isVariadic() != Overridden->isVariadic()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002592 Diag(Method->getLocation(),
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002593 diag::warn_conflicting_overriding_variadic);
2594 Diag(Overridden->getLocation(), diag::note_previous_declaration);
2595 }
2596}
2597
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002598/// WarnExactTypedMethods - This routine issues a warning if method
2599/// implementation declaration matches exactly that of its declaration.
2600void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2601 ObjCMethodDecl *MethodDecl,
2602 bool IsProtocolMethodDecl) {
2603 // don't issue warning when protocol method is optional because primary
2604 // class is not required to implement it and it is safe for protocol
2605 // to implement it.
2606 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
2607 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00002608 // don't issue warning when primary class's method is
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002609 // depecated/unavailable.
2610 if (MethodDecl->hasAttr<UnavailableAttr>() ||
2611 MethodDecl->hasAttr<DeprecatedAttr>())
2612 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00002613
2614 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002615 IsProtocolMethodDecl, false, false);
2616 if (match)
2617 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002618 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2619 EF = MethodDecl->param_end();
2620 IM != EM && IF != EF; ++IM, ++IF) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002621 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002622 *IM, *IF,
2623 IsProtocolMethodDecl, false, false);
2624 if (!match)
2625 break;
2626 }
2627 if (match)
2628 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
David Chisnall92918512011-08-08 17:32:19 +00002629 if (match)
2630 match = !(MethodDecl->isClassMethod() &&
2631 MethodDecl->getSelector() == GetNullarySelector("load", Context));
Fangrui Song6907ce22018-07-30 19:24:48 +00002632
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002633 if (match) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002634 Diag(ImpMethodDecl->getLocation(),
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002635 diag::warn_category_method_impl_match);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002636 Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
2637 << MethodDecl->getDeclName();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002638 }
2639}
2640
Mike Stump87c57ac2009-05-16 07:39:55 +00002641/// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
2642/// improve the efficiency of selector lookups and type checking by associating
2643/// with each protocol / interface / category the flattened instance tables. If
2644/// we used an immutable set to keep the table then it wouldn't add significant
2645/// memory cost and it would be handy for lookups.
Daniel Dunbar4684f372008-08-27 05:40:03 +00002646
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002647typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
Ahmed Charlesaf94d562014-03-09 11:34:25 +00002648typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002649
2650static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
2651 ProtocolNameSet &PNS) {
2652 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
2653 PNS.insert(PDecl->getIdentifier());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002654 for (const auto *PI : PDecl->protocols())
2655 findProtocolsWithExplicitImpls(PI, PNS);
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002656}
2657
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002658/// Recursively populates a set with all conformed protocols in a class
2659/// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
2660/// attribute.
2661static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
2662 ProtocolNameSet &PNS) {
2663 if (!Super)
2664 return;
2665
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002666 for (const auto *I : Super->all_referenced_protocols())
2667 findProtocolsWithExplicitImpls(I, PNS);
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002668
2669 findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002670}
2671
Steve Naroffa36992242008-02-08 22:06:17 +00002672/// CheckProtocolMethodDefs - This routine checks unimplemented methods
Chris Lattnerda463fe2007-12-12 07:09:47 +00002673/// Declared in protocol, and those referenced by it.
Ted Kremenek285ee852013-12-13 06:26:10 +00002674static void CheckProtocolMethodDefs(Sema &S,
2675 SourceLocation ImpLoc,
2676 ObjCProtocolDecl *PDecl,
2677 bool& IncompleteImpl,
2678 const Sema::SelectorSet &InsMap,
2679 const Sema::SelectorSet &ClsMap,
Ted Kremenek33e430f2013-12-13 06:26:14 +00002680 ObjCContainerDecl *CDecl,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002681 LazyProtocolNameSet &ProtocolsExplictImpl) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002682 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00002683 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002684 : dyn_cast<ObjCInterfaceDecl>(CDecl);
Fariborz Jahanian2e8074b2010-03-27 21:10:05 +00002685 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
Fangrui Song6907ce22018-07-30 19:24:48 +00002686
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002687 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
Craig Topperc3ec1492014-05-26 06:22:03 +00002688 ObjCInterfaceDecl *NSIDecl = nullptr;
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002689
2690 // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
2691 // then we should check if any class in the super class hierarchy also
2692 // conforms to this protocol, either directly or via protocol inheritance.
2693 // If so, we can skip checking this protocol completely because we
2694 // know that a parent class already satisfies this protocol.
2695 //
2696 // Note: we could generalize this logic for all protocols, and merely
2697 // add the limit on looking at the super class chain for just
2698 // specially marked protocols. This may be a good optimization. This
2699 // change is restricted to 'objc_protocol_requires_explicit_implementation'
2700 // protocols for now for controlled evaluation.
2701 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
Ahmed Charlesaf94d562014-03-09 11:34:25 +00002702 if (!ProtocolsExplictImpl) {
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002703 ProtocolsExplictImpl.reset(new ProtocolNameSet);
2704 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
2705 }
2706 if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
2707 ProtocolsExplictImpl->end())
2708 return;
2709
2710 // If no super class conforms to the protocol, we should not search
2711 // for methods in the super class to implicitly satisfy the protocol.
Craig Topperc3ec1492014-05-26 06:22:03 +00002712 Super = nullptr;
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002713 }
2714
Ted Kremenek285ee852013-12-13 06:26:10 +00002715 if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
Mike Stump11289f42009-09-09 15:08:12 +00002716 // check to see if class implements forwardInvocation method and objects
2717 // of this class are derived from 'NSProxy' so that to forward requests
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002718 // from one object to another.
Mike Stump11289f42009-09-09 15:08:12 +00002719 // Under such conditions, which means that every method possible is
2720 // implemented in the class, we should not issue "Method definition not
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002721 // found" warnings.
2722 // FIXME: Use a general GetUnarySelector method for this.
Ted Kremenek285ee852013-12-13 06:26:10 +00002723 IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
2724 Selector fISelector = S.Context.Selectors.getSelector(1, &II);
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002725 if (InsMap.count(fISelector))
2726 // Is IDecl derived from 'NSProxy'? If so, no instance methods
2727 // need be implemented in the implementation.
Ted Kremenek285ee852013-12-13 06:26:10 +00002728 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002729 }
Mike Stump11289f42009-09-09 15:08:12 +00002730
Fariborz Jahanianc41cf052013-01-07 19:21:03 +00002731 // If this is a forward protocol declaration, get its definition.
2732 if (!PDecl->isThisDeclarationADefinition() &&
2733 PDecl->getDefinition())
2734 PDecl = PDecl->getDefinition();
Fangrui Song6907ce22018-07-30 19:24:48 +00002735
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002736 // If a method lookup fails locally we still need to look and see if
2737 // the method was implemented by a base class or an inherited
2738 // protocol. This lookup is slow, but occurs rarely in correct code
2739 // and otherwise would terminate in a warning.
2740
Chris Lattnerda463fe2007-12-12 07:09:47 +00002741 // check unimplemented instance methods.
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002742 if (!NSIDecl)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002743 for (auto *method : PDecl->instance_methods()) {
Mike Stump11289f42009-09-09 15:08:12 +00002744 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
Jordan Rosed01e83a2012-10-10 16:42:25 +00002745 !method->isPropertyAccessor() &&
2746 !InsMap.count(method->getSelector()) &&
Ted Kremenek00781502013-11-23 01:01:29 +00002747 (!Super || !Super->lookupMethod(method->getSelector(),
2748 true /* instance */,
2749 false /* shallowCategory */,
Ted Kremenek28eace62013-11-23 01:01:34 +00002750 true /* followsSuper */,
Craig Topperc3ec1492014-05-26 06:22:03 +00002751 nullptr /* category */))) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002752 // If a method is not implemented in the category implementation but
2753 // has been declared in its primary class, superclass,
Fangrui Song6907ce22018-07-30 19:24:48 +00002754 // or in one of their protocols, no need to issue the warning.
2755 // This is because method will be implemented in the primary class
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002756 // or one of its super class implementation.
Fangrui Song6907ce22018-07-30 19:24:48 +00002757
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002758 // Ugly, but necessary. Method declared in protocol might have
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002759 // have been synthesized due to a property declared in the class which
2760 // uses the protocol.
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002761 if (ObjCMethodDecl *MethodInClass =
Ted Kremenek00781502013-11-23 01:01:29 +00002762 IDecl->lookupMethod(method->getSelector(),
2763 true /* instance */,
2764 true /* shallowCategoryLookup */,
2765 false /* followSuper */))
Jordan Rosed01e83a2012-10-10 16:42:25 +00002766 if (C || MethodInClass->isPropertyAccessor())
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002767 continue;
2768 unsigned DIAG = diag::warn_unimplemented_protocol_method;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002769 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
Ted Kremenek285ee852013-12-13 06:26:10 +00002770 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002771 PDecl);
Fariborz Jahanian97752f72010-03-27 19:02:17 +00002772 }
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002773 }
2774 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002775 // check unimplemented class methods
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002776 for (auto *method : PDecl->class_methods()) {
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002777 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
2778 !ClsMap.count(method->getSelector()) &&
Ted Kremenek00781502013-11-23 01:01:29 +00002779 (!Super || !Super->lookupMethod(method->getSelector(),
2780 false /* class method */,
2781 false /* shallowCategoryLookup */,
Ted Kremenek28eace62013-11-23 01:01:34 +00002782 true /* followSuper */,
Craig Topperc3ec1492014-05-26 06:22:03 +00002783 nullptr /* category */))) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002784 // See above comment for instance method lookups.
Ted Kremenek00781502013-11-23 01:01:29 +00002785 if (C && IDecl->lookupMethod(method->getSelector(),
2786 false /* class */,
2787 true /* shallowCategoryLookup */,
2788 false /* followSuper */))
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002789 continue;
Ted Kremenek00781502013-11-23 01:01:29 +00002790
Fariborz Jahanianc1fb8622010-03-31 18:23:33 +00002791 unsigned DIAG = diag::warn_unimplemented_protocol_method;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002792 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
Ted Kremenek285ee852013-12-13 06:26:10 +00002793 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
Fariborz Jahanianc1fb8622010-03-31 18:23:33 +00002794 }
Fariborz Jahanian97752f72010-03-27 19:02:17 +00002795 }
Steve Naroff3ce37a62007-12-14 23:37:57 +00002796 }
Chris Lattner390d39a2008-07-21 21:32:27 +00002797 // Check on this protocols's referenced protocols, recursively.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002798 for (auto *PI : PDecl->protocols())
2799 CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002800 CDecl, ProtocolsExplictImpl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002801}
2802
Fariborz Jahanianf9ae68a2011-07-16 00:08:33 +00002803/// MatchAllMethodDeclarations - Check methods declared in interface
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002804/// or protocol against those declared in their implementations.
2805///
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002806void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
2807 const SelectorSet &ClsMap,
2808 SelectorSet &InsMapSeen,
2809 SelectorSet &ClsMapSeen,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002810 ObjCImplDecl* IMPDecl,
2811 ObjCContainerDecl* CDecl,
2812 bool &IncompleteImpl,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002813 bool ImmediateClass,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002814 bool WarnCategoryMethodImpl) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002815 // Check and see if instance methods in class interface have been
2816 // implemented in the implementation class. If so, their types match.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002817 for (auto *I : CDecl->instance_methods()) {
David Blaikie82e95a32014-11-19 07:49:47 +00002818 if (!InsMapSeen.insert(I->getSelector()).second)
Benjamin Kramer9f8e2d72013-10-14 15:16:10 +00002819 continue;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002820 if (!I->isPropertyAccessor() &&
2821 !InsMap.count(I->getSelector())) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002822 if (ImmediateClass)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002823 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
Ted Kremenek65d63572013-03-27 00:02:21 +00002824 diag::warn_undef_method_impl);
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002825 continue;
Mike Stump12b8ce12009-08-04 21:02:39 +00002826 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002827 ObjCMethodDecl *ImpMethodDecl =
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002828 IMPDecl->getInstanceMethod(I->getSelector());
Manman Rena58f92f2016-10-11 21:18:20 +00002829 assert(CDecl->getInstanceMethod(I->getSelector(), true/*AllowHidden*/) &&
Argyrios Kyrtzidis342e08f2011-08-30 19:43:21 +00002830 "Expected to find the method through lookup as well");
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002831 // ImpMethodDecl may be null as in a @dynamic property.
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002832 if (ImpMethodDecl) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002833 if (!WarnCategoryMethodImpl)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002834 WarnConflictingTypedMethods(ImpMethodDecl, I,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002835 isa<ObjCProtocolDecl>(CDecl));
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002836 else if (!I->isPropertyAccessor())
2837 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002838 }
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002839 }
2840 }
Mike Stump11289f42009-09-09 15:08:12 +00002841
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002842 // Check and see if class methods in class interface have been
2843 // implemented in the implementation class. If so, their types match.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002844 for (auto *I : CDecl->class_methods()) {
David Blaikie82e95a32014-11-19 07:49:47 +00002845 if (!ClsMapSeen.insert(I->getSelector()).second)
Benjamin Kramer9f8e2d72013-10-14 15:16:10 +00002846 continue;
Manman Rend36f7d52016-01-27 20:10:32 +00002847 if (!I->isPropertyAccessor() &&
2848 !ClsMap.count(I->getSelector())) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002849 if (ImmediateClass)
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002850 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
Ted Kremenek65d63572013-03-27 00:02:21 +00002851 diag::warn_undef_method_impl);
Mike Stump12b8ce12009-08-04 21:02:39 +00002852 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002853 ObjCMethodDecl *ImpMethodDecl =
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002854 IMPDecl->getClassMethod(I->getSelector());
Manman Rena58f92f2016-10-11 21:18:20 +00002855 assert(CDecl->getClassMethod(I->getSelector(), true/*AllowHidden*/) &&
Argyrios Kyrtzidis342e08f2011-08-30 19:43:21 +00002856 "Expected to find the method through lookup as well");
Manman Rend36f7d52016-01-27 20:10:32 +00002857 // ImpMethodDecl may be null as in a @dynamic property.
2858 if (ImpMethodDecl) {
2859 if (!WarnCategoryMethodImpl)
2860 WarnConflictingTypedMethods(ImpMethodDecl, I,
2861 isa<ObjCProtocolDecl>(CDecl));
2862 else if (!I->isPropertyAccessor())
2863 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2864 }
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002865 }
2866 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002867
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002868 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
2869 // Also, check for methods declared in protocols inherited by
2870 // this protocol.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002871 for (auto *PI : PD->protocols())
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002872 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002873 IMPDecl, PI, IncompleteImpl, false,
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002874 WarnCategoryMethodImpl);
2875 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002876
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002877 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002878 // when checking that methods in implementation match their declaration,
2879 // i.e. when WarnCategoryMethodImpl is false, check declarations in class
2880 // extension; as well as those in categories.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002881 if (!WarnCategoryMethodImpl) {
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002882 for (auto *Cat : I->visible_categories())
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002883 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Argyrios Kyrtzidis3a437542015-10-13 23:27:34 +00002884 IMPDecl, Cat, IncompleteImpl,
2885 ImmediateClass && Cat->IsClassExtension(),
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002886 WarnCategoryMethodImpl);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002887 } else {
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002888 // Also methods in class extensions need be looked at next.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002889 for (auto *Ext : I->visible_extensions())
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002890 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002891 IMPDecl, Ext, IncompleteImpl, false,
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002892 WarnCategoryMethodImpl);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002893 }
2894
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002895 // Check for any implementation of a methods declared in protocol.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002896 for (auto *PI : I->all_referenced_protocols())
Mike Stump11289f42009-09-09 15:08:12 +00002897 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002898 IMPDecl, PI, IncompleteImpl, false,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002899 WarnCategoryMethodImpl);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002900
Raphael Isemannb23ccec2018-12-10 12:37:46 +00002901 // FIXME. For now, we are not checking for exact match of methods
Fangrui Song6907ce22018-07-30 19:24:48 +00002902 // in category implementation and its primary class's super class.
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002903 if (!WarnCategoryMethodImpl && I->getSuperClass())
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002904 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Mike Stump11289f42009-09-09 15:08:12 +00002905 IMPDecl,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002906 I->getSuperClass(), IncompleteImpl, false);
2907 }
2908}
2909
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002910/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2911/// category matches with those implemented in its primary class and
Fangrui Song6907ce22018-07-30 19:24:48 +00002912/// warns each time an exact match is found.
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002913void Sema::CheckCategoryVsClassMethodMatches(
2914 ObjCCategoryImplDecl *CatIMPDecl) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002915 // Get category's primary class.
2916 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
2917 if (!CatDecl)
2918 return;
2919 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
2920 if (!IDecl)
2921 return;
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002922 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
2923 SelectorSet InsMap, ClsMap;
Fangrui Song6907ce22018-07-30 19:24:48 +00002924
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002925 for (const auto *I : CatIMPDecl->instance_methods()) {
2926 Selector Sel = I->getSelector();
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002927 // When checking for methods implemented in the category, skip over
2928 // those declared in category class's super class. This is because
2929 // the super class must implement the method.
2930 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
2931 continue;
2932 InsMap.insert(Sel);
2933 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002934
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002935 for (const auto *I : CatIMPDecl->class_methods()) {
2936 Selector Sel = I->getSelector();
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002937 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
2938 continue;
2939 ClsMap.insert(Sel);
2940 }
2941 if (InsMap.empty() && ClsMap.empty())
2942 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00002943
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002944 SelectorSet InsMapSeen, ClsMapSeen;
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002945 bool IncompleteImpl = false;
2946 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2947 CatIMPDecl, IDecl,
Fangrui Song6907ce22018-07-30 19:24:48 +00002948 IncompleteImpl, false,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002949 true /*WarnCategoryMethodImpl*/);
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002950}
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002951
Fariborz Jahanian25491a22010-05-05 21:52:17 +00002952void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002953 ObjCContainerDecl* CDecl,
Chris Lattner9ef10f42009-03-01 00:56:52 +00002954 bool IncompleteImpl) {
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002955 SelectorSet InsMap;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002956 // Check and see if instance methods in class interface have been
2957 // implemented in the implementation class.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002958 for (const auto *I : IMPDecl->instance_methods())
2959 InsMap.insert(I->getSelector());
Mike Stump11289f42009-09-09 15:08:12 +00002960
Douglas Gregoracf4fd32015-11-03 01:15:46 +00002961 // Add the selectors for getters/setters of @dynamic properties.
2962 for (const auto *PImpl : IMPDecl->property_impls()) {
2963 // We only care about @dynamic implementations.
2964 if (PImpl->getPropertyImplementation() != ObjCPropertyImplDecl::Dynamic)
2965 continue;
2966
2967 const auto *P = PImpl->getPropertyDecl();
2968 if (!P) continue;
2969
2970 InsMap.insert(P->getGetterName());
2971 if (!P->getSetterName().isNull())
2972 InsMap.insert(P->getSetterName());
2973 }
2974
Fariborz Jahanian6c6aea92009-04-14 23:15:21 +00002975 // Check and see if properties declared in the interface have either 1)
2976 // an implementation or 2) there is a @synthesize/@dynamic implementation
2977 // of the property in the @implementation.
Ted Kremenek348e88c2014-02-21 19:41:34 +00002978 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2979 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
2980 LangOpts.ObjCRuntime.isNonFragile() &&
2981 !IDecl->isObjCRequiresPropertyDefs();
2982 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
2983 }
2984
Douglas Gregor849ebc22015-06-19 18:14:46 +00002985 // Diagnose null-resettable synthesized setters.
2986 diagnoseNullResettableSynthesizedSetters(IMPDecl);
2987
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002988 SelectorSet ClsMap;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002989 for (const auto *I : IMPDecl->class_methods())
2990 ClsMap.insert(I->getSelector());
Mike Stump11289f42009-09-09 15:08:12 +00002991
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002992 // Check for type conflict of methods declared in a class/protocol and
2993 // its implementation; if any.
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002994 SelectorSet InsMapSeen, ClsMapSeen;
Mike Stump11289f42009-09-09 15:08:12 +00002995 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2996 IMPDecl, CDecl,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002997 IncompleteImpl, true);
Fangrui Song6907ce22018-07-30 19:24:48 +00002998
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002999 // check all methods implemented in category against those declared
3000 // in its primary class.
Fangrui Song6907ce22018-07-30 19:24:48 +00003001 if (ObjCCategoryImplDecl *CatDecl =
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00003002 dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
3003 CheckCategoryVsClassMethodMatches(CatDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003004
Chris Lattnerda463fe2007-12-12 07:09:47 +00003005 // Check the protocol list for unimplemented methods in the @implementation
3006 // class.
Fariborz Jahanian07b71652009-05-01 20:07:12 +00003007 // Check and see if class methods in class interface have been
3008 // implemented in the implementation class.
Mike Stump11289f42009-09-09 15:08:12 +00003009
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00003010 LazyProtocolNameSet ExplicitImplProtocols;
3011
Chris Lattner9ef10f42009-03-01 00:56:52 +00003012 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003013 for (auto *PI : I->all_referenced_protocols())
3014 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl,
3015 InsMap, ClsMap, I, ExplicitImplProtocols);
Chris Lattner9ef10f42009-03-01 00:56:52 +00003016 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahanian8764c742009-10-05 21:32:49 +00003017 // For extended class, unimplemented methods in its protocols will
3018 // be reported in the primary class.
Fariborz Jahanian30a42922010-02-15 21:55:26 +00003019 if (!C->IsClassExtension()) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003020 for (auto *P : C->protocols())
3021 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00003022 IncompleteImpl, InsMap, ClsMap, CDecl,
3023 ExplicitImplProtocols);
Ted Kremenek348e88c2014-02-21 19:41:34 +00003024 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
Nico Weber2e0c8f72014-12-27 03:58:08 +00003025 /*SynthesizeProperties=*/false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003026 }
Chris Lattner9ef10f42009-03-01 00:56:52 +00003027 } else
David Blaikie83d382b2011-09-23 05:06:16 +00003028 llvm_unreachable("invalid ObjCContainerDecl type.");
Chris Lattnerda463fe2007-12-12 07:09:47 +00003029}
3030
Fariborz Jahanian3a039e32011-08-27 20:50:59 +00003031Sema::DeclGroupPtrTy
Chris Lattnerda463fe2007-12-12 07:09:47 +00003032Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
Chris Lattner99a83312009-02-16 19:25:52 +00003033 IdentifierInfo **IdentList,
Ted Kremeneka26da852009-11-17 23:12:20 +00003034 SourceLocation *IdentLocs,
Douglas Gregor85f3f952015-07-07 03:57:15 +00003035 ArrayRef<ObjCTypeParamList *> TypeParamLists,
Chris Lattner99a83312009-02-16 19:25:52 +00003036 unsigned NumElts) {
Fariborz Jahanian3a039e32011-08-27 20:50:59 +00003037 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003038 for (unsigned i = 0; i != NumElts; ++i) {
3039 // Check for another declaration kind with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00003040 NamedDecl *PrevDecl
Fangrui Song6907ce22018-07-30 19:24:48 +00003041 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
Richard Smithbecb92d2017-10-10 22:33:17 +00003042 LookupOrdinaryName, forRedeclarationInCurContext());
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003043 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Steve Naroff946166f2008-06-05 22:57:10 +00003044 // GCC apparently allows the following idiom:
3045 //
3046 // typedef NSObject < XCElementTogglerP > XCElementToggler;
3047 // @class XCElementToggler;
3048 //
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003049 // Here we have chosen to ignore the forward class declaration
3050 // with a warning. Since this is the implied behavior.
Richard Smithdda56e42011-04-15 14:24:37 +00003051 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
John McCall8b07ec22010-05-15 11:32:37 +00003052 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003053 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
Chris Lattner0369c572008-11-23 23:12:31 +00003054 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall8b07ec22010-05-15 11:32:37 +00003055 } else {
Mike Stump12b8ce12009-08-04 21:02:39 +00003056 // a forward class declaration matching a typedef name of a class refers
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003057 // to the underlying class. Just ignore the forward class with a warning
Nico Weber2e0c8f72014-12-27 03:58:08 +00003058 // as this will force the intended behavior which is to lookup the
3059 // typedef name.
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003060 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003061 Diag(AtClassLoc, diag::warn_forward_class_redefinition)
3062 << IdentList[i];
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003063 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3064 continue;
3065 }
Fariborz Jahanian0d451812009-05-07 21:49:26 +00003066 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003067 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003068
Douglas Gregordc9166c2011-12-15 20:29:51 +00003069 // Create a declaration to describe this forward declaration.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003070 ObjCInterfaceDecl *PrevIDecl
3071 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidisdd710632013-06-18 21:26:33 +00003072
3073 IdentifierInfo *ClassName = IdentList[i];
3074 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
3075 // A previous decl with a different name is because of
3076 // @compatibility_alias, for example:
3077 // \code
3078 // @class NewImage;
3079 // @compatibility_alias OldImage NewImage;
3080 // \endcode
3081 // A lookup for 'OldImage' will return the 'NewImage' decl.
3082 //
3083 // In such a case use the real declaration name, instead of the alias one,
3084 // otherwise we will break IdentifierResolver and redecls-chain invariants.
3085 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
3086 // has been aliased.
3087 ClassName = PrevIDecl->getIdentifier();
3088 }
3089
Douglas Gregor85f3f952015-07-07 03:57:15 +00003090 // If this forward declaration has type parameters, compare them with the
3091 // type parameters of the previous declaration.
3092 ObjCTypeParamList *TypeParams = TypeParamLists[i];
3093 if (PrevIDecl && TypeParams) {
3094 if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) {
3095 // Check for consistency with the previous declaration.
3096 if (checkTypeParamListConsistency(
3097 *this, PrevTypeParams, TypeParams,
3098 TypeParamListContext::ForwardDeclaration)) {
3099 TypeParams = nullptr;
3100 }
3101 } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
3102 // The @interface does not have type parameters. Complain.
3103 Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class)
3104 << ClassName
3105 << TypeParams->getSourceRange();
3106 Diag(Def->getLocation(), diag::note_defined_here)
3107 << ClassName;
3108
3109 TypeParams = nullptr;
3110 }
3111 }
3112
Douglas Gregordc9166c2011-12-15 20:29:51 +00003113 ObjCInterfaceDecl *IDecl
3114 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00003115 ClassName, TypeParams, PrevIDecl,
3116 IdentLocs[i]);
Douglas Gregordc9166c2011-12-15 20:29:51 +00003117 IDecl->setAtEndRange(IdentLocs[i]);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003118
Douglas Gregordc9166c2011-12-15 20:29:51 +00003119 PushOnScopeChains(IDecl, TUScope);
Douglas Gregordeafd0b2011-12-27 22:43:10 +00003120 CheckObjCDeclScope(IDecl);
3121 DeclsInGroup.push_back(IDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003122 }
Rafael Espindolaab417692013-07-09 12:05:01 +00003123
Richard Smith3beb7c62017-01-12 02:27:38 +00003124 return BuildDeclaratorGroup(DeclsInGroup);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003125}
3126
John McCall54507ab2011-06-16 01:15:19 +00003127static bool tryMatchRecordTypes(ASTContext &Context,
3128 Sema::MethodMatchStrategy strategy,
3129 const Type *left, const Type *right);
3130
John McCall31168b02011-06-15 23:02:42 +00003131static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
3132 QualType leftQT, QualType rightQT) {
3133 const Type *left =
3134 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
3135 const Type *right =
3136 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
3137
3138 if (left == right) return true;
3139
3140 // If we're doing a strict match, the types have to match exactly.
3141 if (strategy == Sema::MMS_strict) return false;
3142
3143 if (left->isIncompleteType() || right->isIncompleteType()) return false;
3144
3145 // Otherwise, use this absurdly complicated algorithm to try to
3146 // validate the basic, low-level compatibility of the two types.
3147
3148 // As a minimum, require the sizes and alignments to match.
David Majnemer34b57492014-07-30 01:30:47 +00003149 TypeInfo LeftTI = Context.getTypeInfo(left);
3150 TypeInfo RightTI = Context.getTypeInfo(right);
3151 if (LeftTI.Width != RightTI.Width)
3152 return false;
3153
3154 if (LeftTI.Align != RightTI.Align)
John McCall31168b02011-06-15 23:02:42 +00003155 return false;
3156
3157 // Consider all the kinds of non-dependent canonical types:
3158 // - functions and arrays aren't possible as return and parameter types
Fangrui Song6907ce22018-07-30 19:24:48 +00003159
John McCall31168b02011-06-15 23:02:42 +00003160 // - vector types of equal size can be arbitrarily mixed
3161 if (isa<VectorType>(left)) return isa<VectorType>(right);
3162 if (isa<VectorType>(right)) return false;
3163
3164 // - references should only match references of identical type
John McCall54507ab2011-06-16 01:15:19 +00003165 // - structs, unions, and Objective-C objects must match more-or-less
3166 // exactly
John McCall31168b02011-06-15 23:02:42 +00003167 // - everything else should be a scalar
3168 if (!left->isScalarType() || !right->isScalarType())
John McCall54507ab2011-06-16 01:15:19 +00003169 return tryMatchRecordTypes(Context, strategy, left, right);
John McCall31168b02011-06-15 23:02:42 +00003170
John McCall9320b872011-09-09 05:25:32 +00003171 // Make scalars agree in kind, except count bools as chars, and group
3172 // all non-member pointers together.
John McCall31168b02011-06-15 23:02:42 +00003173 Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
3174 Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
3175 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
3176 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
John McCall9320b872011-09-09 05:25:32 +00003177 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
3178 leftSK = Type::STK_ObjCObjectPointer;
3179 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
3180 rightSK = Type::STK_ObjCObjectPointer;
John McCall31168b02011-06-15 23:02:42 +00003181
3182 // Note that data member pointers and function member pointers don't
3183 // intermix because of the size differences.
3184
3185 return (leftSK == rightSK);
3186}
Chris Lattnerda463fe2007-12-12 07:09:47 +00003187
John McCall54507ab2011-06-16 01:15:19 +00003188static bool tryMatchRecordTypes(ASTContext &Context,
3189 Sema::MethodMatchStrategy strategy,
3190 const Type *lt, const Type *rt) {
3191 assert(lt && rt && lt != rt);
3192
3193 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
3194 RecordDecl *left = cast<RecordType>(lt)->getDecl();
3195 RecordDecl *right = cast<RecordType>(rt)->getDecl();
3196
3197 // Require union-hood to match.
3198 if (left->isUnion() != right->isUnion()) return false;
3199
3200 // Require an exact match if either is non-POD.
3201 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
3202 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
3203 return false;
3204
3205 // Require size and alignment to match.
David Majnemer34b57492014-07-30 01:30:47 +00003206 TypeInfo LeftTI = Context.getTypeInfo(lt);
3207 TypeInfo RightTI = Context.getTypeInfo(rt);
3208 if (LeftTI.Width != RightTI.Width)
3209 return false;
3210
3211 if (LeftTI.Align != RightTI.Align)
3212 return false;
John McCall54507ab2011-06-16 01:15:19 +00003213
3214 // Require fields to match.
3215 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
3216 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
3217 for (; li != le && ri != re; ++li, ++ri) {
3218 if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
3219 return false;
3220 }
3221 return (li == le && ri == re);
3222}
3223
Chris Lattnerda463fe2007-12-12 07:09:47 +00003224/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
3225/// returns true, or false, accordingly.
3226/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
John McCall31168b02011-06-15 23:02:42 +00003227bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
3228 const ObjCMethodDecl *right,
3229 MethodMatchStrategy strategy) {
Alp Toker314cc812014-01-25 16:55:45 +00003230 if (!matchTypes(Context, strategy, left->getReturnType(),
3231 right->getReturnType()))
John McCall31168b02011-06-15 23:02:42 +00003232 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003233
Douglas Gregor560b7fa2013-02-07 19:13:24 +00003234 // If either is hidden, it is not considered to match.
3235 if (left->isHidden() || right->isHidden())
3236 return false;
3237
David Blaikiebbafb8a2012-03-11 07:00:24 +00003238 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003239 (left->hasAttr<NSReturnsRetainedAttr>()
3240 != right->hasAttr<NSReturnsRetainedAttr>() ||
3241 left->hasAttr<NSConsumesSelfAttr>()
3242 != right->hasAttr<NSConsumesSelfAttr>()))
3243 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003244
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00003245 ObjCMethodDecl::param_const_iterator
Douglas Gregor0bf70f42012-05-17 23:13:29 +00003246 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
3247 re = right->param_end();
Mike Stump11289f42009-09-09 15:08:12 +00003248
Douglas Gregor0bf70f42012-05-17 23:13:29 +00003249 for (; li != le && ri != re; ++li, ++ri) {
John McCall31168b02011-06-15 23:02:42 +00003250 assert(ri != right->param_end() && "Param mismatch");
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00003251 const ParmVarDecl *lparm = *li, *rparm = *ri;
John McCall31168b02011-06-15 23:02:42 +00003252
3253 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
3254 return false;
3255
David Blaikiebbafb8a2012-03-11 07:00:24 +00003256 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003257 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
3258 return false;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003259 }
3260 return true;
3261}
3262
Manman Ren71224532016-04-09 18:59:48 +00003263static bool isMethodContextSameForKindofLookup(ObjCMethodDecl *Method,
3264 ObjCMethodDecl *MethodInList) {
3265 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3266 auto *MethodInListProtocol =
3267 dyn_cast<ObjCProtocolDecl>(MethodInList->getDeclContext());
3268 // If this method belongs to a protocol but the method in list does not, or
3269 // vice versa, we say the context is not the same.
3270 if ((MethodProtocol && !MethodInListProtocol) ||
3271 (!MethodProtocol && MethodInListProtocol))
3272 return false;
3273
3274 if (MethodProtocol && MethodInListProtocol)
3275 return true;
3276
3277 ObjCInterfaceDecl *MethodInterface = Method->getClassInterface();
3278 ObjCInterfaceDecl *MethodInListInterface =
3279 MethodInList->getClassInterface();
3280 return MethodInterface == MethodInListInterface;
3281}
3282
Nico Weber2e0c8f72014-12-27 03:58:08 +00003283void Sema::addMethodToGlobalList(ObjCMethodList *List,
3284 ObjCMethodDecl *Method) {
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003285 // Record at the head of the list whether there were 0, 1, or >= 2 methods
3286 // inside categories.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003287 if (ObjCCategoryDecl *CD =
3288 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
Argyrios Kyrtzidis04703a62013-04-27 00:10:12 +00003289 if (!CD->IsClassExtension() && List->getBits() < 2)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003290 List->setBits(List->getBits() + 1);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003291
Douglas Gregorc454afe2012-01-25 00:19:56 +00003292 // If the list is empty, make it a singleton list.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003293 if (List->getMethod() == nullptr) {
3294 List->setMethod(Method);
Craig Topperc3ec1492014-05-26 06:22:03 +00003295 List->setNext(nullptr);
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003296 return;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003297 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003298
Douglas Gregorc454afe2012-01-25 00:19:56 +00003299 // We've seen a method with this name, see if we have already seen this type
3300 // signature.
3301 ObjCMethodList *Previous = List;
Manman Ren051d0b62016-04-13 23:43:56 +00003302 ObjCMethodList *ListWithSameDeclaration = nullptr;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003303 for (; List; Previous = List, List = List->getNext()) {
Douglas Gregor600a2f52013-06-21 00:20:25 +00003304 // If we are building a module, keep all of the methods.
Richard Smithbbcc9f02016-08-26 00:14:38 +00003305 if (getLangOpts().isCompilingModule())
Douglas Gregor600a2f52013-06-21 00:20:25 +00003306 continue;
3307
Manman Ren051d0b62016-04-13 23:43:56 +00003308 bool SameDeclaration = MatchTwoMethodDeclarations(Method,
3309 List->getMethod());
Manman Ren71224532016-04-09 18:59:48 +00003310 // Looking for method with a type bound requires the correct context exists.
Manman Ren051d0b62016-04-13 23:43:56 +00003311 // We need to insert a method into the list if the context is different.
3312 // If the method's declaration matches the list
3313 // a> the method belongs to a different context: we need to insert it, in
3314 // order to emit the availability message, we need to prioritize over
3315 // availability among the methods with the same declaration.
3316 // b> the method belongs to the same context: there is no need to insert a
3317 // new entry.
3318 // If the method's declaration does not match the list, we insert it to the
3319 // end.
3320 if (!SameDeclaration ||
Manman Ren71224532016-04-09 18:59:48 +00003321 !isMethodContextSameForKindofLookup(Method, List->getMethod())) {
Fariborz Jahaniand436b2a2015-04-07 16:56:27 +00003322 // Even if two method types do not match, we would like to say
3323 // there is more than one declaration so unavailability/deprecated
3324 // warning is not too noisy.
3325 if (!Method->isDefined())
3326 List->setHasMoreThanOneDecl(true);
Manman Ren051d0b62016-04-13 23:43:56 +00003327
3328 // For methods with the same declaration, the one that is deprecated
3329 // should be put in the front for better diagnostics.
3330 if (Method->isDeprecated() && SameDeclaration &&
3331 !ListWithSameDeclaration && !List->getMethod()->isDeprecated())
3332 ListWithSameDeclaration = List;
3333
3334 if (Method->isUnavailable() && SameDeclaration &&
3335 !ListWithSameDeclaration &&
3336 List->getMethod()->getAvailability() < AR_Deprecated)
3337 ListWithSameDeclaration = List;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003338 continue;
Fariborz Jahaniand436b2a2015-04-07 16:56:27 +00003339 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003340
3341 ObjCMethodDecl *PrevObjCMethod = List->getMethod();
Douglas Gregorc454afe2012-01-25 00:19:56 +00003342
3343 // Propagate the 'defined' bit.
3344 if (Method->isDefined())
3345 PrevObjCMethod->setDefined(true);
Nico Webere3b11042014-12-27 07:09:37 +00003346 else {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003347 // Objective-C doesn't allow an @interface for a class after its
3348 // @implementation. So if Method is not defined and there already is
3349 // an entry for this type signature, Method has to be for a different
3350 // class than PrevObjCMethod.
3351 List->setHasMoreThanOneDecl(true);
3352 }
3353
Douglas Gregorc454afe2012-01-25 00:19:56 +00003354 // If a method is deprecated, push it in the global pool.
3355 // This is used for better diagnostics.
3356 if (Method->isDeprecated()) {
3357 if (!PrevObjCMethod->isDeprecated())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003358 List->setMethod(Method);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003359 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003360 // If the new method is unavailable, push it into global pool
Douglas Gregorc454afe2012-01-25 00:19:56 +00003361 // unless previous one is deprecated.
3362 if (Method->isUnavailable()) {
3363 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003364 List->setMethod(Method);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003365 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003366
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003367 return;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003368 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003369
Douglas Gregorc454afe2012-01-25 00:19:56 +00003370 // We have a new signature for an existing method - add it.
3371 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
Douglas Gregore1716012012-01-25 00:49:42 +00003372 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
Manman Ren71224532016-04-09 18:59:48 +00003373
Manman Ren051d0b62016-04-13 23:43:56 +00003374 // We insert it right before ListWithSameDeclaration.
3375 if (ListWithSameDeclaration) {
3376 auto *List = new (Mem) ObjCMethodList(*ListWithSameDeclaration);
3377 // FIXME: should we clear the other bits in ListWithSameDeclaration?
3378 ListWithSameDeclaration->setMethod(Method);
3379 ListWithSameDeclaration->setNext(List);
Manman Ren71224532016-04-09 18:59:48 +00003380 return;
3381 }
3382
Nico Weber2e0c8f72014-12-27 03:58:08 +00003383 Previous->setNext(new (Mem) ObjCMethodList(Method));
Douglas Gregorc454afe2012-01-25 00:19:56 +00003384}
3385
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003386/// Read the contents of the method pool for a given selector from
Sebastian Redl75d8a322010-08-02 23:18:59 +00003387/// external storage.
Douglas Gregore1716012012-01-25 00:49:42 +00003388void Sema::ReadMethodPool(Selector Sel) {
Douglas Gregorc78d3462009-04-24 21:10:55 +00003389 assert(ExternalSource && "We need an external AST source");
Douglas Gregore1716012012-01-25 00:49:42 +00003390 ExternalSource->ReadMethodPool(Sel);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003391}
3392
Manman Rena0f31a02016-04-29 19:04:05 +00003393void Sema::updateOutOfDateSelector(Selector Sel) {
3394 if (!ExternalSource)
3395 return;
3396 ExternalSource->updateOutOfDateSelector(Sel);
3397}
3398
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003399void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
Sebastian Redl75d8a322010-08-02 23:18:59 +00003400 bool instance) {
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00003401 // Ignore methods of invalid containers.
3402 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003403 return;
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00003404
Douglas Gregor70f449b2012-01-25 00:59:09 +00003405 if (ExternalSource)
3406 ReadMethodPool(Method->getSelector());
Fangrui Song6907ce22018-07-30 19:24:48 +00003407
Sebastian Redl75d8a322010-08-02 23:18:59 +00003408 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
Douglas Gregor70f449b2012-01-25 00:59:09 +00003409 if (Pos == MethodPool.end())
3410 Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
3411 GlobalMethods())).first;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003412
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003413 Method->setDefined(impl);
Fangrui Song6907ce22018-07-30 19:24:48 +00003414
Sebastian Redl75d8a322010-08-02 23:18:59 +00003415 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003416 addMethodToGlobalList(&Entry, Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003417}
3418
John McCall31168b02011-06-15 23:02:42 +00003419/// Determines if this is an "acceptable" loose mismatch in the global
3420/// method pool. This exists mostly as a hack to get around certain
3421/// global mismatches which we can't afford to make warnings / errors.
3422/// Really, what we want is a way to take a method out of the global
3423/// method pool.
3424static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
3425 ObjCMethodDecl *other) {
3426 if (!chosen->isInstanceMethod())
3427 return false;
3428
3429 Selector sel = chosen->getSelector();
3430 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
3431 return false;
3432
3433 // Don't complain about mismatches for -length if the method we
3434 // chose has an integral result type.
Alp Toker314cc812014-01-25 16:55:45 +00003435 return (chosen->getReturnType()->isIntegerType());
John McCall31168b02011-06-15 23:02:42 +00003436}
3437
Manman Ren7ed4f982016-04-07 19:32:24 +00003438/// Return true if the given method is wthin the type bound.
3439static bool FilterMethodsByTypeBound(ObjCMethodDecl *Method,
3440 const ObjCObjectType *TypeBound) {
3441 if (!TypeBound)
3442 return true;
3443
3444 if (TypeBound->isObjCId())
3445 // FIXME: should we handle the case of bounding to id<A, B> differently?
3446 return true;
3447
3448 auto *BoundInterface = TypeBound->getInterface();
3449 assert(BoundInterface && "unexpected object type!");
3450
3451 // Check if the Method belongs to a protocol. We should allow any method
3452 // defined in any protocol, because any subclass could adopt the protocol.
3453 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3454 if (MethodProtocol) {
3455 return true;
3456 }
3457
3458 // If the Method belongs to a class, check if it belongs to the class
3459 // hierarchy of the class bound.
3460 if (ObjCInterfaceDecl *MethodInterface = Method->getClassInterface()) {
3461 // We allow methods declared within classes that are part of the hierarchy
3462 // of the class bound (superclass of, subclass of, or the same as the class
3463 // bound).
3464 return MethodInterface == BoundInterface ||
3465 MethodInterface->isSuperClassOf(BoundInterface) ||
3466 BoundInterface->isSuperClassOf(MethodInterface);
3467 }
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003468 llvm_unreachable("unknown method context");
Manman Ren7ed4f982016-04-07 19:32:24 +00003469}
3470
Manman Rend2a3cd72016-04-07 19:30:20 +00003471/// We first select the type of the method: Instance or Factory, then collect
3472/// all methods with that type.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003473bool Sema::CollectMultipleMethodsInGlobalPool(
Manman Rend2a3cd72016-04-07 19:30:20 +00003474 Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods,
Manman Ren7ed4f982016-04-07 19:32:24 +00003475 bool InstanceFirst, bool CheckTheOther,
3476 const ObjCObjectType *TypeBound) {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003477 if (ExternalSource)
3478 ReadMethodPool(Sel);
3479
3480 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3481 if (Pos == MethodPool.end())
3482 return false;
Manman Rend2a3cd72016-04-07 19:30:20 +00003483
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003484 // Gather the non-hidden methods.
Manman Rend2a3cd72016-04-07 19:30:20 +00003485 ObjCMethodList &MethList = InstanceFirst ? Pos->second.first :
3486 Pos->second.second;
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003487 for (ObjCMethodList *M = &MethList; M; M = M->getNext())
Manman Ren7ed4f982016-04-07 19:32:24 +00003488 if (M->getMethod() && !M->getMethod()->isHidden()) {
3489 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3490 Methods.push_back(M->getMethod());
3491 }
Manman Rend2a3cd72016-04-07 19:30:20 +00003492
3493 // Return if we find any method with the desired kind.
3494 if (!Methods.empty())
3495 return Methods.size() > 1;
3496
3497 if (!CheckTheOther)
3498 return false;
3499
3500 // Gather the other kind.
3501 ObjCMethodList &MethList2 = InstanceFirst ? Pos->second.second :
3502 Pos->second.first;
3503 for (ObjCMethodList *M = &MethList2; M; M = M->getNext())
Manman Ren7ed4f982016-04-07 19:32:24 +00003504 if (M->getMethod() && !M->getMethod()->isHidden()) {
3505 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3506 Methods.push_back(M->getMethod());
3507 }
Manman Rend2a3cd72016-04-07 19:30:20 +00003508
Nico Weber2e0c8f72014-12-27 03:58:08 +00003509 return Methods.size() > 1;
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003510}
3511
Manman Rend2a3cd72016-04-07 19:30:20 +00003512bool Sema::AreMultipleMethodsInGlobalPool(
3513 Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R,
3514 bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl *> &Methods) {
3515 // Diagnose finding more than one method in global pool.
3516 SmallVector<ObjCMethodDecl *, 4> FilteredMethods;
3517 FilteredMethods.push_back(BestMethod);
3518
3519 for (auto *M : Methods)
3520 if (M != BestMethod && !M->hasAttr<UnavailableAttr>())
3521 FilteredMethods.push_back(M);
3522
3523 if (FilteredMethods.size() > 1)
3524 DiagnoseMultipleMethodInGlobalPool(FilteredMethods, Sel, R,
3525 receiverIdOrClass);
3526
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003527 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
Nico Weber2e0c8f72014-12-27 03:58:08 +00003528 // Test for no method in the pool which should not trigger any warning by
3529 // caller.
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003530 if (Pos == MethodPool.end())
3531 return true;
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003532 ObjCMethodList &MethList =
3533 BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003534 return MethList.hasMoreThanOneDecl();
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003535}
3536
Sebastian Redl75d8a322010-08-02 23:18:59 +00003537ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00003538 bool receiverIdOrClass,
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003539 bool instance) {
Douglas Gregor70f449b2012-01-25 00:59:09 +00003540 if (ExternalSource)
3541 ReadMethodPool(Sel);
Fangrui Song6907ce22018-07-30 19:24:48 +00003542
Sebastian Redl75d8a322010-08-02 23:18:59 +00003543 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
Douglas Gregor70f449b2012-01-25 00:59:09 +00003544 if (Pos == MethodPool.end())
Craig Topperc3ec1492014-05-26 06:22:03 +00003545 return nullptr;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003546
Douglas Gregor77f49a42013-01-16 18:47:38 +00003547 // Gather the non-hidden methods.
Sebastian Redl75d8a322010-08-02 23:18:59 +00003548 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00003549 SmallVector<ObjCMethodDecl *, 4> Methods;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003550 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003551 if (M->getMethod() && !M->getMethod()->isHidden())
3552 return M->getMethod();
Douglas Gregorc78d3462009-04-24 21:10:55 +00003553 }
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003554 return nullptr;
3555}
Douglas Gregor77f49a42013-01-16 18:47:38 +00003556
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003557void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3558 Selector Sel, SourceRange R,
3559 bool receiverIdOrClass) {
Douglas Gregor77f49a42013-01-16 18:47:38 +00003560 // We found multiple methods, so we may have to complain.
3561 bool issueDiagnostic = false, issueError = false;
Jonathan Roelofs74411362015-04-28 18:04:44 +00003562
Douglas Gregor77f49a42013-01-16 18:47:38 +00003563 // We support a warning which complains about *any* difference in
3564 // method signature.
3565 bool strictSelectorMatch =
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003566 receiverIdOrClass &&
3567 !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
Douglas Gregor77f49a42013-01-16 18:47:38 +00003568 if (strictSelectorMatch) {
3569 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3570 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
3571 issueDiagnostic = true;
3572 break;
3573 }
3574 }
3575 }
Jonathan Roelofs74411362015-04-28 18:04:44 +00003576
Douglas Gregor77f49a42013-01-16 18:47:38 +00003577 // If we didn't see any strict differences, we won't see any loose
3578 // differences. In ARC, however, we also need to check for loose
3579 // mismatches, because most of them are errors.
3580 if (!strictSelectorMatch ||
3581 (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
3582 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3583 // This checks if the methods differ in type mismatch.
3584 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
3585 !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
3586 issueDiagnostic = true;
3587 if (getLangOpts().ObjCAutoRefCount)
3588 issueError = true;
3589 break;
3590 }
3591 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003592
Douglas Gregor77f49a42013-01-16 18:47:38 +00003593 if (issueDiagnostic) {
3594 if (issueError)
3595 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
3596 else if (strictSelectorMatch)
3597 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
3598 else
3599 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
Fangrui Song6907ce22018-07-30 19:24:48 +00003600
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003601 Diag(Methods[0]->getBeginLoc(),
Douglas Gregor77f49a42013-01-16 18:47:38 +00003602 issueError ? diag::note_possibility : diag::note_using)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003603 << Methods[0]->getSourceRange();
Douglas Gregor77f49a42013-01-16 18:47:38 +00003604 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003605 Diag(Methods[I]->getBeginLoc(), diag::note_also_found)
3606 << Methods[I]->getSourceRange();
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003607 }
Douglas Gregor77f49a42013-01-16 18:47:38 +00003608 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003609}
3610
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003611ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
Sebastian Redl75d8a322010-08-02 23:18:59 +00003612 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3613 if (Pos == MethodPool.end())
Craig Topperc3ec1492014-05-26 06:22:03 +00003614 return nullptr;
Sebastian Redl75d8a322010-08-02 23:18:59 +00003615
3616 GlobalMethods &Methods = Pos->second;
Fariborz Jahanianec762bd2014-03-26 20:59:26 +00003617 for (const ObjCMethodList *Method = &Methods.first; Method;
3618 Method = Method->getNext())
Fariborz Jahanian4019c7f2015-02-19 21:52:41 +00003619 if (Method->getMethod() &&
3620 (Method->getMethod()->isDefined() ||
3621 Method->getMethod()->isPropertyAccessor()))
Nico Weber2e0c8f72014-12-27 03:58:08 +00003622 return Method->getMethod();
Fangrui Song6907ce22018-07-30 19:24:48 +00003623
Fariborz Jahanianec762bd2014-03-26 20:59:26 +00003624 for (const ObjCMethodList *Method = &Methods.second; Method;
3625 Method = Method->getNext())
Fariborz Jahanian4019c7f2015-02-19 21:52:41 +00003626 if (Method->getMethod() &&
3627 (Method->getMethod()->isDefined() ||
3628 Method->getMethod()->isPropertyAccessor()))
Nico Weber2e0c8f72014-12-27 03:58:08 +00003629 return Method->getMethod();
Craig Topperc3ec1492014-05-26 06:22:03 +00003630 return nullptr;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003631}
3632
Fariborz Jahanian42f89382013-05-30 21:48:58 +00003633static void
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003634HelperSelectorsForTypoCorrection(
3635 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
3636 StringRef Typo, const ObjCMethodDecl * Method) {
3637 const unsigned MaxEditDistance = 1;
3638 unsigned BestEditDistance = MaxEditDistance + 1;
Richard Trieuea8d3702013-06-06 02:22:29 +00003639 std::string MethodName = Method->getSelector().getAsString();
Fangrui Song6907ce22018-07-30 19:24:48 +00003640
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003641 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
3642 if (MinPossibleEditDistance > 0 &&
3643 Typo.size() / MinPossibleEditDistance < 1)
3644 return;
3645 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
3646 if (EditDistance > MaxEditDistance)
3647 return;
3648 if (EditDistance == BestEditDistance)
3649 BestMethod.push_back(Method);
3650 else if (EditDistance < BestEditDistance) {
3651 BestMethod.clear();
3652 BestMethod.push_back(Method);
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003653 }
3654}
3655
Fariborz Jahanian75481672013-06-17 17:10:54 +00003656static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
3657 QualType ObjectType) {
3658 if (ObjectType.isNull())
3659 return true;
3660 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
3661 return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003662 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
3663 nullptr;
Fariborz Jahanian75481672013-06-17 17:10:54 +00003664}
3665
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003666const ObjCMethodDecl *
Fariborz Jahanian75481672013-06-17 17:10:54 +00003667Sema::SelectorsForTypoCorrection(Selector Sel,
3668 QualType ObjectType) {
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003669 unsigned NumArgs = Sel.getNumArgs();
3670 SmallVector<const ObjCMethodDecl *, 8> Methods;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003671 bool ObjectIsId = true, ObjectIsClass = true;
3672 if (ObjectType.isNull())
3673 ObjectIsId = ObjectIsClass = false;
3674 else if (!ObjectType->isObjCObjectPointerType())
Craig Topperc3ec1492014-05-26 06:22:03 +00003675 return nullptr;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003676 else if (const ObjCObjectPointerType *ObjCPtr =
3677 ObjectType->getAsObjCInterfacePointerType()) {
3678 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
3679 ObjectIsId = ObjectIsClass = false;
3680 }
3681 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
3682 ObjectIsClass = false;
3683 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
3684 ObjectIsId = false;
3685 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003686 return nullptr;
3687
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003688 for (GlobalMethodPool::iterator b = MethodPool.begin(),
3689 e = MethodPool.end(); b != e; b++) {
3690 // instance methods
3691 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003692 if (M->getMethod() &&
3693 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3694 (M->getMethod()->getSelector() != Sel)) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003695 if (ObjectIsId)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003696 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003697 else if (!ObjectIsClass &&
Nico Weber2e0c8f72014-12-27 03:58:08 +00003698 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3699 ObjectType))
3700 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003701 }
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003702 // class methods
3703 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003704 if (M->getMethod() &&
3705 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3706 (M->getMethod()->getSelector() != Sel)) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003707 if (ObjectIsClass)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003708 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003709 else if (!ObjectIsId &&
Nico Weber2e0c8f72014-12-27 03:58:08 +00003710 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3711 ObjectType))
3712 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003713 }
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003714 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003715
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003716 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
3717 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
3718 HelperSelectorsForTypoCorrection(SelectedMethods,
3719 Sel.getAsString(), Methods[i]);
3720 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003721 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003722}
3723
Fariborz Jahanian42f89382013-05-30 21:48:58 +00003724/// DiagnoseDuplicateIvars -
Fangrui Song6907ce22018-07-30 19:24:48 +00003725/// Check for duplicate ivars in the entire class at the start of
James Dennett634962f2012-06-14 21:40:34 +00003726/// \@implementation. This becomes necesssary because class extension can
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003727/// add ivars to a class in random order which will not be known until
James Dennett634962f2012-06-14 21:40:34 +00003728/// class's \@implementation is seen.
Fangrui Song6907ce22018-07-30 19:24:48 +00003729void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003730 ObjCInterfaceDecl *SID) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00003731 for (auto *Ivar : ID->ivars()) {
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003732 if (Ivar->isInvalidDecl())
3733 continue;
3734 if (IdentifierInfo *II = Ivar->getIdentifier()) {
3735 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
3736 if (prevIvar) {
3737 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3738 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
3739 Ivar->setInvalidDecl();
3740 }
3741 }
3742 }
3743}
3744
John McCallb61e14e2015-10-27 04:54:50 +00003745/// Diagnose attempts to define ARC-__weak ivars when __weak is disabled.
3746static void DiagnoseWeakIvars(Sema &S, ObjCImplementationDecl *ID) {
3747 if (S.getLangOpts().ObjCWeak) return;
3748
3749 for (auto ivar = ID->getClassInterface()->all_declared_ivar_begin();
3750 ivar; ivar = ivar->getNextIvar()) {
3751 if (ivar->isInvalidDecl()) continue;
3752 if (ivar->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
3753 if (S.getLangOpts().ObjCWeakRuntime) {
3754 S.Diag(ivar->getLocation(), diag::err_arc_weak_disabled);
3755 } else {
3756 S.Diag(ivar->getLocation(), diag::err_arc_weak_no_runtime);
3757 }
3758 }
3759 }
3760}
3761
Volodymyr Sapsai30680e92017-10-23 22:01:41 +00003762/// Diagnose attempts to use flexible array member with retainable object type.
3763static void DiagnoseRetainableFlexibleArrayMember(Sema &S,
3764 ObjCInterfaceDecl *ID) {
3765 if (!S.getLangOpts().ObjCAutoRefCount)
3766 return;
3767
3768 for (auto ivar = ID->all_declared_ivar_begin(); ivar;
3769 ivar = ivar->getNextIvar()) {
3770 if (ivar->isInvalidDecl())
3771 continue;
3772 QualType IvarTy = ivar->getType();
3773 if (IvarTy->isIncompleteArrayType() &&
3774 (IvarTy.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) &&
3775 IvarTy->isObjCLifetimeType()) {
3776 S.Diag(ivar->getLocation(), diag::err_flexible_array_arc_retainable);
3777 ivar->setInvalidDecl();
3778 }
3779 }
3780}
3781
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003782Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
3783 switch (CurContext->getDeclKind()) {
3784 case Decl::ObjCInterface:
3785 return Sema::OCK_Interface;
3786 case Decl::ObjCProtocol:
3787 return Sema::OCK_Protocol;
3788 case Decl::ObjCCategory:
Benjamin Kramera008d3a2015-04-10 11:37:55 +00003789 if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003790 return Sema::OCK_ClassExtension;
Benjamin Kramera008d3a2015-04-10 11:37:55 +00003791 return Sema::OCK_Category;
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003792 case Decl::ObjCImplementation:
3793 return Sema::OCK_Implementation;
3794 case Decl::ObjCCategoryImpl:
3795 return Sema::OCK_CategoryImplementation;
3796
3797 default:
3798 return Sema::OCK_None;
3799 }
3800}
3801
Volodymyr Sapsai30680e92017-10-23 22:01:41 +00003802static bool IsVariableSizedType(QualType T) {
3803 if (T->isIncompleteArrayType())
3804 return true;
3805 const auto *RecordTy = T->getAs<RecordType>();
3806 return (RecordTy && RecordTy->getDecl()->hasFlexibleArrayMember());
3807}
3808
3809static void DiagnoseVariableSizedIvars(Sema &S, ObjCContainerDecl *OCD) {
3810 ObjCInterfaceDecl *IntfDecl = nullptr;
3811 ObjCInterfaceDecl::ivar_range Ivars = llvm::make_range(
3812 ObjCInterfaceDecl::ivar_iterator(), ObjCInterfaceDecl::ivar_iterator());
3813 if ((IntfDecl = dyn_cast<ObjCInterfaceDecl>(OCD))) {
3814 Ivars = IntfDecl->ivars();
3815 } else if (auto *ImplDecl = dyn_cast<ObjCImplementationDecl>(OCD)) {
3816 IntfDecl = ImplDecl->getClassInterface();
3817 Ivars = ImplDecl->ivars();
3818 } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(OCD)) {
3819 if (CategoryDecl->IsClassExtension()) {
3820 IntfDecl = CategoryDecl->getClassInterface();
3821 Ivars = CategoryDecl->ivars();
3822 }
3823 }
3824
3825 // Check if variable sized ivar is in interface and visible to subclasses.
3826 if (!isa<ObjCInterfaceDecl>(OCD)) {
3827 for (auto ivar : Ivars) {
3828 if (!ivar->isInvalidDecl() && IsVariableSizedType(ivar->getType())) {
3829 S.Diag(ivar->getLocation(), diag::warn_variable_sized_ivar_visibility)
3830 << ivar->getDeclName() << ivar->getType();
3831 }
3832 }
3833 }
3834
3835 // Subsequent checks require interface decl.
3836 if (!IntfDecl)
3837 return;
3838
3839 // Check if variable sized ivar is followed by another ivar.
3840 for (ObjCIvarDecl *ivar = IntfDecl->all_declared_ivar_begin(); ivar;
3841 ivar = ivar->getNextIvar()) {
3842 if (ivar->isInvalidDecl() || !ivar->getNextIvar())
3843 continue;
3844 QualType IvarTy = ivar->getType();
3845 bool IsInvalidIvar = false;
3846 if (IvarTy->isIncompleteArrayType()) {
3847 S.Diag(ivar->getLocation(), diag::err_flexible_array_not_at_end)
3848 << ivar->getDeclName() << IvarTy
3849 << TTK_Class; // Use "class" for Obj-C.
3850 IsInvalidIvar = true;
3851 } else if (const RecordType *RecordTy = IvarTy->getAs<RecordType>()) {
3852 if (RecordTy->getDecl()->hasFlexibleArrayMember()) {
3853 S.Diag(ivar->getLocation(),
3854 diag::err_objc_variable_sized_type_not_at_end)
3855 << ivar->getDeclName() << IvarTy;
3856 IsInvalidIvar = true;
3857 }
3858 }
3859 if (IsInvalidIvar) {
3860 S.Diag(ivar->getNextIvar()->getLocation(),
3861 diag::note_next_ivar_declaration)
3862 << ivar->getNextIvar()->getSynthesize();
3863 ivar->setInvalidDecl();
3864 }
3865 }
3866
3867 // Check if ObjC container adds ivars after variable sized ivar in superclass.
3868 // Perform the check only if OCD is the first container to declare ivars to
3869 // avoid multiple warnings for the same ivar.
3870 ObjCIvarDecl *FirstIvar =
3871 (Ivars.begin() == Ivars.end()) ? nullptr : *Ivars.begin();
3872 if (FirstIvar && (FirstIvar == IntfDecl->all_declared_ivar_begin())) {
3873 const ObjCInterfaceDecl *SuperClass = IntfDecl->getSuperClass();
3874 while (SuperClass && SuperClass->ivar_empty())
3875 SuperClass = SuperClass->getSuperClass();
3876 if (SuperClass) {
3877 auto IvarIter = SuperClass->ivar_begin();
3878 std::advance(IvarIter, SuperClass->ivar_size() - 1);
3879 const ObjCIvarDecl *LastIvar = *IvarIter;
3880 if (IsVariableSizedType(LastIvar->getType())) {
3881 S.Diag(FirstIvar->getLocation(),
3882 diag::warn_superclass_variable_sized_type_not_at_end)
3883 << FirstIvar->getDeclName() << LastIvar->getDeclName()
3884 << LastIvar->getType() << SuperClass->getDeclName();
3885 S.Diag(LastIvar->getLocation(), diag::note_entity_declared_at)
3886 << LastIvar->getDeclName();
3887 }
3888 }
3889 }
3890}
3891
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003892// Note: For class/category implementations, allMethods is always null.
Robert Wilhelm57c67112013-07-17 21:14:35 +00003893Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
Fariborz Jahaniandfb76872013-07-17 00:05:08 +00003894 ArrayRef<DeclGroupPtrTy> allTUVars) {
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003895 if (getObjCContainerKind() == Sema::OCK_None)
Craig Topperc3ec1492014-05-26 06:22:03 +00003896 return nullptr;
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003897
3898 assert(AtEnd.isValid() && "Invalid location for '@end'");
3899
George Burgess IV00f70bd2018-03-01 05:43:23 +00003900 auto *OCD = cast<ObjCContainerDecl>(CurContext);
3901 Decl *ClassDecl = OCD;
3902
Mike Stump11289f42009-09-09 15:08:12 +00003903 bool isInterfaceDeclKind =
Chris Lattner219b3e92008-03-16 21:17:37 +00003904 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
3905 || isa<ObjCProtocolDecl>(ClassDecl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003906 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
Steve Naroffb3a87982009-01-09 15:36:25 +00003907
Steve Naroff35c62ae2009-01-08 17:28:14 +00003908 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
3909 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
3910 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
3911
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003912 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003913 ObjCMethodDecl *Method =
John McCall48871652010-08-21 09:40:31 +00003914 cast_or_null<ObjCMethodDecl>(allMethods[i]);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003915
3916 if (!Method) continue; // Already issued a diagnostic.
Douglas Gregorffca3a22009-01-09 17:18:27 +00003917 if (Method->isInstanceMethod()) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00003918 /// Check for instance method of the same name with incompatible types
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003919 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
Mike Stump11289f42009-09-09 15:08:12 +00003920 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
Chris Lattnerda463fe2007-12-12 07:09:47 +00003921 : false;
Mike Stump11289f42009-09-09 15:08:12 +00003922 if ((isInterfaceDeclKind && PrevMethod && !match)
Eli Friedman42b1e9e2008-12-16 20:15:50 +00003923 || (checkIdenticalMethods && match)) {
Chris Lattner0369c572008-11-23 23:12:31 +00003924 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00003925 << Method->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003926 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Douglas Gregor87e92752010-12-21 17:34:17 +00003927 Method->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00003928 } else {
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003929 if (PrevMethod) {
Argyrios Kyrtzidisdcaaa212011-10-14 08:02:31 +00003930 Method->setAsRedeclaration(PrevMethod);
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003931 if (!Context.getSourceManager().isInSystemHeader(
3932 Method->getLocation()))
3933 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3934 << Method->getDeclName();
3935 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3936 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003937 InsMap[Method->getSelector()] = Method;
3938 /// The following allows us to typecheck messages to "id".
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003939 AddInstanceMethodToGlobalPool(Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003940 }
Mike Stump12b8ce12009-08-04 21:02:39 +00003941 } else {
Chris Lattnerda463fe2007-12-12 07:09:47 +00003942 /// Check for class method of the same name with incompatible types
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003943 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
Mike Stump11289f42009-09-09 15:08:12 +00003944 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
Chris Lattnerda463fe2007-12-12 07:09:47 +00003945 : false;
Mike Stump11289f42009-09-09 15:08:12 +00003946 if ((isInterfaceDeclKind && PrevMethod && !match)
Eli Friedman42b1e9e2008-12-16 20:15:50 +00003947 || (checkIdenticalMethods && match)) {
Chris Lattner0369c572008-11-23 23:12:31 +00003948 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00003949 << Method->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003950 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Douglas Gregor87e92752010-12-21 17:34:17 +00003951 Method->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00003952 } else {
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003953 if (PrevMethod) {
Argyrios Kyrtzidisdcaaa212011-10-14 08:02:31 +00003954 Method->setAsRedeclaration(PrevMethod);
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003955 if (!Context.getSourceManager().isInSystemHeader(
3956 Method->getLocation()))
3957 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3958 << Method->getDeclName();
3959 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3960 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003961 ClsMap[Method->getSelector()] = Method;
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003962 AddFactoryMethodToGlobalPool(Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003963 }
3964 }
3965 }
Douglas Gregorb8982092013-01-21 19:42:21 +00003966 if (isa<ObjCInterfaceDecl>(ClassDecl)) {
3967 // Nothing to do here.
Steve Naroffb3a87982009-01-09 15:36:25 +00003968 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
Fariborz Jahanian62293f42008-12-06 19:59:02 +00003969 // Categories are used to extend the class by declaring new methods.
Mike Stump11289f42009-09-09 15:08:12 +00003970 // By the same token, they are also used to add new properties. No
Fariborz Jahanian62293f42008-12-06 19:59:02 +00003971 // need to compare the added property to those in the class.
Daniel Dunbar4684f372008-08-27 05:40:03 +00003972
Fariborz Jahanianc21f5432010-12-10 23:36:33 +00003973 if (C->IsClassExtension()) {
3974 ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
3975 DiagnoseClassExtensionDupMethods(C, CCPrimary);
Fariborz Jahanianc21f5432010-12-10 23:36:33 +00003976 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003977 }
Steve Naroffb3a87982009-01-09 15:36:25 +00003978 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
Fariborz Jahanian30a42922010-02-15 21:55:26 +00003979 if (CDecl->getIdentifier())
3980 // ProcessPropertyDecl is responsible for diagnosing conflicts with any
3981 // user-defined setter/getter. It also synthesizes setter/getter methods
3982 // and adds them to the DeclContext and global method pools.
Manman Renefe1bac2016-01-27 20:00:32 +00003983 for (auto *I : CDecl->properties())
Douglas Gregore17765e2015-11-03 17:02:34 +00003984 ProcessPropertyDecl(I);
Ted Kremenekc7c64312010-01-07 01:20:12 +00003985 CDecl->setAtEndRange(AtEnd);
Steve Naroffb3a87982009-01-09 15:36:25 +00003986 }
3987 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
Ted Kremenekc7c64312010-01-07 01:20:12 +00003988 IC->setAtEndRange(AtEnd);
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00003989 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003990 // Any property declared in a class extension might have user
3991 // declared setter or getter in current class extension or one
3992 // of the other class extensions. Mark them as synthesized as
3993 // property will be synthesized when property with same name is
3994 // seen in the @implementation.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00003995 for (const auto *Ext : IDecl->visible_extensions()) {
Manman Rena7a8b1f2016-01-26 18:05:23 +00003996 for (const auto *Property : Ext->instance_properties()) {
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003997 // Skip over properties declared @dynamic
3998 if (const ObjCPropertyImplDecl *PIDecl
Manman Ren5b786402016-01-28 18:49:28 +00003999 = IC->FindPropertyImplDecl(Property->getIdentifier(),
4000 Property->getQueryKind()))
Fangrui Song6907ce22018-07-30 19:24:48 +00004001 if (PIDecl->getPropertyImplementation()
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00004002 == ObjCPropertyImplDecl::Dynamic)
4003 continue;
Douglas Gregor048fbfa2013-01-16 23:00:23 +00004004
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00004005 for (const auto *Ext : IDecl->visible_extensions()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00004006 if (ObjCMethodDecl *GetterMethod
4007 = Ext->getInstanceMethod(Property->getGetterName()))
Jordan Rosed01e83a2012-10-10 16:42:25 +00004008 GetterMethod->setPropertyAccessor(true);
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00004009 if (!Property->isReadOnly())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00004010 if (ObjCMethodDecl *SetterMethod
4011 = Ext->getInstanceMethod(Property->getSetterName()))
Jordan Rosed01e83a2012-10-10 16:42:25 +00004012 SetterMethod->setPropertyAccessor(true);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00004013 }
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00004014 }
4015 }
Fariborz Jahanian25491a22010-05-05 21:52:17 +00004016 ImplMethodsVsClassMethods(S, IC, IDecl);
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00004017 AtomicPropertySetterGetterRules(IC, IDecl);
John McCall31168b02011-06-15 23:02:42 +00004018 DiagnoseOwningPropertyGetterSynthesis(IC);
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004019 DiagnoseUnusedBackingIvarInAccessor(S, IC);
Fariborz Jahanian20cfff32015-03-11 16:59:48 +00004020 if (IDecl->hasDesignatedInitializers())
4021 DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
John McCallb61e14e2015-10-27 04:54:50 +00004022 DiagnoseWeakIvars(*this, IC);
Volodymyr Sapsai30680e92017-10-23 22:01:41 +00004023 DiagnoseRetainableFlexibleArrayMember(*this, IDecl);
Argyrios Kyrtzidisdb5ce0f2013-12-03 21:11:54 +00004024
Patrick Beardacfbe9e2012-04-06 18:12:22 +00004025 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
Craig Topperc3ec1492014-05-26 06:22:03 +00004026 if (IDecl->getSuperClass() == nullptr) {
Patrick Beardacfbe9e2012-04-06 18:12:22 +00004027 // This class has no superclass, so check that it has been marked with
4028 // __attribute((objc_root_class)).
4029 if (!HasRootClassAttr) {
4030 SourceLocation DeclLoc(IDecl->getLocation());
Alp Tokerb6cc5922014-05-03 03:45:55 +00004031 SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
Patrick Beardacfbe9e2012-04-06 18:12:22 +00004032 Diag(DeclLoc, diag::warn_objc_root_class_missing)
4033 << IDecl->getIdentifier();
4034 // See if NSObject is in the current scope, and if it is, suggest
4035 // adding " : NSObject " to the class declaration.
4036 NamedDecl *IF = LookupSingleName(TUScope,
4037 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
4038 DeclLoc, LookupOrdinaryName);
4039 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
4040 if (NSObjectDecl && NSObjectDecl->getDefinition()) {
4041 Diag(SuperClassLoc, diag::note_objc_needs_superclass)
4042 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
4043 } else {
4044 Diag(SuperClassLoc, diag::note_objc_needs_superclass);
4045 }
4046 }
4047 } else if (HasRootClassAttr) {
4048 // Complain that only root classes may have this attribute.
4049 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
4050 }
4051
Alex Lorenza8c44ba2016-10-28 10:25:10 +00004052 if (const ObjCInterfaceDecl *Super = IDecl->getSuperClass()) {
4053 // An interface can subclass another interface with a
4054 // objc_subclassing_restricted attribute when it has that attribute as
4055 // well (because of interfaces imported from Swift). Therefore we have
4056 // to check if we can subclass in the implementation as well.
4057 if (IDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
4058 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
4059 Diag(IC->getLocation(), diag::err_restricted_superclass_mismatch);
4060 Diag(Super->getLocation(), diag::note_class_declared);
4061 }
4062 }
4063
John McCall2c91c3b2019-05-30 04:09:01 +00004064 if (IDecl->hasAttr<ObjCClassStubAttr>())
4065 Diag(IC->getLocation(), diag::err_implementation_of_class_stub);
4066
John McCall5fb5df92012-06-20 06:18:46 +00004067 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian545643c2010-02-23 23:41:11 +00004068 while (IDecl->getSuperClass()) {
4069 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
4070 IDecl = IDecl->getSuperClass();
4071 }
Patrick Beardacfbe9e2012-04-06 18:12:22 +00004072 }
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00004073 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004074 SetIvarInitializers(IC);
Mike Stump11289f42009-09-09 15:08:12 +00004075 } else if (ObjCCategoryImplDecl* CatImplClass =
Steve Naroffb3a87982009-01-09 15:36:25 +00004076 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
Ted Kremenekc7c64312010-01-07 01:20:12 +00004077 CatImplClass->setAtEndRange(AtEnd);
Mike Stump11289f42009-09-09 15:08:12 +00004078
Chris Lattnerda463fe2007-12-12 07:09:47 +00004079 // Find category interface decl and then check that all methods declared
Daniel Dunbar4684f372008-08-27 05:40:03 +00004080 // in this interface are implemented in the category @implementation.
Chris Lattner41fd42e2009-02-16 18:32:47 +00004081 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00004082 if (ObjCCategoryDecl *Cat
4083 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
4084 ImplMethodsVsClassMethods(S, CatImplClass, Cat);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004085 }
4086 }
Alex Lorenza8c44ba2016-10-28 10:25:10 +00004087 } else if (const auto *IntfDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
4088 if (const ObjCInterfaceDecl *Super = IntfDecl->getSuperClass()) {
4089 if (!IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
4090 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
4091 Diag(IntfDecl->getLocation(), diag::err_restricted_superclass_mismatch);
4092 Diag(Super->getLocation(), diag::note_class_declared);
4093 }
4094 }
John McCall2c91c3b2019-05-30 04:09:01 +00004095
4096 if (IntfDecl->hasAttr<ObjCClassStubAttr>() &&
4097 !IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>())
4098 Diag(IntfDecl->getLocation(), diag::err_class_stub_subclassing_mismatch);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004099 }
Volodymyr Sapsai30680e92017-10-23 22:01:41 +00004100 DiagnoseVariableSizedIvars(*this, OCD);
Chris Lattner5bbb3c82009-03-29 16:50:03 +00004101 if (isInterfaceDeclKind) {
4102 // Reject invalid vardecls.
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00004103 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00004104 DeclGroupRef DG = allTUVars[i].get();
Chris Lattner5bbb3c82009-03-29 16:50:03 +00004105 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
4106 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
Daniel Dunbar0ca16602009-04-14 02:25:56 +00004107 if (!VDecl->hasExternalStorage())
Steve Naroff42959b22009-04-13 17:58:46 +00004108 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
Fariborz Jahanian629aed92009-03-21 18:06:45 +00004109 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00004110 }
Fariborz Jahanian3654e652009-03-18 22:33:24 +00004111 }
Fariborz Jahanian4327b322011-08-29 17:33:12 +00004112 ActOnObjCContainerFinishDefinition();
Argyrios Kyrtzidisbd8b1502011-10-17 19:48:13 +00004113
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00004114 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00004115 DeclGroupRef DG = allTUVars[i].get();
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004116 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
4117 (*I)->setTopLevelDeclInObjCContainer();
Argyrios Kyrtzidisbd8b1502011-10-17 19:48:13 +00004118 Consumer.HandleTopLevelDeclInObjCContainer(DG);
4119 }
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00004120
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +00004121 ActOnDocumentableDecl(ClassDecl);
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00004122 return ClassDecl;
Chris Lattnerda463fe2007-12-12 07:09:47 +00004123}
4124
Chris Lattnerda463fe2007-12-12 07:09:47 +00004125/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
4126/// objective-c's type qualifier from the parser version of the same info.
Mike Stump11289f42009-09-09 15:08:12 +00004127static Decl::ObjCDeclQualifier
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004128CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
John McCallca872902011-05-01 03:04:29 +00004129 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
Chris Lattnerda463fe2007-12-12 07:09:47 +00004130}
4131
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004132/// Check whether the declared result type of the given Objective-C
Douglas Gregor33823722011-06-11 01:09:30 +00004133/// method declaration is compatible with the method's class.
4134///
Fangrui Song6907ce22018-07-30 19:24:48 +00004135static Sema::ResultTypeCompatibilityKind
Douglas Gregor33823722011-06-11 01:09:30 +00004136CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
4137 ObjCInterfaceDecl *CurrentClass) {
Alp Toker314cc812014-01-25 16:55:45 +00004138 QualType ResultType = Method->getReturnType();
4139
Fangrui Song6907ce22018-07-30 19:24:48 +00004140 // If an Objective-C method inherits its related result type, then its
Douglas Gregor33823722011-06-11 01:09:30 +00004141 // declared result type must be compatible with its own class type. The
4142 // declared result type is compatible if:
4143 if (const ObjCObjectPointerType *ResultObjectType
4144 = ResultType->getAs<ObjCObjectPointerType>()) {
4145 // - it is id or qualified id, or
4146 if (ResultObjectType->isObjCIdType() ||
4147 ResultObjectType->isObjCQualifiedIdType())
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004148 return Sema::RTC_Compatible;
Fangrui Song6907ce22018-07-30 19:24:48 +00004149
Douglas Gregor33823722011-06-11 01:09:30 +00004150 if (CurrentClass) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004151 if (ObjCInterfaceDecl *ResultClass
Douglas Gregor33823722011-06-11 01:09:30 +00004152 = ResultObjectType->getInterfaceDecl()) {
4153 // - it is the same as the method's class type, or
Douglas Gregor0b144e12011-12-15 00:29:59 +00004154 if (declaresSameEntity(CurrentClass, ResultClass))
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004155 return Sema::RTC_Compatible;
Fangrui Song6907ce22018-07-30 19:24:48 +00004156
Douglas Gregor33823722011-06-11 01:09:30 +00004157 // - it is a superclass of the method's class type
4158 if (ResultClass->isSuperClassOf(CurrentClass))
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004159 return Sema::RTC_Compatible;
Fangrui Song6907ce22018-07-30 19:24:48 +00004160 }
Douglas Gregorbab8a962011-09-08 01:46:34 +00004161 } else {
4162 // Any Objective-C pointer type might be acceptable for a protocol
4163 // method; we just don't know.
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004164 return Sema::RTC_Unknown;
Douglas Gregor33823722011-06-11 01:09:30 +00004165 }
4166 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004167
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004168 return Sema::RTC_Incompatible;
Douglas Gregor33823722011-06-11 01:09:30 +00004169}
4170
John McCalld2930c22011-07-22 02:45:48 +00004171namespace {
4172/// A helper class for searching for methods which a particular method
4173/// overrides.
4174class OverrideSearch {
Daniel Dunbard6d74c32012-02-29 03:04:05 +00004175public:
Matt Davis55043e22019-04-22 16:04:44 +00004176 const ObjCMethodDecl *Method;
Akira Hatanaka4c687f32018-02-06 23:44:40 +00004177 llvm::SmallSetVector<ObjCMethodDecl*, 4> Overridden;
John McCalld2930c22011-07-22 02:45:48 +00004178 bool Recursive;
4179
4180public:
Matt Davis55043e22019-04-22 16:04:44 +00004181 OverrideSearch(Sema &S, const ObjCMethodDecl *method) : Method(method) {
John McCalld2930c22011-07-22 02:45:48 +00004182 Selector selector = method->getSelector();
4183
4184 // Bypass this search if we've never seen an instance/class method
4185 // with this selector before.
4186 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
4187 if (it == S.MethodPool.end()) {
Axel Naumanndd433f02012-10-18 19:05:02 +00004188 if (!S.getExternalSource()) return;
Douglas Gregore1716012012-01-25 00:49:42 +00004189 S.ReadMethodPool(selector);
Fangrui Song6907ce22018-07-30 19:24:48 +00004190
Douglas Gregore1716012012-01-25 00:49:42 +00004191 it = S.MethodPool.find(selector);
4192 if (it == S.MethodPool.end())
4193 return;
John McCalld2930c22011-07-22 02:45:48 +00004194 }
Matt Davis55043e22019-04-22 16:04:44 +00004195 const ObjCMethodList &list =
John McCalld2930c22011-07-22 02:45:48 +00004196 method->isInstanceMethod() ? it->second.first : it->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00004197 if (!list.getMethod()) return;
John McCalld2930c22011-07-22 02:45:48 +00004198
Matt Davis55043e22019-04-22 16:04:44 +00004199 const ObjCContainerDecl *container
John McCalld2930c22011-07-22 02:45:48 +00004200 = cast<ObjCContainerDecl>(method->getDeclContext());
4201
4202 // Prevent the search from reaching this container again. This is
4203 // important with categories, which override methods from the
4204 // interface and each other.
Matt Davis55043e22019-04-22 16:04:44 +00004205 if (const ObjCCategoryDecl *Category =
4206 dyn_cast<ObjCCategoryDecl>(container)) {
Douglas Gregorcf4ac442012-05-03 21:25:24 +00004207 searchFromContainer(container);
Matt Davis55043e22019-04-22 16:04:44 +00004208 if (const ObjCInterfaceDecl *Interface = Category->getClassInterface())
Douglas Gregorc5928af2012-05-17 22:39:14 +00004209 searchFromContainer(Interface);
Douglas Gregorcf4ac442012-05-03 21:25:24 +00004210 } else {
4211 searchFromContainer(container);
4212 }
Douglas Gregor33823722011-06-11 01:09:30 +00004213 }
John McCalld2930c22011-07-22 02:45:48 +00004214
Akira Hatanaka4c687f32018-02-06 23:44:40 +00004215 typedef decltype(Overridden)::iterator iterator;
John McCalld2930c22011-07-22 02:45:48 +00004216 iterator begin() const { return Overridden.begin(); }
4217 iterator end() const { return Overridden.end(); }
4218
4219private:
Matt Davis55043e22019-04-22 16:04:44 +00004220 void searchFromContainer(const ObjCContainerDecl *container) {
John McCalld2930c22011-07-22 02:45:48 +00004221 if (container->isInvalidDecl()) return;
4222
4223 switch (container->getDeclKind()) {
4224#define OBJCCONTAINER(type, base) \
4225 case Decl::type: \
4226 searchFrom(cast<type##Decl>(container)); \
4227 break;
4228#define ABSTRACT_DECL(expansion)
4229#define DECL(type, base) \
4230 case Decl::type:
4231#include "clang/AST/DeclNodes.inc"
4232 llvm_unreachable("not an ObjC container!");
4233 }
4234 }
4235
Matt Davis55043e22019-04-22 16:04:44 +00004236 void searchFrom(const ObjCProtocolDecl *protocol) {
Douglas Gregore6e48b12012-01-01 19:29:29 +00004237 if (!protocol->hasDefinition())
4238 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00004239
John McCalld2930c22011-07-22 02:45:48 +00004240 // A method in a protocol declaration overrides declarations from
4241 // referenced ("parent") protocols.
4242 search(protocol->getReferencedProtocols());
4243 }
4244
Matt Davis55043e22019-04-22 16:04:44 +00004245 void searchFrom(const ObjCCategoryDecl *category) {
John McCalld2930c22011-07-22 02:45:48 +00004246 // A method in a category declaration overrides declarations from
4247 // the main class and from protocols the category references.
Douglas Gregorcf4ac442012-05-03 21:25:24 +00004248 // The main class is handled in the constructor.
John McCalld2930c22011-07-22 02:45:48 +00004249 search(category->getReferencedProtocols());
4250 }
4251
Matt Davis55043e22019-04-22 16:04:44 +00004252 void searchFrom(const ObjCCategoryImplDecl *impl) {
John McCalld2930c22011-07-22 02:45:48 +00004253 // A method in a category definition that has a category
4254 // declaration overrides declarations from the category
4255 // declaration.
4256 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
4257 search(category);
Douglas Gregorc5928af2012-05-17 22:39:14 +00004258 if (ObjCInterfaceDecl *Interface = category->getClassInterface())
4259 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00004260
4261 // Otherwise it overrides declarations from the class.
Matt Davis55043e22019-04-22 16:04:44 +00004262 } else if (const auto *Interface = impl->getClassInterface()) {
Douglas Gregorc5928af2012-05-17 22:39:14 +00004263 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00004264 }
4265 }
4266
Matt Davis55043e22019-04-22 16:04:44 +00004267 void searchFrom(const ObjCInterfaceDecl *iface) {
John McCalld2930c22011-07-22 02:45:48 +00004268 // A method in a class declaration overrides declarations from
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00004269 if (!iface->hasDefinition())
4270 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00004271
John McCalld2930c22011-07-22 02:45:48 +00004272 // - categories,
Aaron Ballman15063e12014-03-13 21:35:02 +00004273 for (auto *Cat : iface->known_categories())
4274 search(Cat);
John McCalld2930c22011-07-22 02:45:48 +00004275
4276 // - the super class, and
4277 if (ObjCInterfaceDecl *super = iface->getSuperClass())
4278 search(super);
4279
4280 // - any referenced protocols.
4281 search(iface->getReferencedProtocols());
4282 }
4283
Matt Davis55043e22019-04-22 16:04:44 +00004284 void searchFrom(const ObjCImplementationDecl *impl) {
John McCalld2930c22011-07-22 02:45:48 +00004285 // A method in a class implementation overrides declarations from
4286 // the class interface.
Matt Davis55043e22019-04-22 16:04:44 +00004287 if (const auto *Interface = impl->getClassInterface())
Douglas Gregorc5928af2012-05-17 22:39:14 +00004288 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00004289 }
4290
John McCalld2930c22011-07-22 02:45:48 +00004291 void search(const ObjCProtocolList &protocols) {
Matt Davis55043e22019-04-22 16:04:44 +00004292 for (const auto *Proto : protocols)
4293 search(Proto);
John McCalld2930c22011-07-22 02:45:48 +00004294 }
4295
Matt Davis55043e22019-04-22 16:04:44 +00004296 void search(const ObjCContainerDecl *container) {
John McCalld2930c22011-07-22 02:45:48 +00004297 // Check for a method in this container which matches this selector.
4298 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
Argyrios Kyrtzidisbd8cd3e2013-03-29 21:51:48 +00004299 Method->isInstanceMethod(),
4300 /*AllowHidden=*/true);
John McCalld2930c22011-07-22 02:45:48 +00004301
4302 // If we find one, record it and bail out.
4303 if (meth) {
4304 Overridden.insert(meth);
4305 return;
4306 }
4307
4308 // Otherwise, search for methods that a hypothetical method here
4309 // would have overridden.
4310
4311 // Note that we're now in a recursive case.
4312 Recursive = true;
4313
4314 searchFromContainer(container);
4315 }
4316};
Hans Wennborgdcfba332015-10-06 23:40:43 +00004317} // end anonymous namespace
Douglas Gregor33823722011-06-11 01:09:30 +00004318
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004319void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
4320 ObjCInterfaceDecl *CurrentClass,
4321 ResultTypeCompatibilityKind RTC) {
Matt Davis55043e22019-04-22 16:04:44 +00004322 if (!ObjCMethod)
4323 return;
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004324 // Search for overridden methods and merge information down from them.
4325 OverrideSearch overrides(*this, ObjCMethod);
4326 // Keep track if the method overrides any method in the class's base classes,
4327 // its protocols, or its categories' protocols; we will keep that info
4328 // in the ObjCMethodDecl.
4329 // For this info, a method in an implementation is not considered as
4330 // overriding the same method in the interface or its categories.
4331 bool hasOverriddenMethodsInBaseOrProtocol = false;
Matt Davis55043e22019-04-22 16:04:44 +00004332 for (ObjCMethodDecl *overridden : overrides) {
Argyrios Kyrtzidisc2091d52013-04-17 00:09:08 +00004333 if (!hasOverriddenMethodsInBaseOrProtocol) {
4334 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
4335 CurrentClass != overridden->getClassInterface() ||
4336 overridden->isOverriding()) {
4337 hasOverriddenMethodsInBaseOrProtocol = true;
4338
4339 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
4340 // OverrideSearch will return as "overridden" the same method in the
4341 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
4342 // check whether a category of a base class introduced a method with the
4343 // same selector, after the interface method declaration.
4344 // To avoid unnecessary lookups in the majority of cases, we use the
4345 // extra info bits in GlobalMethodPool to check whether there were any
4346 // category methods with this selector.
4347 GlobalMethodPool::iterator It =
4348 MethodPool.find(ObjCMethod->getSelector());
4349 if (It != MethodPool.end()) {
4350 ObjCMethodList &List =
4351 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
4352 unsigned CategCount = List.getBits();
4353 if (CategCount > 0) {
4354 // If the method is in a category we'll do lookup if there were at
4355 // least 2 category methods recorded, otherwise only one will do.
4356 if (CategCount > 1 ||
4357 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
4358 OverrideSearch overrides(*this, overridden);
Matt Davis55043e22019-04-22 16:04:44 +00004359 for (ObjCMethodDecl *SuperOverridden : overrides) {
Argyrios Kyrtzidis04703a62013-04-27 00:10:12 +00004360 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
4361 CurrentClass != SuperOverridden->getClassInterface()) {
Argyrios Kyrtzidisc2091d52013-04-17 00:09:08 +00004362 hasOverriddenMethodsInBaseOrProtocol = true;
4363 overridden->setOverriding(true);
4364 break;
4365 }
4366 }
4367 }
4368 }
4369 }
4370 }
4371 }
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004372
4373 // Propagate down the 'related result type' bit from overridden methods.
4374 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
Erich Keane9b18eca2018-08-01 21:31:08 +00004375 ObjCMethod->setRelatedResultType();
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004376
4377 // Then merge the declarations.
4378 mergeObjCMethodDecls(ObjCMethod, overridden);
4379
4380 if (ObjCMethod->isImplicit() && overridden->isImplicit())
4381 continue; // Conflicting properties are detected elsewhere.
4382
4383 // Check for overriding methods
Fangrui Song6907ce22018-07-30 19:24:48 +00004384 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004385 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
4386 CheckConflictingOverridingMethod(ObjCMethod, overridden,
4387 isa<ObjCProtocolDecl>(overridden->getDeclContext()));
Fangrui Song6907ce22018-07-30 19:24:48 +00004388
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004389 if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
Fariborz Jahanian31a25682012-07-05 22:26:07 +00004390 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
4391 !overridden->isImplicit() /* not meant for properties */) {
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004392 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
4393 E = ObjCMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +00004394 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
4395 PrevE = overridden->param_end();
4396 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004397 assert(PrevI != overridden->param_end() && "Param mismatch");
4398 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
4399 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
4400 // If type of argument of method in this class does not match its
4401 // respective argument type in the super class method, issue warning;
4402 if (!Context.typesAreCompatible(T1, T2)) {
4403 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
4404 << T1 << T2;
4405 Diag(overridden->getLocation(), diag::note_previous_declaration);
4406 break;
4407 }
4408 }
4409 }
4410 }
4411
4412 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
4413}
4414
Douglas Gregor813a0662015-06-19 18:14:38 +00004415/// Merge type nullability from for a redeclaration of the same entity,
4416/// producing the updated type of the redeclared entity.
4417static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc,
4418 QualType type,
4419 bool usesCSKeyword,
4420 SourceLocation prevLoc,
4421 QualType prevType,
4422 bool prevUsesCSKeyword) {
4423 // Determine the nullability of both types.
4424 auto nullability = type->getNullability(S.Context);
4425 auto prevNullability = prevType->getNullability(S.Context);
4426
4427 // Easy case: both have nullability.
4428 if (nullability.hasValue() == prevNullability.hasValue()) {
4429 // Neither has nullability; continue.
4430 if (!nullability)
4431 return type;
4432
4433 // The nullabilities are equivalent; do nothing.
4434 if (*nullability == *prevNullability)
4435 return type;
4436
4437 // Complain about mismatched nullability.
4438 S.Diag(loc, diag::err_nullability_conflicting)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00004439 << DiagNullabilityKind(*nullability, usesCSKeyword)
4440 << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword);
Douglas Gregor813a0662015-06-19 18:14:38 +00004441 return type;
4442 }
4443
4444 // If it's the redeclaration that has nullability, don't change anything.
4445 if (nullability)
4446 return type;
4447
4448 // Otherwise, provide the result with the same nullability.
4449 return S.Context.getAttributedType(
4450 AttributedType::getNullabilityAttrKind(*prevNullability),
4451 type, type);
4452}
4453
NAKAMURA Takumi2df5c3c2015-06-20 03:52:52 +00004454/// Merge information from the declaration of a method in the \@interface
Douglas Gregor813a0662015-06-19 18:14:38 +00004455/// (or a category/extension) into the corresponding method in the
4456/// @implementation (for a class or category).
4457static void mergeInterfaceMethodToImpl(Sema &S,
4458 ObjCMethodDecl *method,
4459 ObjCMethodDecl *prevMethod) {
4460 // Merge the objc_requires_super attribute.
4461 if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() &&
4462 !method->hasAttr<ObjCRequiresSuperAttr>()) {
4463 // merge the attribute into implementation.
4464 method->addAttr(
4465 ObjCRequiresSuperAttr::CreateImplicit(S.Context,
4466 method->getLocation()));
4467 }
4468
4469 // Merge nullability of the result type.
4470 QualType newReturnType
4471 = mergeTypeNullabilityForRedecl(
4472 S, method->getReturnTypeSourceRange().getBegin(),
4473 method->getReturnType(),
4474 method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4475 prevMethod->getReturnTypeSourceRange().getBegin(),
4476 prevMethod->getReturnType(),
4477 prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4478 method->setReturnType(newReturnType);
4479
4480 // Handle each of the parameters.
4481 unsigned numParams = method->param_size();
4482 unsigned numPrevParams = prevMethod->param_size();
4483 for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) {
4484 ParmVarDecl *param = method->param_begin()[i];
4485 ParmVarDecl *prevParam = prevMethod->param_begin()[i];
4486
4487 // Merge nullability.
4488 QualType newParamType
4489 = mergeTypeNullabilityForRedecl(
4490 S, param->getLocation(), param->getType(),
4491 param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4492 prevParam->getLocation(), prevParam->getType(),
4493 prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4494 param->setType(newParamType);
4495 }
4496}
4497
Alex Lorenza8a372d2017-04-27 10:43:48 +00004498/// Verify that the method parameters/return value have types that are supported
4499/// by the x86 target.
4500static void checkObjCMethodX86VectorTypes(Sema &SemaRef,
4501 const ObjCMethodDecl *Method) {
4502 assert(SemaRef.getASTContext().getTargetInfo().getTriple().getArch() ==
4503 llvm::Triple::x86 &&
4504 "x86-specific check invoked for a different target");
4505 SourceLocation Loc;
4506 QualType T;
4507 for (const ParmVarDecl *P : Method->parameters()) {
4508 if (P->getType()->isVectorType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004509 Loc = P->getBeginLoc();
Alex Lorenza8a372d2017-04-27 10:43:48 +00004510 T = P->getType();
4511 break;
4512 }
4513 }
4514 if (Loc.isInvalid()) {
4515 if (Method->getReturnType()->isVectorType()) {
4516 Loc = Method->getReturnTypeSourceRange().getBegin();
4517 T = Method->getReturnType();
4518 } else
4519 return;
4520 }
4521
4522 // Vector parameters/return values are not supported by objc_msgSend on x86 in
4523 // iOS < 9 and macOS < 10.11.
4524 const auto &Triple = SemaRef.getASTContext().getTargetInfo().getTriple();
4525 VersionTuple AcceptedInVersion;
4526 if (Triple.getOS() == llvm::Triple::IOS)
4527 AcceptedInVersion = VersionTuple(/*Major=*/9);
4528 else if (Triple.isMacOSX())
4529 AcceptedInVersion = VersionTuple(/*Major=*/10, /*Minor=*/11);
4530 else
4531 return;
Alex Lorenza8a372d2017-04-27 10:43:48 +00004532 if (SemaRef.getASTContext().getTargetInfo().getPlatformMinVersion() >=
Alex Lorenz92824832017-05-05 16:15:17 +00004533 AcceptedInVersion)
Alex Lorenza8a372d2017-04-27 10:43:48 +00004534 return;
4535 SemaRef.Diag(Loc, diag::err_objc_method_unsupported_param_ret_type)
4536 << T << (Method->getReturnType()->isVectorType() ? /*return value*/ 1
4537 : /*parameter*/ 0)
4538 << (Triple.isMacOSX() ? "macOS 10.11" : "iOS 9");
4539}
4540
John McCall48871652010-08-21 09:40:31 +00004541Decl *Sema::ActOnMethodDeclaration(
Erich Keanec480f302018-07-12 21:09:05 +00004542 Scope *S, SourceLocation MethodLoc, SourceLocation EndLoc,
4543 tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
4544 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
Chris Lattnerda463fe2007-12-12 07:09:47 +00004545 // optional arguments. The number of types/arguments is obtained
4546 // from the Sel.getNumArgs().
Erich Keanec480f302018-07-12 21:09:05 +00004547 ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
4548 unsigned CNumArgs, // c-style args
4549 const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodDeclKind,
Fariborz Jahanianc677f692011-03-12 18:54:30 +00004550 bool isVariadic, bool MethodDefinition) {
Steve Naroff83777fe2008-02-29 21:48:07 +00004551 // Make sure we can establish a context for the method.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004552 if (!CurContext->isObjCContainer()) {
Richard Smithf8812672016-12-02 22:38:31 +00004553 Diag(MethodLoc, diag::err_missing_method_context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004554 return nullptr;
Steve Naroff83777fe2008-02-29 21:48:07 +00004555 }
George Burgess IV00f70bd2018-03-01 05:43:23 +00004556 Decl *ClassDecl = cast<ObjCContainerDecl>(CurContext);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004557 QualType resultDeclType;
Mike Stump11289f42009-09-09 15:08:12 +00004558
Douglas Gregorbab8a962011-09-08 01:46:34 +00004559 bool HasRelatedResultType = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00004560 TypeSourceInfo *ReturnTInfo = nullptr;
Steve Naroff32606412009-02-20 22:59:16 +00004561 if (ReturnType) {
Alp Toker314cc812014-01-25 16:55:45 +00004562 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004563
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004564 if (CheckFunctionReturnType(resultDeclType, MethodLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00004565 return nullptr;
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004566
Douglas Gregor813a0662015-06-19 18:14:38 +00004567 QualType bareResultType = resultDeclType;
4568 (void)AttributedType::stripOuterNullability(bareResultType);
4569 HasRelatedResultType = (bareResultType == Context.getObjCInstanceType());
Fariborz Jahanianb5a52ca2011-07-21 17:00:47 +00004570 } else { // get the type for "id".
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004571 resultDeclType = Context.getObjCIdType();
Fariborz Jahanianb21138f2011-07-21 17:38:14 +00004572 Diag(MethodLoc, diag::warn_missing_method_return_type)
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004573 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
Fariborz Jahanianb5a52ca2011-07-21 17:00:47 +00004574 }
Mike Stump11289f42009-09-09 15:08:12 +00004575
Alp Toker314cc812014-01-25 16:55:45 +00004576 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
4577 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
4578 MethodType == tok::minus, isVariadic,
4579 /*isPropertyAccessor=*/false,
4580 /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
4581 MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
4582 : ObjCMethodDecl::Required,
4583 HasRelatedResultType);
Mike Stump11289f42009-09-09 15:08:12 +00004584
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004585 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump11289f42009-09-09 15:08:12 +00004586
Chris Lattner23b0faf2009-04-11 19:42:43 +00004587 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
John McCall856bbea2009-10-23 21:48:59 +00004588 QualType ArgType;
John McCallbcd03502009-12-07 02:54:59 +00004589 TypeSourceInfo *DI;
Mike Stump11289f42009-09-09 15:08:12 +00004590
David Blaikie7d170102013-05-15 07:37:26 +00004591 if (!ArgInfo[i].Type) {
John McCall856bbea2009-10-23 21:48:59 +00004592 ArgType = Context.getObjCIdType();
Craig Topperc3ec1492014-05-26 06:22:03 +00004593 DI = nullptr;
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004594 } else {
John McCall856bbea2009-10-23 21:48:59 +00004595 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004596 }
Mike Stump11289f42009-09-09 15:08:12 +00004597
Fangrui Song6907ce22018-07-30 19:24:48 +00004598 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
Richard Smithbecb92d2017-10-10 22:33:17 +00004599 LookupOrdinaryName, forRedeclarationInCurContext());
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004600 LookupName(R, S);
4601 if (R.isSingleResult()) {
4602 NamedDecl *PrevDecl = R.getFoundDecl();
4603 if (S->isDeclScope(PrevDecl)) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004604 Diag(ArgInfo[i].NameLoc,
4605 (MethodDefinition ? diag::warn_method_param_redefinition
4606 : diag::warn_method_param_declaration))
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004607 << ArgInfo[i].Name;
Fangrui Song6907ce22018-07-30 19:24:48 +00004608 Diag(PrevDecl->getLocation(),
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004609 diag::note_previous_declaration);
4610 }
4611 }
4612
Abramo Bagnaradff19302011-03-08 08:55:46 +00004613 SourceLocation StartLoc = DI
4614 ? DI->getTypeLoc().getBeginLoc()
4615 : ArgInfo[i].NameLoc;
4616
John McCalld44f4d72011-04-23 02:46:06 +00004617 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
4618 ArgInfo[i].NameLoc, ArgInfo[i].Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004619 ArgType, DI, SC_None);
Mike Stump11289f42009-09-09 15:08:12 +00004620
John McCall82490832011-05-02 00:30:12 +00004621 Param->setObjCMethodScopeInfo(i);
4622
Chris Lattnerc5ffed42008-04-04 06:12:32 +00004623 Param->setObjCDeclQualifier(
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004624 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
Mike Stump11289f42009-09-09 15:08:12 +00004625
Chris Lattner9713a1c2009-04-11 19:34:56 +00004626 // Apply the attributes to the parameter.
Douglas Gregor758a8692009-06-17 21:51:59 +00004627 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00004628 AddPragmaAttributes(TUScope, Param);
Mike Stump11289f42009-09-09 15:08:12 +00004629
Fariborz Jahanian52d02f62012-01-14 18:44:35 +00004630 if (Param->hasAttr<BlocksAttr>()) {
4631 Diag(Param->getLocation(), diag::err_block_on_nonlocal);
4632 Param->setInvalidDecl();
4633 }
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004634 S->AddDecl(Param);
4635 IdResolver.AddDecl(Param);
4636
Chris Lattnerc5ffed42008-04-04 06:12:32 +00004637 Params.push_back(Param);
4638 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004639
Fariborz Jahanian60462092010-04-08 00:30:06 +00004640 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +00004641 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
Fariborz Jahanian60462092010-04-08 00:30:06 +00004642 QualType ArgType = Param->getType();
4643 if (ArgType.isNull())
4644 ArgType = Context.getObjCIdType();
4645 else
4646 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
Douglas Gregor84280642011-07-12 04:42:08 +00004647 ArgType = Context.getAdjustedParameterType(ArgType);
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004648
Fariborz Jahanian60462092010-04-08 00:30:06 +00004649 Param->setDeclContext(ObjCMethod);
Fariborz Jahanian60462092010-04-08 00:30:06 +00004650 Params.push_back(Param);
4651 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004652
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004653 ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004654 ObjCMethod->setObjCDeclQualifier(
4655 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
Daniel Dunbarc136e0c2008-09-26 04:12:28 +00004656
Erich Keanec480f302018-07-12 21:09:05 +00004657 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00004658 AddPragmaAttributes(TUScope, ObjCMethod);
Mike Stump11289f42009-09-09 15:08:12 +00004659
Douglas Gregor87e92752010-12-21 17:34:17 +00004660 // Add the method now.
Craig Topperc3ec1492014-05-26 06:22:03 +00004661 const ObjCMethodDecl *PrevMethod = nullptr;
John McCalld2930c22011-07-22 02:45:48 +00004662 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00004663 if (MethodType == tok::minus) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004664 PrevMethod = ImpDecl->getInstanceMethod(Sel);
4665 ImpDecl->addInstanceMethod(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004666 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004667 PrevMethod = ImpDecl->getClassMethod(Sel);
4668 ImpDecl->addClassMethod(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004669 }
Douglas Gregor33823722011-06-11 01:09:30 +00004670
Douglas Gregor813a0662015-06-19 18:14:38 +00004671 // Merge information from the @interface declaration into the
4672 // @implementation.
4673 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) {
4674 if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
4675 ObjCMethod->isInstanceMethod())) {
4676 mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD);
4677
4678 // Warn about defining -dealloc in a category.
4679 if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() &&
4680 ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) {
4681 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
4682 << ObjCMethod->getDeclName();
4683 }
4684 }
Akira Hatanakaa6b5e002018-07-28 04:06:13 +00004685
4686 // Warn if a method declared in a protocol to which a category or
4687 // extension conforms is non-escaping and the implementation's method is
4688 // escaping.
4689 for (auto *C : IDecl->visible_categories())
4690 for (auto &P : C->protocols())
4691 if (auto *IMD = P->lookupMethod(ObjCMethod->getSelector(),
4692 ObjCMethod->isInstanceMethod())) {
4693 assert(ObjCMethod->parameters().size() ==
4694 IMD->parameters().size() &&
4695 "Methods have different number of parameters");
4696 auto OI = IMD->param_begin(), OE = IMD->param_end();
4697 auto NI = ObjCMethod->param_begin();
4698 for (; OI != OE; ++OI, ++NI)
4699 diagnoseNoescape(*NI, *OI, C, P, *this);
4700 }
Fariborz Jahanian7e350d22013-12-17 22:44:28 +00004701 }
Douglas Gregor87e92752010-12-21 17:34:17 +00004702 } else {
4703 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004704 }
John McCalld2930c22011-07-22 02:45:48 +00004705
Chris Lattnerda463fe2007-12-12 07:09:47 +00004706 if (PrevMethod) {
4707 // You can never have two method definitions with the same name.
Chris Lattner0369c572008-11-23 23:12:31 +00004708 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00004709 << ObjCMethod->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00004710 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian096f7c12013-05-13 17:27:00 +00004711 ObjCMethod->setInvalidDecl();
4712 return ObjCMethod;
Mike Stump11289f42009-09-09 15:08:12 +00004713 }
John McCall28a6aea2009-11-04 02:18:39 +00004714
Douglas Gregor33823722011-06-11 01:09:30 +00004715 // If this Objective-C method does not have a related result type, but we
4716 // are allowed to infer related result types, try to do so based on the
4717 // method family.
4718 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
4719 if (!CurrentClass) {
4720 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
4721 CurrentClass = Cat->getClassInterface();
4722 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
4723 CurrentClass = Impl->getClassInterface();
4724 else if (ObjCCategoryImplDecl *CatImpl
4725 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
4726 CurrentClass = CatImpl->getClassInterface();
4727 }
John McCalld2930c22011-07-22 02:45:48 +00004728
Douglas Gregorbab8a962011-09-08 01:46:34 +00004729 ResultTypeCompatibilityKind RTC
4730 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
John McCalld2930c22011-07-22 02:45:48 +00004731
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004732 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
John McCalld2930c22011-07-22 02:45:48 +00004733
John McCall31168b02011-06-15 23:02:42 +00004734 bool ARCError = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004735 if (getLangOpts().ObjCAutoRefCount)
John McCalle48f3892013-04-04 01:38:37 +00004736 ARCError = CheckARCMethodDecl(ObjCMethod);
John McCall31168b02011-06-15 23:02:42 +00004737
Douglas Gregorbab8a962011-09-08 01:46:34 +00004738 // Infer the related result type when possible.
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004739 if (!ARCError && RTC == Sema::RTC_Compatible &&
Douglas Gregorbab8a962011-09-08 01:46:34 +00004740 !ObjCMethod->hasRelatedResultType() &&
4741 LangOpts.ObjCInferRelatedResultType) {
Douglas Gregor33823722011-06-11 01:09:30 +00004742 bool InferRelatedResultType = false;
4743 switch (ObjCMethod->getMethodFamily()) {
4744 case OMF_None:
4745 case OMF_copy:
4746 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +00004747 case OMF_finalize:
Douglas Gregor33823722011-06-11 01:09:30 +00004748 case OMF_mutableCopy:
4749 case OMF_release:
4750 case OMF_retainCount:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00004751 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00004752 case OMF_performSelector:
Douglas Gregor33823722011-06-11 01:09:30 +00004753 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004754
Douglas Gregor33823722011-06-11 01:09:30 +00004755 case OMF_alloc:
4756 case OMF_new:
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00004757 InferRelatedResultType = ObjCMethod->isClassMethod();
Douglas Gregor33823722011-06-11 01:09:30 +00004758 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004759
Douglas Gregor33823722011-06-11 01:09:30 +00004760 case OMF_init:
4761 case OMF_autorelease:
4762 case OMF_retain:
4763 case OMF_self:
4764 InferRelatedResultType = ObjCMethod->isInstanceMethod();
4765 break;
4766 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004767
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00004768 if (InferRelatedResultType &&
4769 !ObjCMethod->getReturnType()->isObjCIndependentClassType())
Erich Keane9b18eca2018-08-01 21:31:08 +00004770 ObjCMethod->setRelatedResultType();
Douglas Gregor33823722011-06-11 01:09:30 +00004771 }
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00004772
Alex Lorenza8a372d2017-04-27 10:43:48 +00004773 if (MethodDefinition &&
4774 Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
4775 checkObjCMethodX86VectorTypes(*this, ObjCMethod);
4776
Steven Wu3bb4aa52018-04-16 23:34:18 +00004777 // + load method cannot have availability attributes. It get called on
4778 // startup, so it has to have the availability of the deployment target.
4779 if (const auto *attr = ObjCMethod->getAttr<AvailabilityAttr>()) {
4780 if (ObjCMethod->isClassMethod() &&
4781 ObjCMethod->getSelector().getAsString() == "load") {
4782 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
4783 << 0;
4784 ObjCMethod->dropAttr<AvailabilityAttr>();
4785 }
4786 }
4787
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00004788 ActOnDocumentableDecl(ObjCMethod);
4789
John McCall48871652010-08-21 09:40:31 +00004790 return ObjCMethod;
Chris Lattnerda463fe2007-12-12 07:09:47 +00004791}
4792
Chris Lattner438e5012008-12-17 07:13:27 +00004793bool Sema::CheckObjCDeclScope(Decl *D) {
Fariborz Jahanianf36734d2011-08-22 18:34:22 +00004794 // Following is also an error. But it is caused by a missing @end
4795 // and diagnostic is issued elsewhere.
Argyrios Kyrtzidis822c4332012-03-23 23:24:23 +00004796 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004797 return false;
Argyrios Kyrtzidis822c4332012-03-23 23:24:23 +00004798
4799 // If we switched context to translation unit while we are still lexically in
4800 // an objc container, it means the parser missed emitting an error.
4801 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
4802 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004803
Anders Carlssona6b508a2008-11-04 16:57:32 +00004804 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
4805 D->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004806
Anders Carlssona6b508a2008-11-04 16:57:32 +00004807 return true;
4808}
Chris Lattner438e5012008-12-17 07:13:27 +00004809
James Dennett634962f2012-06-14 21:40:34 +00004810/// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
Chris Lattner438e5012008-12-17 07:13:27 +00004811/// instance variables of ClassName into Decls.
John McCall48871652010-08-21 09:40:31 +00004812void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
Chris Lattner438e5012008-12-17 07:13:27 +00004813 IdentifierInfo *ClassName,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004814 SmallVectorImpl<Decl*> &Decls) {
Chris Lattner438e5012008-12-17 07:13:27 +00004815 // Check that ClassName is a valid class
Douglas Gregorb2ccf012010-04-15 22:33:43 +00004816 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
Chris Lattner438e5012008-12-17 07:13:27 +00004817 if (!Class) {
4818 Diag(DeclStart, diag::err_undef_interface) << ClassName;
4819 return;
4820 }
John McCall5fb5df92012-06-20 06:18:46 +00004821 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanianece1b2b2009-04-21 20:28:41 +00004822 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
4823 return;
4824 }
Mike Stump11289f42009-09-09 15:08:12 +00004825
Chris Lattner438e5012008-12-17 07:13:27 +00004826 // Collect the instance variables
Jordy Rosea91768e2011-07-22 02:08:32 +00004827 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004828 Context.DeepCollectObjCIvars(Class, true, Ivars);
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004829 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004830 for (unsigned i = 0; i < Ivars.size(); i++) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00004831 const FieldDecl* ID = Ivars[i];
John McCall48871652010-08-21 09:40:31 +00004832 RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
Abramo Bagnaradff19302011-03-08 08:55:46 +00004833 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
4834 /*FIXME: StartL=*/ID->getLocation(),
4835 ID->getLocation(),
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004836 ID->getIdentifier(), ID->getType(),
4837 ID->getBitWidth());
John McCall48871652010-08-21 09:40:31 +00004838 Decls.push_back(FD);
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004839 }
Mike Stump11289f42009-09-09 15:08:12 +00004840
Chris Lattner438e5012008-12-17 07:13:27 +00004841 // Introduce all of these fields into the appropriate scope.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004842 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
Chris Lattner438e5012008-12-17 07:13:27 +00004843 D != Decls.end(); ++D) {
John McCall48871652010-08-21 09:40:31 +00004844 FieldDecl *FD = cast<FieldDecl>(*D);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004845 if (getLangOpts().CPlusPlus)
George Burgess IV00f70bd2018-03-01 05:43:23 +00004846 PushOnScopeChains(FD, S);
John McCall48871652010-08-21 09:40:31 +00004847 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004848 Record->addDecl(FD);
Chris Lattner438e5012008-12-17 07:13:27 +00004849 }
4850}
4851
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004852/// Build a type-check a new Objective-C exception variable declaration.
Abramo Bagnaradff19302011-03-08 08:55:46 +00004853VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
4854 SourceLocation StartLoc,
4855 SourceLocation IdLoc,
4856 IdentifierInfo *Id,
Douglas Gregorf3564192010-04-26 17:32:49 +00004857 bool Invalid) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004858 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
Douglas Gregorf3564192010-04-26 17:32:49 +00004859 // duration shall not be qualified by an address-space qualifier."
4860 // Since all parameters have automatic store duration, they can not have
4861 // an address space.
Alexander Richardson6d989432017-10-15 18:48:14 +00004862 if (T.getAddressSpace() != LangAS::Default) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004863 Diag(IdLoc, diag::err_arg_with_address_space);
Douglas Gregorf3564192010-04-26 17:32:49 +00004864 Invalid = true;
4865 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004866
Douglas Gregorf3564192010-04-26 17:32:49 +00004867 // An @catch parameter must be an unqualified object pointer type;
4868 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
4869 if (Invalid) {
4870 // Don't do any further checking.
Douglas Gregorf4e837f2010-04-26 17:57:08 +00004871 } else if (T->isDependentType()) {
4872 // Okay: we don't know what this type will instantiate to.
Douglas Gregorf3564192010-04-26 17:32:49 +00004873 } else if (T->isObjCQualifiedIdType()) {
4874 Invalid = true;
Abramo Bagnaradff19302011-03-08 08:55:46 +00004875 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
Saleem Abdulrasool278e1c42018-05-20 19:26:44 +00004876 } else if (T->isObjCIdType()) {
4877 // Okay: we don't know what this type will instantiate to.
4878 } else if (!T->isObjCObjectPointerType()) {
4879 Invalid = true;
4880 Diag(IdLoc, diag::err_catch_param_not_objc_type);
4881 } else if (!T->getAs<ObjCObjectPointerType>()->getInterfaceType()) {
4882 Invalid = true;
4883 Diag(IdLoc, diag::err_catch_param_not_objc_type);
Douglas Gregorf3564192010-04-26 17:32:49 +00004884 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004885
Abramo Bagnaradff19302011-03-08 08:55:46 +00004886 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004887 T, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00004888 New->setExceptionVariable(true);
Fangrui Song6907ce22018-07-30 19:24:48 +00004889
Douglas Gregor8ca0c642011-12-10 01:22:52 +00004890 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004891 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
Douglas Gregor8ca0c642011-12-10 01:22:52 +00004892 Invalid = true;
4893
Douglas Gregorf3564192010-04-26 17:32:49 +00004894 if (Invalid)
4895 New->setInvalidDecl();
4896 return New;
4897}
4898
John McCall48871652010-08-21 09:40:31 +00004899Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
Douglas Gregorf3564192010-04-26 17:32:49 +00004900 const DeclSpec &DS = D.getDeclSpec();
Fangrui Song6907ce22018-07-30 19:24:48 +00004901
Douglas Gregorf3564192010-04-26 17:32:49 +00004902 // We allow the "register" storage class on exception variables because
4903 // GCC did, but we drop it completely. Any other storage class is an error.
4904 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
4905 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
4906 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
Richard Smithb4a9e862013-04-12 22:46:28 +00004907 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
Douglas Gregorf3564192010-04-26 17:32:49 +00004908 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
Richard Smithb4a9e862013-04-12 22:46:28 +00004909 << DeclSpec::getSpecifierName(SCS);
4910 }
Richard Smith62f19e72016-06-25 00:15:56 +00004911 if (DS.isInlineSpecified())
4912 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004913 << getLangOpts().CPlusPlus17;
Richard Smithb4a9e862013-04-12 22:46:28 +00004914 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
4915 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
4916 diag::err_invalid_thread)
4917 << DeclSpec::getSpecifierName(TSCS);
Douglas Gregorf3564192010-04-26 17:32:49 +00004918 D.getMutableDeclSpec().ClearStorageClassSpecs();
4919
Richard Smithb1402ae2013-03-18 22:52:47 +00004920 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Fangrui Song6907ce22018-07-30 19:24:48 +00004921
Douglas Gregorf3564192010-04-26 17:32:49 +00004922 // Check that there are no default arguments inside the type of this
4923 // exception object (C++ only).
David Blaikiebbafb8a2012-03-11 07:00:24 +00004924 if (getLangOpts().CPlusPlus)
Douglas Gregorf3564192010-04-26 17:32:49 +00004925 CheckExtraCXXDefaultArguments(D);
Fangrui Song6907ce22018-07-30 19:24:48 +00004926
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00004927 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00004928 QualType ExceptionType = TInfo->getType();
Douglas Gregorf3564192010-04-26 17:32:49 +00004929
Abramo Bagnaradff19302011-03-08 08:55:46 +00004930 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
4931 D.getSourceRange().getBegin(),
4932 D.getIdentifierLoc(),
4933 D.getIdentifier(),
Douglas Gregorf3564192010-04-26 17:32:49 +00004934 D.isInvalidType());
Fangrui Song6907ce22018-07-30 19:24:48 +00004935
Douglas Gregorf3564192010-04-26 17:32:49 +00004936 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
4937 if (D.getCXXScopeSpec().isSet()) {
4938 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
4939 << D.getCXXScopeSpec().getRange();
4940 New->setInvalidDecl();
4941 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004942
Douglas Gregorf3564192010-04-26 17:32:49 +00004943 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00004944 S->AddDecl(New);
Douglas Gregorf3564192010-04-26 17:32:49 +00004945 if (D.getIdentifier())
4946 IdResolver.AddDecl(New);
Fangrui Song6907ce22018-07-30 19:24:48 +00004947
Douglas Gregorf3564192010-04-26 17:32:49 +00004948 ProcessDeclAttributes(S, New, D);
Fangrui Song6907ce22018-07-30 19:24:48 +00004949
Douglas Gregorf3564192010-04-26 17:32:49 +00004950 if (New->hasAttr<BlocksAttr>())
4951 Diag(New->getLocation(), diag::err_block_on_nonlocal);
John McCall48871652010-08-21 09:40:31 +00004952 return New;
Douglas Gregore11ee112010-04-23 23:01:43 +00004953}
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004954
4955/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004956/// initialization.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004957void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004958 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004959 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004960 Iv= Iv->getNextIvar()) {
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004961 QualType QT = Context.getBaseElementType(Iv->getType());
Douglas Gregor527786e2010-05-20 02:24:22 +00004962 if (QT->isRecordType())
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004963 Ivars.push_back(Iv);
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004964 }
4965}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004966
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004967void Sema::DiagnoseUseOfUnimplementedSelectors() {
Douglas Gregor72e357f2011-07-28 14:54:22 +00004968 // Load referenced selectors from the external source.
4969 if (ExternalSource) {
4970 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
4971 ExternalSource->ReadReferencedSelectors(Sels);
4972 for (unsigned I = 0, N = Sels.size(); I != N; ++I)
4973 ReferencedSelectors[Sels[I].first] = Sels[I].second;
4974 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004975
Fariborz Jahanianc9b7c202011-02-04 23:19:27 +00004976 // Warning will be issued only when selector table is
4977 // generated (which means there is at lease one implementation
4978 // in the TU). This is to match gcc's behavior.
Fangrui Song6907ce22018-07-30 19:24:48 +00004979 if (ReferencedSelectors.empty() ||
Fariborz Jahanianc9b7c202011-02-04 23:19:27 +00004980 !Context.AnyObjCImplementation())
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004981 return;
Chandler Carruth12c8f652015-03-27 00:55:05 +00004982 for (auto &SelectorAndLocation : ReferencedSelectors) {
4983 Selector Sel = SelectorAndLocation.first;
4984 SourceLocation Loc = SelectorAndLocation.second;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004985 if (!LookupImplementedMethodInGlobalPool(Sel))
Chandler Carruth12c8f652015-03-27 00:55:05 +00004986 Diag(Loc, diag::warn_unimplemented_selector) << Sel;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004987 }
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004988}
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004989
4990ObjCIvarDecl *
4991Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4992 const ObjCPropertyDecl *&PDecl) const {
Fariborz Jahanian1cc7ae12014-01-02 17:24:32 +00004993 if (Method->isClassMethod())
Craig Topperc3ec1492014-05-26 06:22:03 +00004994 return nullptr;
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004995 const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
4996 if (!IDecl)
Craig Topperc3ec1492014-05-26 06:22:03 +00004997 return nullptr;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004998 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
4999 /*shallowCategoryLookup=*/false,
5000 /*followSuper=*/false);
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00005001 if (!Method || !Method->isPropertyAccessor())
Craig Topperc3ec1492014-05-26 06:22:03 +00005002 return nullptr;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005003 if ((PDecl = Method->findPropertyDecl()))
Fariborz Jahanian122d94f2014-01-27 22:27:43 +00005004 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
5005 // property backing ivar must belong to property's class
5006 // or be a private ivar in class's implementation.
5007 // FIXME. fix the const-ness issue.
5008 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
5009 IV->getIdentifier());
5010 return IV;
5011 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005012 return nullptr;
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00005013}
5014
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005015namespace {
5016 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
5017 /// accessor references the backing ivar.
Argyrios Kyrtzidis98045c12014-01-03 19:53:09 +00005018 class UnusedBackingIvarChecker :
Richard Smith50668452015-11-24 03:55:01 +00005019 public RecursiveASTVisitor<UnusedBackingIvarChecker> {
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005020 public:
5021 Sema &S;
5022 const ObjCMethodDecl *Method;
5023 const ObjCIvarDecl *IvarD;
5024 bool AccessedIvar;
5025 bool InvokedSelfMethod;
5026
5027 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
5028 const ObjCIvarDecl *IvarD)
5029 : S(S), Method(Method), IvarD(IvarD),
5030 AccessedIvar(false), InvokedSelfMethod(false) {
5031 assert(IvarD);
5032 }
5033
5034 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
5035 if (E->getDecl() == IvarD) {
5036 AccessedIvar = true;
5037 return false;
5038 }
5039 return true;
5040 }
5041
5042 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
5043 if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
5044 S.isSelfExpr(E->getInstanceReceiver(), Method)) {
5045 InvokedSelfMethod = true;
5046 }
5047 return true;
5048 }
5049 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00005050} // end anonymous namespace
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005051
5052void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
5053 const ObjCImplementationDecl *ImplD) {
5054 if (S->hasUnrecoverableErrorOccurred())
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00005055 return;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005056
Aaron Ballmanf26acce2014-03-13 19:50:17 +00005057 for (const auto *CurMethod : ImplD->instance_methods()) {
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005058 unsigned DIAG = diag::warn_unused_property_backing_ivar;
5059 SourceLocation Loc = CurMethod->getLocation();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005060 if (Diags.isIgnored(DIAG, Loc))
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005061 continue;
5062
5063 const ObjCPropertyDecl *PDecl;
5064 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
5065 if (!IV)
5066 continue;
5067
5068 UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
5069 Checker.TraverseStmt(CurMethod->getBody());
5070 if (Checker.AccessedIvar)
5071 continue;
5072
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00005073 // Do not issue this warning if backing ivar is used somewhere and accessor
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005074 // implementation makes a self call. This is to prevent false positive in
5075 // cases where the ivar is accessed by another method that the accessor
5076 // delegates to.
5077 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
Argyrios Kyrtzidisd8a35322014-01-03 19:39:23 +00005078 Diag(Loc, DIAG) << IV;
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00005079 Diag(PDecl->getLocation(), diag::note_property_declare);
5080 }
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00005081 }
5082}