blob: e1eed827167bd38a826ad4f2fdd9cbfb2fcfe834 [file] [log] [blame]
Chris Lattnerda463fe2007-12-12 07:09:47 +00001//===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerda463fe2007-12-12 07:09:47 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for Objective C declarations.
11//
12//===----------------------------------------------------------------------===//
13
Mehdi Amini9670f842016-07-18 19:02:11 +000014#include "TypeLocBuilder.h"
John McCall31168b02011-06-15 23:02:42 +000015#include "clang/AST/ASTConsumer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTMutationListener.h"
18#include "clang/AST/DeclObjC.h"
Steve Naroff157599f2009-03-03 14:49:36 +000019#include "clang/AST/Expr.h"
John McCall31168b02011-06-15 23:02:42 +000020#include "clang/AST/ExprObjC.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000021#include "clang/AST/RecursiveASTVisitor.h"
John McCall31168b02011-06-15 23:02:42 +000022#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Sema/DeclSpec.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Sema/Lookup.h"
25#include "clang/Sema/Scope.h"
26#include "clang/Sema/ScopeInfo.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000027#include "clang/Sema/SemaInternal.h"
Douglas Gregor85f3f952015-07-07 03:57:15 +000028#include "llvm/ADT/DenseMap.h"
John McCalla1e130b2010-08-25 07:03:20 +000029#include "llvm/ADT/DenseSet.h"
30
Chris Lattnerda463fe2007-12-12 07:09:47 +000031using namespace clang;
32
John McCall31168b02011-06-15 23:02:42 +000033/// Check whether the given method, which must be in the 'init'
34/// family, is a valid member of that family.
35///
36/// \param receiverTypeIfCall - if null, check this as if declaring it;
37/// if non-null, check this as if making a call to it with the given
38/// receiver type
39///
40/// \return true to indicate that there was an error and appropriate
41/// actions were taken
42bool Sema::checkInitMethod(ObjCMethodDecl *method,
43 QualType receiverTypeIfCall) {
44 if (method->isInvalidDecl()) return true;
45
46 // This castAs is safe: methods that don't return an object
47 // pointer won't be inferred as inits and will reject an explicit
48 // objc_method_family(init).
49
50 // We ignore protocols here. Should we? What about Class?
51
Alp Toker314cc812014-01-25 16:55:45 +000052 const ObjCObjectType *result =
53 method->getReturnType()->castAs<ObjCObjectPointerType>()->getObjectType();
John McCall31168b02011-06-15 23:02:42 +000054
55 if (result->isObjCId()) {
56 return false;
57 } else if (result->isObjCClass()) {
58 // fall through: always an error
59 } else {
60 ObjCInterfaceDecl *resultClass = result->getInterface();
61 assert(resultClass && "unexpected object type!");
62
63 // It's okay for the result type to still be a forward declaration
64 // if we're checking an interface declaration.
Douglas Gregordc9166c2011-12-15 20:29:51 +000065 if (!resultClass->hasDefinition()) {
John McCall31168b02011-06-15 23:02:42 +000066 if (receiverTypeIfCall.isNull() &&
67 !isa<ObjCImplementationDecl>(method->getDeclContext()))
68 return false;
69
70 // Otherwise, we try to compare class types.
71 } else {
72 // If this method was declared in a protocol, we can't check
73 // anything unless we have a receiver type that's an interface.
Craig Topperc3ec1492014-05-26 06:22:03 +000074 const ObjCInterfaceDecl *receiverClass = nullptr;
John McCall31168b02011-06-15 23:02:42 +000075 if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
76 if (receiverTypeIfCall.isNull())
77 return false;
78
79 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
80 ->getInterfaceDecl();
81
82 // This can be null for calls to e.g. id<Foo>.
83 if (!receiverClass) return false;
84 } else {
85 receiverClass = method->getClassInterface();
86 assert(receiverClass && "method not associated with a class!");
87 }
88
89 // If either class is a subclass of the other, it's fine.
90 if (receiverClass->isSuperClassOf(resultClass) ||
91 resultClass->isSuperClassOf(receiverClass))
92 return false;
93 }
94 }
95
96 SourceLocation loc = method->getLocation();
97
98 // If we're in a system header, and this is not a call, just make
99 // the method unusable.
100 if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
John McCallc6af8c62015-10-28 05:03:19 +0000101 method->addAttr(UnavailableAttr::CreateImplicit(Context, "",
102 UnavailableAttr::IR_ARCInitReturnsUnrelated, loc));
John McCall31168b02011-06-15 23:02:42 +0000103 return true;
104 }
105
106 // Otherwise, it's an error.
107 Diag(loc, diag::err_arc_init_method_unrelated_result_type);
108 method->setInvalidDecl();
109 return true;
110}
111
Fariborz Jahanianac8dbf02011-09-27 22:35:36 +0000112void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
Douglas Gregor66a8ca02013-01-15 22:43:08 +0000113 const ObjCMethodDecl *Overridden) {
Douglas Gregor33823722011-06-11 01:09:30 +0000114 if (Overridden->hasRelatedResultType() &&
115 !NewMethod->hasRelatedResultType()) {
116 // This can only happen when the method follows a naming convention that
117 // implies a related result type, and the original (overridden) method has
118 // a suitable return type, but the new (overriding) method does not have
119 // a suitable return type.
Alp Toker314cc812014-01-25 16:55:45 +0000120 QualType ResultType = NewMethod->getReturnType();
Aaron Ballman41b10ac2014-08-01 13:20:09 +0000121 SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +0000122
123 // Figure out which class this method is part of, if any.
124 ObjCInterfaceDecl *CurrentClass
125 = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
126 if (!CurrentClass) {
127 DeclContext *DC = NewMethod->getDeclContext();
128 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
129 CurrentClass = Cat->getClassInterface();
130 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
131 CurrentClass = Impl->getClassInterface();
132 else if (ObjCCategoryImplDecl *CatImpl
133 = dyn_cast<ObjCCategoryImplDecl>(DC))
134 CurrentClass = CatImpl->getClassInterface();
135 }
136
137 if (CurrentClass) {
138 Diag(NewMethod->getLocation(),
139 diag::warn_related_result_type_compatibility_class)
140 << Context.getObjCInterfaceType(CurrentClass)
141 << ResultType
142 << ResultTypeRange;
143 } else {
144 Diag(NewMethod->getLocation(),
145 diag::warn_related_result_type_compatibility_protocol)
146 << ResultType
147 << ResultTypeRange;
148 }
149
Douglas Gregorbab8a962011-09-08 01:46:34 +0000150 if (ObjCMethodFamily Family = Overridden->getMethodFamily())
151 Diag(Overridden->getLocation(),
John McCall5ec7e7d2013-03-19 07:04:25 +0000152 diag::note_related_result_type_family)
153 << /*overridden method*/ 0
Douglas Gregorbab8a962011-09-08 01:46:34 +0000154 << Family;
155 else
156 Diag(Overridden->getLocation(),
157 diag::note_related_result_type_overridden);
Douglas Gregor33823722011-06-11 01:09:30 +0000158 }
Akira Hatanaka7d85b8f2017-09-20 05:39:18 +0000159
160 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
161 Overridden->hasAttr<NSReturnsRetainedAttr>())) {
162 Diag(NewMethod->getLocation(),
Alex Lorenz26d282f2018-01-03 23:52:42 +0000163 getLangOpts().ObjCAutoRefCount
164 ? diag::err_nsreturns_retained_attribute_mismatch
165 : diag::warn_nsreturns_retained_attribute_mismatch)
166 << 1;
Akira Hatanaka7d85b8f2017-09-20 05:39:18 +0000167 Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
168 }
169 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
170 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
171 Diag(NewMethod->getLocation(),
Alex Lorenz26d282f2018-01-03 23:52:42 +0000172 getLangOpts().ObjCAutoRefCount
173 ? diag::err_nsreturns_retained_attribute_mismatch
174 : diag::warn_nsreturns_retained_attribute_mismatch)
175 << 0;
Akira Hatanaka7d85b8f2017-09-20 05:39:18 +0000176 Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
177 }
178
179 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
180 oe = Overridden->param_end();
181 for (ObjCMethodDecl::param_iterator ni = NewMethod->param_begin(),
182 ne = NewMethod->param_end();
183 ni != ne && oi != oe; ++ni, ++oi) {
184 const ParmVarDecl *oldDecl = (*oi);
185 ParmVarDecl *newDecl = (*ni);
186 if (newDecl->hasAttr<NSConsumedAttr>() !=
187 oldDecl->hasAttr<NSConsumedAttr>()) {
Alex Lorenz26d282f2018-01-03 23:52:42 +0000188 Diag(newDecl->getLocation(),
189 getLangOpts().ObjCAutoRefCount
190 ? diag::err_nsconsumed_attribute_mismatch
191 : diag::warn_nsconsumed_attribute_mismatch);
Akira Hatanaka7d85b8f2017-09-20 05:39:18 +0000192 Diag(oldDecl->getLocation(), diag::note_previous_decl) << "parameter";
Fariborz Jahanianac8dbf02011-09-27 22:35:36 +0000193 }
Akira Hatanaka98a49332017-09-22 00:41:05 +0000194
195 // A parameter of the overriding method should be annotated with noescape
196 // if the corresponding parameter of the overridden method is annotated.
197 if (oldDecl->hasAttr<NoEscapeAttr>() && !newDecl->hasAttr<NoEscapeAttr>()) {
198 Diag(newDecl->getLocation(),
199 diag::warn_overriding_method_missing_noescape);
200 Diag(oldDecl->getLocation(), diag::note_overridden_marked_noescape);
201 }
Fariborz Jahanianac8dbf02011-09-27 22:35:36 +0000202 }
Douglas Gregor33823722011-06-11 01:09:30 +0000203}
204
John McCall31168b02011-06-15 23:02:42 +0000205/// \brief Check a method declaration for compatibility with the Objective-C
206/// ARC conventions.
John McCalle48f3892013-04-04 01:38:37 +0000207bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
John McCall31168b02011-06-15 23:02:42 +0000208 ObjCMethodFamily family = method->getMethodFamily();
209 switch (family) {
210 case OMF_None:
Nico Weber1fb82662011-08-28 22:35:17 +0000211 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +0000212 case OMF_retain:
213 case OMF_release:
214 case OMF_autorelease:
215 case OMF_retainCount:
216 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +0000217 case OMF_initialize:
John McCalld2930c22011-07-22 02:45:48 +0000218 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +0000219 return false;
220
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000221 case OMF_dealloc:
Alp Toker314cc812014-01-25 16:55:45 +0000222 if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
Aaron Ballman41b10ac2014-08-01 13:20:09 +0000223 SourceRange ResultTypeRange = method->getReturnTypeSourceRange();
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000224 if (ResultTypeRange.isInvalid())
Richard Smithf8812672016-12-02 22:38:31 +0000225 Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
Alp Toker314cc812014-01-25 16:55:45 +0000226 << method->getReturnType()
227 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000228 else
Richard Smithf8812672016-12-02 22:38:31 +0000229 Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
Alp Toker314cc812014-01-25 16:55:45 +0000230 << method->getReturnType()
231 << FixItHint::CreateReplacement(ResultTypeRange, "void");
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000232 return true;
233 }
234 return false;
235
John McCall31168b02011-06-15 23:02:42 +0000236 case OMF_init:
237 // If the method doesn't obey the init rules, don't bother annotating it.
John McCalle48f3892013-04-04 01:38:37 +0000238 if (checkInitMethod(method, QualType()))
John McCall31168b02011-06-15 23:02:42 +0000239 return true;
240
Aaron Ballman36a53502014-01-16 13:03:14 +0000241 method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
John McCall31168b02011-06-15 23:02:42 +0000242
243 // Don't add a second copy of this attribute, but otherwise don't
244 // let it be suppressed.
245 if (method->hasAttr<NSReturnsRetainedAttr>())
246 return false;
247 break;
248
249 case OMF_alloc:
250 case OMF_copy:
251 case OMF_mutableCopy:
252 case OMF_new:
253 if (method->hasAttr<NSReturnsRetainedAttr>() ||
254 method->hasAttr<NSReturnsNotRetainedAttr>() ||
255 method->hasAttr<NSReturnsAutoreleasedAttr>())
256 return false;
257 break;
258 }
259
Aaron Ballman36a53502014-01-16 13:03:14 +0000260 method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
John McCall31168b02011-06-15 23:02:42 +0000261 return false;
262}
263
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000264static void DiagnoseObjCImplementedDeprecations(Sema &S, const NamedDecl *ND,
265 SourceLocation ImplLoc) {
266 if (!ND)
267 return;
268 bool IsCategory = false;
Alex Lorenzf4d4cfb2018-05-03 01:12:06 +0000269 StringRef RealizedPlatform;
270 AvailabilityResult Availability = ND->getAvailability(
271 /*Message=*/nullptr, /*EnclosingVersion=*/VersionTuple(),
272 &RealizedPlatform);
Alex Lorenze1088dc2017-07-13 16:37:11 +0000273 if (Availability != AR_Deprecated) {
Eric Christopher7aba9782017-07-14 01:42:57 +0000274 if (isa<ObjCMethodDecl>(ND)) {
Alex Lorenze1088dc2017-07-13 16:37:11 +0000275 if (Availability != AR_Unavailable)
276 return;
Alex Lorenzf4d4cfb2018-05-03 01:12:06 +0000277 if (RealizedPlatform.empty())
278 RealizedPlatform = S.Context.getTargetInfo().getPlatformName();
279 // Warn about implementing unavailable methods, unless the unavailable
280 // is for an app extension.
281 if (RealizedPlatform.endswith("_app_extension"))
282 return;
Alex Lorenze1088dc2017-07-13 16:37:11 +0000283 S.Diag(ImplLoc, diag::warn_unavailable_def);
284 S.Diag(ND->getLocation(), diag::note_method_declared_at)
285 << ND->getDeclName();
286 return;
287 }
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000288 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND)) {
289 if (!CD->getClassInterface()->isDeprecated())
290 return;
291 ND = CD->getClassInterface();
292 IsCategory = true;
293 } else
294 return;
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000295 }
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000296 S.Diag(ImplLoc, diag::warn_deprecated_def)
297 << (isa<ObjCMethodDecl>(ND)
298 ? /*Method*/ 0
299 : isa<ObjCCategoryDecl>(ND) || IsCategory ? /*Category*/ 2
300 : /*Class*/ 1);
301 if (isa<ObjCMethodDecl>(ND))
302 S.Diag(ND->getLocation(), diag::note_method_declared_at)
303 << ND->getDeclName();
304 else
305 S.Diag(ND->getLocation(), diag::note_previous_decl)
306 << (isa<ObjCCategoryDecl>(ND) ? "category" : "class");
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000307}
308
Fariborz Jahanianbd0642f2011-08-31 17:37:55 +0000309/// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
310/// pool.
311void Sema::AddAnyMethodToGlobalPool(Decl *D) {
312 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
313
314 // If we don't have a valid method decl, simply return.
315 if (!MDecl)
316 return;
317 if (MDecl->isInstanceMethod())
318 AddInstanceMethodToGlobalPool(MDecl, true);
319 else
320 AddFactoryMethodToGlobalPool(MDecl, true);
321}
322
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000323/// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
324/// has explicit ownership attribute; false otherwise.
325static bool
326HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
327 QualType T = Param->getType();
328
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000329 if (const PointerType *PT = T->getAs<PointerType>()) {
330 T = PT->getPointeeType();
331 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
332 T = RT->getPointeeType();
333 } else {
334 return true;
335 }
336
337 // If we have a lifetime qualifier, but it's local, we must have
338 // inferred it. So, it is implicit.
339 return !T.getLocalQualifiers().hasObjCLifetime();
340}
341
Fariborz Jahanian18d0a5d2012-08-08 23:41:08 +0000342/// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
343/// and user declared, in the method definition's AST.
344void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000345 assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
John McCall48871652010-08-21 09:40:31 +0000346 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
Fariborz Jahanian577574a2012-07-02 23:37:09 +0000347
Steve Naroff542cd5d2008-07-25 17:57:26 +0000348 // If we don't have a valid method decl, simply return.
349 if (!MDecl)
350 return;
Steve Naroff1d2538c2007-12-18 01:30:32 +0000351
Akira Hatanakaff6c4f32018-04-12 06:01:41 +0000352 QualType ResultType = MDecl->getReturnType();
353 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
354 !MDecl->isInvalidDecl() &&
355 RequireCompleteType(MDecl->getLocation(), ResultType,
356 diag::err_func_def_incomplete_result))
357 MDecl->setInvalidDecl();
358
Chris Lattnerda463fe2007-12-12 07:09:47 +0000359 // Allow all of Sema to see that we are entering a method definition.
Douglas Gregor91f84212008-12-11 16:49:14 +0000360 PushDeclContext(FnBodyScope, MDecl);
Douglas Gregor9a28e842010-03-01 23:15:13 +0000361 PushFunctionScope();
362
Chris Lattnerda463fe2007-12-12 07:09:47 +0000363 // Create Decl objects for each parameter, entrring them in the scope for
364 // binding to their use.
Chris Lattnerda463fe2007-12-12 07:09:47 +0000365
366 // Insert the invisible arguments, self and _cmd!
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000367 MDecl->createImplicitParams(Context, MDecl->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000368
Daniel Dunbar279d1cc2008-08-26 06:07:48 +0000369 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
370 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000371
Reid Kleckner5a115802013-06-24 14:38:26 +0000372 // The ObjC parser requires parameter names so there's no need to check.
David Majnemer59f77922016-06-24 04:05:48 +0000373 CheckParmsForFunctionDef(MDecl->parameters(),
Reid Kleckner5a115802013-06-24 14:38:26 +0000374 /*CheckParameterNames=*/false);
375
Chris Lattner58258242008-04-10 02:22:51 +0000376 // Introduce all of the other parameters into this scope.
David Majnemer59f77922016-06-24 04:05:48 +0000377 for (auto *Param : MDecl->parameters()) {
Fariborz Jahanianb3e87122010-09-17 22:07:07 +0000378 if (!Param->isInvalidDecl() &&
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000379 getLangOpts().ObjCAutoRefCount &&
380 !HasExplicitOwnershipAttr(*this, Param))
381 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
382 Param->getType();
Fariborz Jahaniancd278ff2012-08-30 23:56:02 +0000383
Aaron Ballman43b68be2014-03-07 17:50:17 +0000384 if (Param->getIdentifier())
385 PushOnScopeChains(Param, FnBodyScope);
Fariborz Jahanianb3e87122010-09-17 22:07:07 +0000386 }
John McCall31168b02011-06-15 23:02:42 +0000387
388 // In ARC, disallow definition of retain/release/autorelease/retainCount
David Blaikiebbafb8a2012-03-11 07:00:24 +0000389 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +0000390 switch (MDecl->getMethodFamily()) {
391 case OMF_retain:
392 case OMF_retainCount:
393 case OMF_release:
394 case OMF_autorelease:
395 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
Fariborz Jahanian39d1c422013-05-16 19:08:44 +0000396 << 0 << MDecl->getSelector();
John McCall31168b02011-06-15 23:02:42 +0000397 break;
398
399 case OMF_None:
400 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +0000401 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +0000402 case OMF_alloc:
403 case OMF_init:
404 case OMF_mutableCopy:
405 case OMF_copy:
406 case OMF_new:
407 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +0000408 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +0000409 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +0000410 break;
411 }
412 }
413
Nico Weber715abaf2011-08-22 17:25:57 +0000414 // Warn on deprecated methods under -Wdeprecated-implementations,
415 // and prepare for warning on missing super calls.
416 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
Fariborz Jahanian566fff02012-09-07 23:46:23 +0000417 ObjCMethodDecl *IMD =
418 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
419
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000420 if (IMD) {
421 ObjCImplDecl *ImplDeclOfMethodDef =
422 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
423 ObjCContainerDecl *ContDeclOfMethodDecl =
424 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
Craig Topperc3ec1492014-05-26 06:22:03 +0000425 ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000426 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
427 ImplDeclOfMethodDecl = OID->getImplementation();
Fariborz Jahanianed39e7c2014-03-18 16:25:22 +0000428 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
429 if (CD->IsClassExtension()) {
430 if (ObjCInterfaceDecl *OID = CD->getClassInterface())
431 ImplDeclOfMethodDecl = OID->getImplementation();
432 } else
433 ImplDeclOfMethodDecl = CD->getImplementation();
Fariborz Jahanian19a08bb2014-03-18 00:10:37 +0000434 }
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000435 // No need to issue deprecated warning if deprecated mehod in class/category
436 // is being implemented in its own implementation (no overriding is involved).
Fariborz Jahanianed39e7c2014-03-18 16:25:22 +0000437 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000438 DiagnoseObjCImplementedDeprecations(*this, IMD, MDecl->getLocation());
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000439 }
Nico Weber715abaf2011-08-22 17:25:57 +0000440
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000441 if (MDecl->getMethodFamily() == OMF_init) {
442 if (MDecl->isDesignatedInitializerForTheInterface()) {
443 getCurFunction()->ObjCIsDesignatedInit = true;
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +0000444 getCurFunction()->ObjCWarnForNoDesignatedInitChain =
Craig Topperc3ec1492014-05-26 06:22:03 +0000445 IC->getSuperClass() != nullptr;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000446 } else if (IC->hasDesignatedInitializers()) {
447 getCurFunction()->ObjCIsSecondaryInit = true;
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +0000448 getCurFunction()->ObjCWarnForNoInitDelegation = true;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000449 }
450 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +0000451
Nico Weber1fb82662011-08-28 22:35:17 +0000452 // If this is "dealloc" or "finalize", set some bit here.
Nico Weber715abaf2011-08-22 17:25:57 +0000453 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
454 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
455 // Only do this if the current class actually has a superclass.
Jordan Rosed03d99d2013-03-05 01:27:54 +0000456 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
Jordan Rose2afd6612012-10-19 16:05:26 +0000457 ObjCMethodFamily Family = MDecl->getMethodFamily();
458 if (Family == OMF_dealloc) {
459 if (!(getLangOpts().ObjCAutoRefCount ||
460 getLangOpts().getGC() == LangOptions::GCOnly))
461 getCurFunction()->ObjCShouldCallSuper = true;
462
463 } else if (Family == OMF_finalize) {
464 if (Context.getLangOpts().getGC() != LangOptions::NonGC)
465 getCurFunction()->ObjCShouldCallSuper = true;
466
Fariborz Jahaniance4bbb22013-11-05 00:28:21 +0000467 } else {
Jordan Rose2afd6612012-10-19 16:05:26 +0000468 const ObjCMethodDecl *SuperMethod =
Jordan Rosed03d99d2013-03-05 01:27:54 +0000469 SuperClass->lookupMethod(MDecl->getSelector(),
470 MDecl->isInstanceMethod());
Jordan Rose2afd6612012-10-19 16:05:26 +0000471 getCurFunction()->ObjCShouldCallSuper =
472 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
Fariborz Jahaniand6876b22012-09-10 18:04:25 +0000473 }
Nico Weber1fb82662011-08-28 22:35:17 +0000474 }
Nico Weber715abaf2011-08-22 17:25:57 +0000475 }
Chris Lattnerda463fe2007-12-12 07:09:47 +0000476}
477
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000478namespace {
479
480// Callback to only accept typo corrections that are Objective-C classes.
481// If an ObjCInterfaceDecl* is given to the constructor, then the validation
482// function will reject corrections to that class.
483class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback {
484 public:
Craig Topperc3ec1492014-05-26 06:22:03 +0000485 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000486 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
487 : CurrentIDecl(IDecl) {}
488
Craig Toppere14c0f82014-03-12 04:55:44 +0000489 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000490 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
491 return ID && !declaresSameEntity(ID, CurrentIDecl);
492 }
493
494 private:
495 ObjCInterfaceDecl *CurrentIDecl;
496};
497
Hans Wennborgdcfba332015-10-06 23:40:43 +0000498} // end anonymous namespace
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000499
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +0000500static void diagnoseUseOfProtocols(Sema &TheSema,
501 ObjCContainerDecl *CD,
502 ObjCProtocolDecl *const *ProtoRefs,
503 unsigned NumProtoRefs,
504 const SourceLocation *ProtoLocs) {
505 assert(ProtoRefs);
506 // Diagnose availability in the context of the ObjC container.
507 Sema::ContextRAII SavedContext(TheSema, CD);
508 for (unsigned i = 0; i < NumProtoRefs; ++i) {
Alex Lorenzcdd596f2017-07-07 09:15:29 +0000509 (void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i],
510 /*UnknownObjCClass=*/nullptr,
511 /*ObjCPropertyAccess=*/false,
512 /*AvoidPartialAvailabilityChecks=*/true);
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +0000513 }
514}
515
Douglas Gregore9d95f12015-07-07 03:57:35 +0000516void Sema::
517ActOnSuperClassOfClassInterface(Scope *S,
518 SourceLocation AtInterfaceLoc,
519 ObjCInterfaceDecl *IDecl,
520 IdentifierInfo *ClassName,
521 SourceLocation ClassLoc,
522 IdentifierInfo *SuperName,
523 SourceLocation SuperLoc,
524 ArrayRef<ParsedType> SuperTypeArgs,
525 SourceRange SuperTypeArgsRange) {
526 // Check if a different kind of symbol declared in this scope.
527 NamedDecl *PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
528 LookupOrdinaryName);
529
530 if (!PrevDecl) {
531 // Try to correct for a typo in the superclass name without correcting
532 // to the class we're defining.
533 if (TypoCorrection Corrected = CorrectTypo(
534 DeclarationNameInfo(SuperName, SuperLoc),
535 LookupOrdinaryName, TUScope,
Hans Wennborgdcfba332015-10-06 23:40:43 +0000536 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(IDecl),
Douglas Gregore9d95f12015-07-07 03:57:35 +0000537 CTK_ErrorRecovery)) {
538 diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
539 << SuperName << ClassName);
540 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
541 }
542 }
543
544 if (declaresSameEntity(PrevDecl, IDecl)) {
545 Diag(SuperLoc, diag::err_recursive_superclass)
546 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
547 IDecl->setEndOfDefinitionLoc(ClassLoc);
548 } else {
549 ObjCInterfaceDecl *SuperClassDecl =
550 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
551 QualType SuperClassType;
552
553 // Diagnose classes that inherit from deprecated classes.
554 if (SuperClassDecl) {
555 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
556 SuperClassType = Context.getObjCInterfaceType(SuperClassDecl);
557 }
558
Hans Wennborgdcfba332015-10-06 23:40:43 +0000559 if (PrevDecl && !SuperClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +0000560 // The previous declaration was not a class decl. Check if we have a
561 // typedef. If we do, get the underlying class type.
562 if (const TypedefNameDecl *TDecl =
563 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
564 QualType T = TDecl->getUnderlyingType();
565 if (T->isObjCObjectType()) {
566 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
567 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
568 SuperClassType = Context.getTypeDeclType(TDecl);
569
570 // This handles the following case:
571 // @interface NewI @end
572 // typedef NewI DeprI __attribute__((deprecated("blah")))
573 // @interface SI : DeprI /* warn here */ @end
574 (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
575 }
576 }
577 }
578
579 // This handles the following case:
580 //
581 // typedef int SuperClass;
582 // @interface MyClass : SuperClass {} @end
583 //
584 if (!SuperClassDecl) {
585 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
586 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
587 }
588 }
589
590 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
591 if (!SuperClassDecl)
592 Diag(SuperLoc, diag::err_undef_superclass)
593 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
594 else if (RequireCompleteType(SuperLoc,
595 SuperClassType,
596 diag::err_forward_superclass,
597 SuperClassDecl->getDeclName(),
598 ClassName,
599 SourceRange(AtInterfaceLoc, ClassLoc))) {
Hans Wennborgdcfba332015-10-06 23:40:43 +0000600 SuperClassDecl = nullptr;
Douglas Gregore9d95f12015-07-07 03:57:35 +0000601 SuperClassType = QualType();
602 }
603 }
604
605 if (SuperClassType.isNull()) {
606 assert(!SuperClassDecl && "Failed to set SuperClassType?");
607 return;
608 }
609
610 // Handle type arguments on the superclass.
611 TypeSourceInfo *SuperClassTInfo = nullptr;
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000612 if (!SuperTypeArgs.empty()) {
613 TypeResult fullSuperClassType = actOnObjCTypeArgsAndProtocolQualifiers(
614 S,
615 SuperLoc,
616 CreateParsedType(SuperClassType,
617 nullptr),
618 SuperTypeArgsRange.getBegin(),
619 SuperTypeArgs,
620 SuperTypeArgsRange.getEnd(),
621 SourceLocation(),
622 { },
623 { },
624 SourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +0000625 if (!fullSuperClassType.isUsable())
626 return;
627
628 SuperClassType = GetTypeFromParser(fullSuperClassType.get(),
629 &SuperClassTInfo);
630 }
631
632 if (!SuperClassTInfo) {
633 SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType,
634 SuperLoc);
635 }
636
637 IDecl->setSuperClass(SuperClassTInfo);
638 IDecl->setEndOfDefinitionLoc(SuperClassTInfo->getTypeLoc().getLocEnd());
639 }
640}
641
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000642DeclResult Sema::actOnObjCTypeParam(Scope *S,
643 ObjCTypeParamVariance variance,
644 SourceLocation varianceLoc,
645 unsigned index,
Douglas Gregore83b9562015-07-07 03:57:53 +0000646 IdentifierInfo *paramName,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000647 SourceLocation paramLoc,
648 SourceLocation colonLoc,
649 ParsedType parsedTypeBound) {
650 // If there was an explicitly-provided type bound, check it.
651 TypeSourceInfo *typeBoundInfo = nullptr;
652 if (parsedTypeBound) {
653 // The type bound can be any Objective-C pointer type.
654 QualType typeBound = GetTypeFromParser(parsedTypeBound, &typeBoundInfo);
655 if (typeBound->isObjCObjectPointerType()) {
656 // okay
657 } else if (typeBound->isObjCObjectType()) {
658 // The user forgot the * on an Objective-C pointer type, e.g.,
659 // "T : NSView".
Craig Topper07fa1762015-11-15 02:31:46 +0000660 SourceLocation starLoc = getLocForEndOfToken(
Douglas Gregor85f3f952015-07-07 03:57:15 +0000661 typeBoundInfo->getTypeLoc().getEndLoc());
662 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
663 diag::err_objc_type_param_bound_missing_pointer)
664 << typeBound << paramName
665 << FixItHint::CreateInsertion(starLoc, " *");
666
667 // Create a new type location builder so we can update the type
668 // location information we have.
669 TypeLocBuilder builder;
670 builder.pushFullCopy(typeBoundInfo->getTypeLoc());
671
672 // Create the Objective-C pointer type.
673 typeBound = Context.getObjCObjectPointerType(typeBound);
674 ObjCObjectPointerTypeLoc newT
675 = builder.push<ObjCObjectPointerTypeLoc>(typeBound);
676 newT.setStarLoc(starLoc);
677
678 // Form the new type source information.
679 typeBoundInfo = builder.getTypeSourceInfo(Context, typeBound);
680 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +0000681 // Not a valid type bound.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000682 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
683 diag::err_objc_type_param_bound_nonobject)
684 << typeBound << paramName;
685
686 // Forget the bound; we'll default to id later.
687 typeBoundInfo = nullptr;
688 }
Douglas Gregore83b9562015-07-07 03:57:53 +0000689
John McCall69975252015-09-23 22:14:21 +0000690 // Type bounds cannot have qualifiers (even indirectly) or explicit
691 // nullability.
Douglas Gregore83b9562015-07-07 03:57:53 +0000692 if (typeBoundInfo) {
John McCall69975252015-09-23 22:14:21 +0000693 QualType typeBound = typeBoundInfo->getType();
694 TypeLoc qual = typeBoundInfo->getTypeLoc().findExplicitQualifierLoc();
695 if (qual || typeBound.hasQualifiers()) {
696 bool diagnosed = false;
697 SourceRange rangeToRemove;
698 if (qual) {
699 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
700 rangeToRemove = attr.getLocalSourceRange();
701 if (attr.getTypePtr()->getImmediateNullability()) {
702 Diag(attr.getLocStart(),
703 diag::err_objc_type_param_bound_explicit_nullability)
704 << paramName << typeBound
705 << FixItHint::CreateRemoval(rangeToRemove);
706 diagnosed = true;
707 }
708 }
709 }
710
711 if (!diagnosed) {
712 Diag(qual ? qual.getLocStart()
713 : typeBoundInfo->getTypeLoc().getLocStart(),
714 diag::err_objc_type_param_bound_qualified)
715 << paramName << typeBound << typeBound.getQualifiers().getAsString()
716 << FixItHint::CreateRemoval(rangeToRemove);
717 }
718
719 // If the type bound has qualifiers other than CVR, we need to strip
720 // them or we'll probably assert later when trying to apply new
721 // qualifiers.
722 Qualifiers quals = typeBound.getQualifiers();
723 quals.removeCVRQualifiers();
724 if (!quals.empty()) {
725 typeBoundInfo =
726 Context.getTrivialTypeSourceInfo(typeBound.getUnqualifiedType());
727 }
Douglas Gregore83b9562015-07-07 03:57:53 +0000728 }
729 }
Douglas Gregor85f3f952015-07-07 03:57:15 +0000730 }
731
732 // If there was no explicit type bound (or we removed it due to an error),
733 // use 'id' instead.
734 if (!typeBoundInfo) {
735 colonLoc = SourceLocation();
736 typeBoundInfo = Context.getTrivialTypeSourceInfo(Context.getObjCIdType());
737 }
738
739 // Create the type parameter.
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000740 return ObjCTypeParamDecl::Create(Context, CurContext, variance, varianceLoc,
741 index, paramLoc, paramName, colonLoc,
742 typeBoundInfo);
Douglas Gregor85f3f952015-07-07 03:57:15 +0000743}
744
745ObjCTypeParamList *Sema::actOnObjCTypeParamList(Scope *S,
746 SourceLocation lAngleLoc,
747 ArrayRef<Decl *> typeParamsIn,
748 SourceLocation rAngleLoc) {
749 // We know that the array only contains Objective-C type parameters.
750 ArrayRef<ObjCTypeParamDecl *>
751 typeParams(
752 reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()),
753 typeParamsIn.size());
754
755 // Diagnose redeclarations of type parameters.
756 // We do this now because Objective-C type parameters aren't pushed into
757 // scope until later (after the instance variable block), but we want the
758 // diagnostics to occur right after we parse the type parameter list.
759 llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams;
760 for (auto typeParam : typeParams) {
761 auto known = knownParams.find(typeParam->getIdentifier());
762 if (known != knownParams.end()) {
763 Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl)
764 << typeParam->getIdentifier()
765 << SourceRange(known->second->getLocation());
766
767 typeParam->setInvalidDecl();
768 } else {
769 knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam));
770
771 // Push the type parameter into scope.
772 PushOnScopeChains(typeParam, S, /*AddToContext=*/false);
773 }
774 }
775
776 // Create the parameter list.
777 return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc);
778}
779
780void Sema::popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList) {
781 for (auto typeParam : *typeParamList) {
782 if (!typeParam->isInvalidDecl()) {
783 S->RemoveDecl(typeParam);
784 IdResolver.RemoveDecl(typeParam);
785 }
786 }
787}
788
789namespace {
790 /// The context in which an Objective-C type parameter list occurs, for use
791 /// in diagnostics.
792 enum class TypeParamListContext {
793 ForwardDeclaration,
794 Definition,
795 Category,
796 Extension
797 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000798} // end anonymous namespace
Douglas Gregor85f3f952015-07-07 03:57:15 +0000799
800/// Check consistency between two Objective-C type parameter lists, e.g.,
NAKAMURA Takumi4c3ab452015-07-08 02:35:56 +0000801/// between a category/extension and an \@interface or between an \@class and an
802/// \@interface.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000803static bool checkTypeParamListConsistency(Sema &S,
804 ObjCTypeParamList *prevTypeParams,
805 ObjCTypeParamList *newTypeParams,
806 TypeParamListContext newContext) {
807 // If the sizes don't match, complain about that.
808 if (prevTypeParams->size() != newTypeParams->size()) {
809 SourceLocation diagLoc;
810 if (newTypeParams->size() > prevTypeParams->size()) {
811 diagLoc = newTypeParams->begin()[prevTypeParams->size()]->getLocation();
812 } else {
Craig Topper07fa1762015-11-15 02:31:46 +0000813 diagLoc = S.getLocForEndOfToken(newTypeParams->back()->getLocEnd());
Douglas Gregor85f3f952015-07-07 03:57:15 +0000814 }
815
816 S.Diag(diagLoc, diag::err_objc_type_param_arity_mismatch)
817 << static_cast<unsigned>(newContext)
818 << (newTypeParams->size() > prevTypeParams->size())
819 << prevTypeParams->size()
820 << newTypeParams->size();
821
822 return true;
823 }
824
825 // Match up the type parameters.
826 for (unsigned i = 0, n = prevTypeParams->size(); i != n; ++i) {
827 ObjCTypeParamDecl *prevTypeParam = prevTypeParams->begin()[i];
828 ObjCTypeParamDecl *newTypeParam = newTypeParams->begin()[i];
829
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000830 // Check for consistency of the variance.
831 if (newTypeParam->getVariance() != prevTypeParam->getVariance()) {
832 if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant &&
833 newContext != TypeParamListContext::Definition) {
834 // When the new type parameter is invariant and is not part
835 // of the definition, just propagate the variance.
836 newTypeParam->setVariance(prevTypeParam->getVariance());
837 } else if (prevTypeParam->getVariance()
838 == ObjCTypeParamVariance::Invariant &&
839 !(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) &&
840 cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext())
841 ->getDefinition() == prevTypeParam->getDeclContext())) {
842 // When the old parameter is invariant and was not part of the
843 // definition, just ignore the difference because it doesn't
844 // matter.
845 } else {
846 {
847 // Diagnose the conflict and update the second declaration.
848 SourceLocation diagLoc = newTypeParam->getVarianceLoc();
849 if (diagLoc.isInvalid())
850 diagLoc = newTypeParam->getLocStart();
851
852 auto diag = S.Diag(diagLoc,
853 diag::err_objc_type_param_variance_conflict)
854 << static_cast<unsigned>(newTypeParam->getVariance())
855 << newTypeParam->getDeclName()
856 << static_cast<unsigned>(prevTypeParam->getVariance())
857 << prevTypeParam->getDeclName();
858 switch (prevTypeParam->getVariance()) {
859 case ObjCTypeParamVariance::Invariant:
860 diag << FixItHint::CreateRemoval(newTypeParam->getVarianceLoc());
861 break;
862
863 case ObjCTypeParamVariance::Covariant:
864 case ObjCTypeParamVariance::Contravariant: {
865 StringRef newVarianceStr
866 = prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant
867 ? "__covariant"
868 : "__contravariant";
869 if (newTypeParam->getVariance()
870 == ObjCTypeParamVariance::Invariant) {
871 diag << FixItHint::CreateInsertion(newTypeParam->getLocStart(),
872 (newVarianceStr + " ").str());
873 } else {
874 diag << FixItHint::CreateReplacement(newTypeParam->getVarianceLoc(),
875 newVarianceStr);
876 }
877 }
878 }
879 }
880
881 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
882 << prevTypeParam->getDeclName();
883
884 // Override the variance.
885 newTypeParam->setVariance(prevTypeParam->getVariance());
886 }
887 }
888
Douglas Gregor85f3f952015-07-07 03:57:15 +0000889 // If the bound types match, there's nothing to do.
890 if (S.Context.hasSameType(prevTypeParam->getUnderlyingType(),
891 newTypeParam->getUnderlyingType()))
892 continue;
893
894 // If the new type parameter's bound was explicit, complain about it being
895 // different from the original.
896 if (newTypeParam->hasExplicitBound()) {
897 SourceRange newBoundRange = newTypeParam->getTypeSourceInfo()
898 ->getTypeLoc().getSourceRange();
899 S.Diag(newBoundRange.getBegin(), diag::err_objc_type_param_bound_conflict)
900 << newTypeParam->getUnderlyingType()
901 << newTypeParam->getDeclName()
902 << prevTypeParam->hasExplicitBound()
903 << prevTypeParam->getUnderlyingType()
904 << (newTypeParam->getDeclName() == prevTypeParam->getDeclName())
905 << prevTypeParam->getDeclName()
906 << FixItHint::CreateReplacement(
907 newBoundRange,
908 prevTypeParam->getUnderlyingType().getAsString(
909 S.Context.getPrintingPolicy()));
910
911 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
912 << prevTypeParam->getDeclName();
913
914 // Override the new type parameter's bound type with the previous type,
915 // so that it's consistent.
916 newTypeParam->setTypeSourceInfo(
917 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
918 continue;
919 }
920
921 // The new type parameter got the implicit bound of 'id'. That's okay for
922 // categories and extensions (overwrite it later), but not for forward
923 // declarations and @interfaces, because those must be standalone.
924 if (newContext == TypeParamListContext::ForwardDeclaration ||
925 newContext == TypeParamListContext::Definition) {
926 // Diagnose this problem for forward declarations and definitions.
927 SourceLocation insertionLoc
Craig Topper07fa1762015-11-15 02:31:46 +0000928 = S.getLocForEndOfToken(newTypeParam->getLocation());
Douglas Gregor85f3f952015-07-07 03:57:15 +0000929 std::string newCode
930 = " : " + prevTypeParam->getUnderlyingType().getAsString(
931 S.Context.getPrintingPolicy());
932 S.Diag(newTypeParam->getLocation(),
933 diag::err_objc_type_param_bound_missing)
934 << prevTypeParam->getUnderlyingType()
935 << newTypeParam->getDeclName()
936 << (newContext == TypeParamListContext::ForwardDeclaration)
937 << FixItHint::CreateInsertion(insertionLoc, newCode);
938
939 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
940 << prevTypeParam->getDeclName();
941 }
942
943 // Update the new type parameter's bound to match the previous one.
944 newTypeParam->setTypeSourceInfo(
945 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
946 }
947
948 return false;
949}
950
John McCall48871652010-08-21 09:40:31 +0000951Decl *Sema::
Douglas Gregore9d95f12015-07-07 03:57:35 +0000952ActOnStartClassInterface(Scope *S, SourceLocation AtInterfaceLoc,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000953 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000954 ObjCTypeParamList *typeParamList,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000955 IdentifierInfo *SuperName, SourceLocation SuperLoc,
Douglas Gregore9d95f12015-07-07 03:57:35 +0000956 ArrayRef<ParsedType> SuperTypeArgs,
957 SourceRange SuperTypeArgsRange,
John McCall48871652010-08-21 09:40:31 +0000958 Decl * const *ProtoRefs, unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +0000959 const SourceLocation *ProtoLocs,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000960 SourceLocation EndProtoLoc, AttributeList *AttrList) {
Chris Lattnerda463fe2007-12-12 07:09:47 +0000961 assert(ClassName && "Missing class identifier");
Mike Stump11289f42009-09-09 15:08:12 +0000962
Chris Lattnerda463fe2007-12-12 07:09:47 +0000963 // Check for another declaration kind with the same name.
Richard Smithbecb92d2017-10-10 22:33:17 +0000964 NamedDecl *PrevDecl =
965 LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
966 forRedeclarationInCurContext());
Douglas Gregor5101c242008-12-05 18:15:24 +0000967
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000968 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +0000969 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Chris Lattner0369c572008-11-23 23:12:31 +0000970 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +0000971 }
Mike Stump11289f42009-09-09 15:08:12 +0000972
Douglas Gregordc9166c2011-12-15 20:29:51 +0000973 // Create a declaration to describe this @interface.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +0000974 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidisdd710632013-06-18 21:26:33 +0000975
976 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
977 // A previous decl with a different name is because of
978 // @compatibility_alias, for example:
979 // \code
980 // @class NewImage;
981 // @compatibility_alias OldImage NewImage;
982 // \endcode
983 // A lookup for 'OldImage' will return the 'NewImage' decl.
984 //
985 // In such a case use the real declaration name, instead of the alias one,
986 // otherwise we will break IdentifierResolver and redecls-chain invariants.
987 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
988 // has been aliased.
989 ClassName = PrevIDecl->getIdentifier();
990 }
991
Douglas Gregor85f3f952015-07-07 03:57:15 +0000992 // If there was a forward declaration with type parameters, check
993 // for consistency.
994 if (PrevIDecl) {
995 if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) {
996 if (typeParamList) {
997 // Both have type parameter lists; check for consistency.
998 if (checkTypeParamListConsistency(*this, prevTypeParamList,
999 typeParamList,
1000 TypeParamListContext::Definition)) {
1001 typeParamList = nullptr;
1002 }
1003 } else {
1004 Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first)
1005 << ClassName;
1006 Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl)
1007 << ClassName;
1008
1009 // Clone the type parameter list.
1010 SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams;
1011 for (auto typeParam : *prevTypeParamList) {
1012 clonedTypeParams.push_back(
1013 ObjCTypeParamDecl::Create(
1014 Context,
1015 CurContext,
Douglas Gregor1ac1b632015-07-07 03:58:54 +00001016 typeParam->getVariance(),
1017 SourceLocation(),
Douglas Gregore83b9562015-07-07 03:57:53 +00001018 typeParam->getIndex(),
Douglas Gregor85f3f952015-07-07 03:57:15 +00001019 SourceLocation(),
1020 typeParam->getIdentifier(),
1021 SourceLocation(),
1022 Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType())));
1023 }
1024
1025 typeParamList = ObjCTypeParamList::create(Context,
1026 SourceLocation(),
1027 clonedTypeParams,
1028 SourceLocation());
1029 }
1030 }
1031 }
1032
Douglas Gregordc9166c2011-12-15 20:29:51 +00001033 ObjCInterfaceDecl *IDecl
1034 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001035 typeParamList, PrevIDecl, ClassLoc);
Douglas Gregordc9166c2011-12-15 20:29:51 +00001036 if (PrevIDecl) {
1037 // Class already seen. Was it a definition?
1038 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
1039 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
1040 << PrevIDecl->getDeclName();
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001041 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregordc9166c2011-12-15 20:29:51 +00001042 IDecl->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00001043 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001044 }
Douglas Gregordc9166c2011-12-15 20:29:51 +00001045
1046 if (AttrList)
1047 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001048 AddPragmaAttributes(TUScope, IDecl);
Douglas Gregordc9166c2011-12-15 20:29:51 +00001049 PushOnScopeChains(IDecl, TUScope);
Mike Stump11289f42009-09-09 15:08:12 +00001050
Douglas Gregordc9166c2011-12-15 20:29:51 +00001051 // Start the definition of this class. If we're in a redefinition case, there
1052 // may already be a definition, so we'll end up adding to it.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001053 if (!IDecl->hasDefinition())
1054 IDecl->startDefinition();
1055
Chris Lattnerda463fe2007-12-12 07:09:47 +00001056 if (SuperName) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001057 // Diagnose availability in the context of the @interface.
1058 ContextRAII SavedContext(*this, IDecl);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001059
Douglas Gregore9d95f12015-07-07 03:57:35 +00001060 ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl,
1061 ClassName, ClassLoc,
1062 SuperName, SuperLoc, SuperTypeArgs,
1063 SuperTypeArgsRange);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001064 } else { // we have a root class.
Douglas Gregor16408322011-12-15 22:34:59 +00001065 IDecl->setEndOfDefinitionLoc(ClassLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001066 }
Mike Stump11289f42009-09-09 15:08:12 +00001067
Sebastian Redle7c1fe62010-08-13 00:28:03 +00001068 // Check then save referenced protocols.
Chris Lattnerdf59f5a2008-07-26 04:13:19 +00001069 if (NumProtoRefs) {
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001070 diagnoseUseOfProtocols(*this, IDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1071 NumProtoRefs, ProtoLocs);
Roman Divackye6377112012-09-06 15:59:27 +00001072 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001073 ProtoLocs, Context);
Douglas Gregor16408322011-12-15 22:34:59 +00001074 IDecl->setEndOfDefinitionLoc(EndProtoLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001075 }
Mike Stump11289f42009-09-09 15:08:12 +00001076
Anders Carlssona6b508a2008-11-04 16:57:32 +00001077 CheckObjCDeclScope(IDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001078 return ActOnObjCContainerStartDefinition(IDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001079}
1080
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001081/// ActOnTypedefedProtocols - this action finds protocol list as part of the
1082/// typedef'ed use for a qualified super class and adds them to the list
1083/// of the protocols.
1084void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
Argyrios Kyrtzidisf95a0002016-11-09 02:47:07 +00001085 SmallVectorImpl<SourceLocation> &ProtocolLocs,
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001086 IdentifierInfo *SuperName,
1087 SourceLocation SuperLoc) {
1088 if (!SuperName)
1089 return;
1090 NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
1091 LookupOrdinaryName);
1092 if (!IDecl)
1093 return;
1094
1095 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
1096 QualType T = TDecl->getUnderlyingType();
1097 if (T->isObjCObjectType())
Argyrios Kyrtzidisf95a0002016-11-09 02:47:07 +00001098 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>()) {
Benjamin Kramerf9890422015-02-17 16:48:30 +00001099 ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
Argyrios Kyrtzidisf95a0002016-11-09 02:47:07 +00001100 // FIXME: Consider whether this should be an invalid loc since the loc
1101 // is not actually pointing to a protocol name reference but to the
1102 // typedef reference. Note that the base class name loc is also pointing
1103 // at the typedef.
1104 ProtocolLocs.append(OPT->getNumProtocols(), SuperLoc);
1105 }
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001106 }
1107}
1108
Richard Smithac4e36d2012-08-08 23:32:13 +00001109/// ActOnCompatibilityAlias - this action is called after complete parsing of
James Dennett634962f2012-06-14 21:40:34 +00001110/// a \@compatibility_alias declaration. It sets up the alias relationships.
Richard Smithac4e36d2012-08-08 23:32:13 +00001111Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
1112 IdentifierInfo *AliasName,
1113 SourceLocation AliasLocation,
1114 IdentifierInfo *ClassName,
1115 SourceLocation ClassLocation) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00001116 // Look for previous declaration of alias name
Richard Smithbecb92d2017-10-10 22:33:17 +00001117 NamedDecl *ADecl =
1118 LookupSingleName(TUScope, AliasName, AliasLocation, LookupOrdinaryName,
1119 forRedeclarationInCurContext());
Chris Lattnerda463fe2007-12-12 07:09:47 +00001120 if (ADecl) {
Eli Friedmanfd6b3f82013-06-21 01:49:53 +00001121 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
Chris Lattnerd0685032008-11-23 23:20:13 +00001122 Diag(ADecl->getLocation(), diag::note_previous_declaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001123 return nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001124 }
1125 // Check for class declaration
Richard Smithbecb92d2017-10-10 22:33:17 +00001126 NamedDecl *CDeclU =
1127 LookupSingleName(TUScope, ClassName, ClassLocation, LookupOrdinaryName,
1128 forRedeclarationInCurContext());
Richard Smithdda56e42011-04-15 14:24:37 +00001129 if (const TypedefNameDecl *TDecl =
1130 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001131 QualType T = TDecl->getUnderlyingType();
John McCall8b07ec22010-05-15 11:32:37 +00001132 if (T->isObjCObjectType()) {
1133 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001134 ClassName = IDecl->getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001135 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
Richard Smithbecb92d2017-10-10 22:33:17 +00001136 LookupOrdinaryName,
1137 forRedeclarationInCurContext());
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001138 }
1139 }
1140 }
Chris Lattner219b3e92008-03-16 21:17:37 +00001141 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
Craig Topperc3ec1492014-05-26 06:22:03 +00001142 if (!CDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001143 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
Chris Lattner219b3e92008-03-16 21:17:37 +00001144 if (CDeclU)
Chris Lattnerd0685032008-11-23 23:20:13 +00001145 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001146 return nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001147 }
Mike Stump11289f42009-09-09 15:08:12 +00001148
Chris Lattner219b3e92008-03-16 21:17:37 +00001149 // Everything checked out, instantiate a new alias declaration AST.
Mike Stump11289f42009-09-09 15:08:12 +00001150 ObjCCompatibleAliasDecl *AliasDecl =
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001151 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001152
Anders Carlssona6b508a2008-11-04 16:57:32 +00001153 if (!CheckObjCDeclScope(AliasDecl))
Douglas Gregor38feed82009-04-24 02:57:34 +00001154 PushOnScopeChains(AliasDecl, TUScope);
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001155
John McCall48871652010-08-21 09:40:31 +00001156 return AliasDecl;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001157}
1158
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001159bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
Steve Naroff41d09ad2009-03-05 15:22:01 +00001160 IdentifierInfo *PName,
1161 SourceLocation &Ploc, SourceLocation PrevLoc,
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001162 const ObjCList<ObjCProtocolDecl> &PList) {
1163
1164 bool res = false;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001165 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
1166 E = PList.end(); I != E; ++I) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001167 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
1168 Ploc)) {
Steve Naroff41d09ad2009-03-05 15:22:01 +00001169 if (PDecl->getIdentifier() == PName) {
1170 Diag(Ploc, diag::err_protocol_has_circular_dependency);
1171 Diag(PrevLoc, diag::note_previous_definition);
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001172 res = true;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001173 }
Douglas Gregore6e48b12012-01-01 19:29:29 +00001174
1175 if (!PDecl->hasDefinition())
1176 continue;
1177
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001178 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
1179 PDecl->getLocation(), PDecl->getReferencedProtocols()))
1180 res = true;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001181 }
1182 }
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001183 return res;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001184}
1185
John McCall48871652010-08-21 09:40:31 +00001186Decl *
Chris Lattner3bbae002008-07-26 04:03:38 +00001187Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
1188 IdentifierInfo *ProtocolName,
1189 SourceLocation ProtocolLoc,
John McCall48871652010-08-21 09:40:31 +00001190 Decl * const *ProtoRefs,
Chris Lattner3bbae002008-07-26 04:03:38 +00001191 unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001192 const SourceLocation *ProtoLocs,
Daniel Dunbar26e2ab42008-09-26 04:48:09 +00001193 SourceLocation EndProtoLoc,
1194 AttributeList *AttrList) {
Fariborz Jahaniancadf7c52011-05-12 22:04:39 +00001195 bool err = false;
Daniel Dunbar26e2ab42008-09-26 04:48:09 +00001196 // FIXME: Deal with AttrList.
Chris Lattnerda463fe2007-12-12 07:09:47 +00001197 assert(ProtocolName && "Missing protocol identifier");
Douglas Gregor32c17572012-01-01 20:30:41 +00001198 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
Richard Smithbecb92d2017-10-10 22:33:17 +00001199 forRedeclarationInCurContext());
Craig Topperc3ec1492014-05-26 06:22:03 +00001200 ObjCProtocolDecl *PDecl = nullptr;
1201 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
Douglas Gregor32c17572012-01-01 20:30:41 +00001202 // If we already have a definition, complain.
1203 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
1204 Diag(Def->getLocation(), diag::note_previous_definition);
Mike Stump11289f42009-09-09 15:08:12 +00001205
Douglas Gregor32c17572012-01-01 20:30:41 +00001206 // Create a new protocol that is completely distinct from previous
1207 // declarations, and do not make this protocol available for name lookup.
1208 // That way, we'll end up completely ignoring the duplicate.
1209 // FIXME: Can we turn this into an error?
1210 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
1211 ProtocolLoc, AtProtoInterfaceLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +00001212 /*PrevDecl=*/nullptr);
Douglas Gregor32c17572012-01-01 20:30:41 +00001213 PDecl->startDefinition();
1214 } else {
1215 if (PrevDecl) {
1216 // Check for circular dependencies among protocol declarations. This can
1217 // only happen if this protocol was forward-declared.
Argyrios Kyrtzidis95dfc122011-11-13 22:08:30 +00001218 ObjCList<ObjCProtocolDecl> PList;
1219 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
1220 err = CheckForwardProtocolDeclarationForCircularDependency(
Douglas Gregor32c17572012-01-01 20:30:41 +00001221 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
Argyrios Kyrtzidis95dfc122011-11-13 22:08:30 +00001222 }
Douglas Gregor32c17572012-01-01 20:30:41 +00001223
1224 // Create the new declaration.
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001225 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
Argyrios Kyrtzidis1f4bee52011-10-17 19:48:06 +00001226 ProtocolLoc, AtProtoInterfaceLoc,
Douglas Gregor05a1f4d2012-01-01 22:06:18 +00001227 /*PrevDecl=*/PrevDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +00001228
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001229 PushOnScopeChains(PDecl, TUScope);
Douglas Gregore6e48b12012-01-01 19:29:29 +00001230 PDecl->startDefinition();
Chris Lattnerf87ca0a2008-03-16 01:23:04 +00001231 }
Douglas Gregore6e48b12012-01-01 19:29:29 +00001232
Fariborz Jahanian1470e932008-12-17 01:07:27 +00001233 if (AttrList)
Douglas Gregor758a8692009-06-17 21:51:59 +00001234 ProcessDeclAttributeList(TUScope, PDecl, AttrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001235 AddPragmaAttributes(TUScope, PDecl);
1236
Douglas Gregor32c17572012-01-01 20:30:41 +00001237 // Merge attributes from previous declarations.
1238 if (PrevDecl)
1239 mergeDeclAttributes(PDecl, PrevDecl);
1240
Fariborz Jahaniancadf7c52011-05-12 22:04:39 +00001241 if (!err && NumProtoRefs ) {
Chris Lattneracc04a92008-03-16 20:19:15 +00001242 /// Check then save referenced protocols.
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001243 diagnoseUseOfProtocols(*this, PDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1244 NumProtoRefs, ProtoLocs);
Roman Divackye6377112012-09-06 15:59:27 +00001245 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001246 ProtoLocs, Context);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001247 }
Mike Stump11289f42009-09-09 15:08:12 +00001248
1249 CheckObjCDeclScope(PDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001250 return ActOnObjCContainerStartDefinition(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001251}
1252
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001253static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
1254 ObjCProtocolDecl *&UndefinedProtocol) {
1255 if (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()) {
1256 UndefinedProtocol = PDecl;
1257 return true;
1258 }
1259
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001260 for (auto *PI : PDecl->protocols())
1261 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
1262 UndefinedProtocol = PI;
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001263 return true;
1264 }
1265 return false;
1266}
1267
Chris Lattnerda463fe2007-12-12 07:09:47 +00001268/// FindProtocolDeclaration - This routine looks up protocols and
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00001269/// issues an error if they are not declared. It returns list of
1270/// protocol declarations in its 'Protocols' argument.
Chris Lattnerda463fe2007-12-12 07:09:47 +00001271void
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001272Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
Craig Toppera9247eb2015-10-22 04:59:56 +00001273 ArrayRef<IdentifierLocPair> ProtocolId,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001274 SmallVectorImpl<Decl *> &Protocols) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001275 for (const IdentifierLocPair &Pair : ProtocolId) {
1276 ObjCProtocolDecl *PDecl = LookupProtocol(Pair.first, Pair.second);
Chris Lattner9c1842b2008-07-26 03:47:43 +00001277 if (!PDecl) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001278 TypoCorrection Corrected = CorrectTypo(
Craig Toppera9247eb2015-10-22 04:59:56 +00001279 DeclarationNameInfo(Pair.first, Pair.second),
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001280 LookupObjCProtocolName, TUScope, nullptr,
1281 llvm::make_unique<DeclFilterCCC<ObjCProtocolDecl>>(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001282 CTK_ErrorRecovery);
Richard Smithf9b15102013-08-17 00:46:16 +00001283 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
1284 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
Craig Toppera9247eb2015-10-22 04:59:56 +00001285 << Pair.first);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001286 }
1287
1288 if (!PDecl) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001289 Diag(Pair.second, diag::err_undeclared_protocol) << Pair.first;
Chris Lattner9c1842b2008-07-26 03:47:43 +00001290 continue;
1291 }
Fariborz Jahanianada44a22013-04-09 17:52:29 +00001292 // If this is a forward protocol declaration, get its definition.
1293 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
1294 PDecl = PDecl->getDefinition();
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001295
1296 // For an objc container, delay protocol reference checking until after we
1297 // can set the objc decl as the availability context, otherwise check now.
1298 if (!ForObjCContainer) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001299 (void)DiagnoseUseOfDecl(PDecl, Pair.second);
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001300 }
Chris Lattner9c1842b2008-07-26 03:47:43 +00001301
1302 // If this is a forward declaration and we are supposed to warn in this
1303 // case, do it.
Douglas Gregoreed49792013-01-17 00:38:46 +00001304 // FIXME: Recover nicely in the hidden case.
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001305 ObjCProtocolDecl *UndefinedProtocol;
1306
Douglas Gregoreed49792013-01-17 00:38:46 +00001307 if (WarnOnDeclarations &&
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001308 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001309 Diag(Pair.second, diag::warn_undef_protocolref) << Pair.first;
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001310 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
1311 << UndefinedProtocol;
1312 }
John McCall48871652010-08-21 09:40:31 +00001313 Protocols.push_back(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001314 }
1315}
1316
Benjamin Kramer8b851d02015-07-13 20:42:13 +00001317namespace {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001318// Callback to only accept typo corrections that are either
1319// Objective-C protocols or valid Objective-C type arguments.
1320class ObjCTypeArgOrProtocolValidatorCCC : public CorrectionCandidateCallback {
1321 ASTContext &Context;
1322 Sema::LookupNameKind LookupKind;
1323 public:
1324 ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context,
1325 Sema::LookupNameKind lookupKind)
1326 : Context(context), LookupKind(lookupKind) { }
1327
1328 bool ValidateCandidate(const TypoCorrection &candidate) override {
1329 // If we're allowed to find protocols and we have a protocol, accept it.
1330 if (LookupKind != Sema::LookupOrdinaryName) {
1331 if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>())
1332 return true;
1333 }
1334
1335 // If we're allowed to find type names and we have one, accept it.
1336 if (LookupKind != Sema::LookupObjCProtocolName) {
1337 // If we have a type declaration, we might accept this result.
1338 if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) {
1339 // If we found a tag declaration outside of C++, skip it. This
1340 // can happy because we look for any name when there is no
1341 // bias to protocol or type names.
1342 if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus)
1343 return false;
1344
1345 // Make sure the type is something we would accept as a type
1346 // argument.
1347 auto type = Context.getTypeDeclType(typeDecl);
1348 if (type->isObjCObjectPointerType() ||
1349 type->isBlockPointerType() ||
1350 type->isDependentType() ||
1351 type->isObjCObjectType())
1352 return true;
1353
1354 return false;
1355 }
1356
1357 // If we have an Objective-C class type, accept it; there will
1358 // be another fix to add the '*'.
1359 if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>())
1360 return true;
1361
1362 return false;
1363 }
1364
1365 return false;
1366 }
1367};
Benjamin Kramer8b851d02015-07-13 20:42:13 +00001368} // end anonymous namespace
Douglas Gregore9d95f12015-07-07 03:57:35 +00001369
Bruno Cardoso Lopesc54768f2016-04-13 20:59:07 +00001370void Sema::DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
1371 SourceLocation ProtocolLoc,
1372 IdentifierInfo *TypeArgId,
1373 SourceLocation TypeArgLoc,
1374 bool SelectProtocolFirst) {
1375 Diag(TypeArgLoc, diag::err_objc_type_args_and_protocols)
1376 << SelectProtocolFirst << TypeArgId << ProtocolId
1377 << SourceRange(ProtocolLoc);
1378}
1379
Douglas Gregore9d95f12015-07-07 03:57:35 +00001380void Sema::actOnObjCTypeArgsOrProtocolQualifiers(
1381 Scope *S,
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001382 ParsedType baseType,
Douglas Gregore9d95f12015-07-07 03:57:35 +00001383 SourceLocation lAngleLoc,
1384 ArrayRef<IdentifierInfo *> identifiers,
1385 ArrayRef<SourceLocation> identifierLocs,
1386 SourceLocation rAngleLoc,
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001387 SourceLocation &typeArgsLAngleLoc,
1388 SmallVectorImpl<ParsedType> &typeArgs,
1389 SourceLocation &typeArgsRAngleLoc,
1390 SourceLocation &protocolLAngleLoc,
1391 SmallVectorImpl<Decl *> &protocols,
1392 SourceLocation &protocolRAngleLoc,
Douglas Gregore9d95f12015-07-07 03:57:35 +00001393 bool warnOnIncompleteProtocols) {
1394 // Local function that updates the declaration specifiers with
1395 // protocol information.
Douglas Gregore9d95f12015-07-07 03:57:35 +00001396 unsigned numProtocolsResolved = 0;
1397 auto resolvedAsProtocols = [&] {
1398 assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols");
1399
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001400 // Determine whether the base type is a parameterized class, in
1401 // which case we want to warn about typos such as
1402 // "NSArray<NSObject>" (that should be NSArray<NSObject *>).
1403 ObjCInterfaceDecl *baseClass = nullptr;
1404 QualType base = GetTypeFromParser(baseType, nullptr);
1405 bool allAreTypeNames = false;
1406 SourceLocation firstClassNameLoc;
1407 if (!base.isNull()) {
1408 if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) {
1409 baseClass = objcObjectType->getInterface();
1410 if (baseClass) {
1411 if (auto typeParams = baseClass->getTypeParamList()) {
1412 if (typeParams->size() == numProtocolsResolved) {
1413 // Note that we should be looking for type names, too.
1414 allAreTypeNames = true;
1415 }
1416 }
1417 }
1418 }
1419 }
1420
Douglas Gregore9d95f12015-07-07 03:57:35 +00001421 for (unsigned i = 0, n = protocols.size(); i != n; ++i) {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001422 ObjCProtocolDecl *&proto
1423 = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001424 // For an objc container, delay protocol reference checking until after we
1425 // can set the objc decl as the availability context, otherwise check now.
1426 if (!warnOnIncompleteProtocols) {
1427 (void)DiagnoseUseOfDecl(proto, identifierLocs[i]);
1428 }
1429
1430 // If this is a forward protocol declaration, get its definition.
1431 if (!proto->isThisDeclarationADefinition() && proto->getDefinition())
1432 proto = proto->getDefinition();
1433
1434 // If this is a forward declaration and we are supposed to warn in this
1435 // case, do it.
1436 // FIXME: Recover nicely in the hidden case.
1437 ObjCProtocolDecl *forwardDecl = nullptr;
1438 if (warnOnIncompleteProtocols &&
1439 NestedProtocolHasNoDefinition(proto, forwardDecl)) {
1440 Diag(identifierLocs[i], diag::warn_undef_protocolref)
1441 << proto->getDeclName();
1442 Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined)
1443 << forwardDecl;
1444 }
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001445
1446 // If everything this far has been a type name (and we care
1447 // about such things), check whether this name refers to a type
1448 // as well.
1449 if (allAreTypeNames) {
1450 if (auto *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1451 LookupOrdinaryName)) {
1452 if (isa<ObjCInterfaceDecl>(decl)) {
1453 if (firstClassNameLoc.isInvalid())
1454 firstClassNameLoc = identifierLocs[i];
1455 } else if (!isa<TypeDecl>(decl)) {
1456 // Not a type.
1457 allAreTypeNames = false;
1458 }
1459 } else {
1460 allAreTypeNames = false;
1461 }
1462 }
1463 }
1464
1465 // All of the protocols listed also have type names, and at least
1466 // one is an Objective-C class name. Check whether all of the
1467 // protocol conformances are declared by the base class itself, in
1468 // which case we warn.
1469 if (allAreTypeNames && firstClassNameLoc.isValid()) {
1470 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> knownProtocols;
1471 Context.CollectInheritedProtocols(baseClass, knownProtocols);
1472 bool allProtocolsDeclared = true;
1473 for (auto proto : protocols) {
1474 if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) {
1475 allProtocolsDeclared = false;
1476 break;
1477 }
1478 }
1479
1480 if (allProtocolsDeclared) {
1481 Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type)
1482 << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc)
Craig Topper07fa1762015-11-15 02:31:46 +00001483 << FixItHint::CreateInsertion(getLocForEndOfToken(firstClassNameLoc),
1484 " *");
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001485 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00001486 }
1487
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001488 protocolLAngleLoc = lAngleLoc;
1489 protocolRAngleLoc = rAngleLoc;
1490 assert(protocols.size() == identifierLocs.size());
Douglas Gregore9d95f12015-07-07 03:57:35 +00001491 };
1492
1493 // Attempt to resolve all of the identifiers as protocols.
1494 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1495 ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]);
1496 protocols.push_back(proto);
1497 if (proto)
1498 ++numProtocolsResolved;
1499 }
1500
1501 // If all of the names were protocols, these were protocol qualifiers.
1502 if (numProtocolsResolved == identifiers.size())
1503 return resolvedAsProtocols();
1504
1505 // Attempt to resolve all of the identifiers as type names or
1506 // Objective-C class names. The latter is technically ill-formed,
1507 // but is probably something like \c NSArray<NSView *> missing the
1508 // \c*.
1509 typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl;
1510 SmallVector<TypeOrClassDecl, 4> typeDecls;
1511 unsigned numTypeDeclsResolved = 0;
1512 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1513 NamedDecl *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1514 LookupOrdinaryName);
1515 if (!decl) {
1516 typeDecls.push_back(TypeOrClassDecl());
1517 continue;
1518 }
1519
1520 if (auto typeDecl = dyn_cast<TypeDecl>(decl)) {
1521 typeDecls.push_back(typeDecl);
1522 ++numTypeDeclsResolved;
1523 continue;
1524 }
1525
1526 if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) {
1527 typeDecls.push_back(objcClass);
1528 ++numTypeDeclsResolved;
1529 continue;
1530 }
1531
1532 typeDecls.push_back(TypeOrClassDecl());
1533 }
1534
1535 AttributeFactory attrFactory;
1536
1537 // Local function that forms a reference to the given type or
1538 // Objective-C class declaration.
1539 auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc)
1540 -> TypeResult {
1541 // Form declaration specifiers. They simply refer to the type.
1542 DeclSpec DS(attrFactory);
1543 const char* prevSpec; // unused
1544 unsigned diagID; // unused
1545 QualType type;
1546 if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>())
1547 type = Context.getTypeDeclType(actualTypeDecl);
1548 else
1549 type = Context.getObjCInterfaceType(typeDecl.get<ObjCInterfaceDecl *>());
1550 TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc);
1551 ParsedType parsedType = CreateParsedType(type, parsedTSInfo);
1552 DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID,
1553 parsedType, Context.getPrintingPolicy());
1554 // Use the identifier location for the type source range.
1555 DS.SetRangeStart(loc);
1556 DS.SetRangeEnd(loc);
1557
1558 // Form the declarator.
Faisal Vali421b2d12017-12-29 05:41:00 +00001559 Declarator D(DS, DeclaratorContext::TypeNameContext);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001560
1561 // If we have a typedef of an Objective-C class type that is missing a '*',
1562 // add the '*'.
1563 if (type->getAs<ObjCInterfaceType>()) {
Craig Topper07fa1762015-11-15 02:31:46 +00001564 SourceLocation starLoc = getLocForEndOfToken(loc);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001565 ParsedAttributes parsedAttrs(attrFactory);
1566 D.AddTypeInfo(DeclaratorChunk::getPointer(/*typeQuals=*/0, starLoc,
1567 SourceLocation(),
1568 SourceLocation(),
1569 SourceLocation(),
Andrey Bokhanko45d41322016-05-11 18:38:21 +00001570 SourceLocation(),
Douglas Gregore9d95f12015-07-07 03:57:35 +00001571 SourceLocation()),
Hans Wennborgdcfba332015-10-06 23:40:43 +00001572 parsedAttrs,
1573 starLoc);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001574
1575 // Diagnose the missing '*'.
1576 Diag(loc, diag::err_objc_type_arg_missing_star)
1577 << type
1578 << FixItHint::CreateInsertion(starLoc, " *");
1579 }
1580
1581 // Convert this to a type.
1582 return ActOnTypeName(S, D);
1583 };
1584
1585 // Local function that updates the declaration specifiers with
1586 // type argument information.
1587 auto resolvedAsTypeDecls = [&] {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001588 // We did not resolve these as protocols.
1589 protocols.clear();
1590
Douglas Gregore9d95f12015-07-07 03:57:35 +00001591 assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl");
1592 // Map type declarations to type arguments.
Douglas Gregore9d95f12015-07-07 03:57:35 +00001593 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1594 // Map type reference to a type.
1595 TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]);
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001596 if (!type.isUsable()) {
1597 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001598 return;
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001599 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00001600
1601 typeArgs.push_back(type.get());
1602 }
1603
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001604 typeArgsLAngleLoc = lAngleLoc;
1605 typeArgsRAngleLoc = rAngleLoc;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001606 };
1607
1608 // If all of the identifiers can be resolved as type names or
1609 // Objective-C class names, we have type arguments.
1610 if (numTypeDeclsResolved == identifiers.size())
1611 return resolvedAsTypeDecls();
1612
1613 // Error recovery: some names weren't found, or we have a mix of
1614 // type and protocol names. Go resolve all of the unresolved names
1615 // and complain if we can't find a consistent answer.
1616 LookupNameKind lookupKind = LookupAnyName;
1617 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1618 // If we already have a protocol or type. Check whether it is the
1619 // right thing.
1620 if (protocols[i] || typeDecls[i]) {
1621 // If we haven't figured out whether we want types or protocols
1622 // yet, try to figure it out from this name.
1623 if (lookupKind == LookupAnyName) {
1624 // If this name refers to both a protocol and a type (e.g., \c
1625 // NSObject), don't conclude anything yet.
1626 if (protocols[i] && typeDecls[i])
1627 continue;
1628
1629 // Otherwise, let this name decide whether we'll be correcting
1630 // toward types or protocols.
1631 lookupKind = protocols[i] ? LookupObjCProtocolName
1632 : LookupOrdinaryName;
1633 continue;
1634 }
1635
1636 // If we want protocols and we have a protocol, there's nothing
1637 // more to do.
1638 if (lookupKind == LookupObjCProtocolName && protocols[i])
1639 continue;
1640
1641 // If we want types and we have a type declaration, there's
1642 // nothing more to do.
1643 if (lookupKind == LookupOrdinaryName && typeDecls[i])
1644 continue;
1645
1646 // We have a conflict: some names refer to protocols and others
1647 // refer to types.
Bruno Cardoso Lopesc54768f2016-04-13 20:59:07 +00001648 DiagnoseTypeArgsAndProtocols(identifiers[0], identifierLocs[0],
1649 identifiers[i], identifierLocs[i],
1650 protocols[i] != nullptr);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001651
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001652 protocols.clear();
1653 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001654 return;
1655 }
1656
1657 // Perform typo correction on the name.
1658 TypoCorrection corrected = CorrectTypo(
1659 DeclarationNameInfo(identifiers[i], identifierLocs[i]), lookupKind, S,
1660 nullptr,
1661 llvm::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(Context,
1662 lookupKind),
1663 CTK_ErrorRecovery);
1664 if (corrected) {
1665 // Did we find a protocol?
1666 if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) {
1667 diagnoseTypo(corrected,
1668 PDiag(diag::err_undeclared_protocol_suggest)
1669 << identifiers[i]);
1670 lookupKind = LookupObjCProtocolName;
1671 protocols[i] = proto;
1672 ++numProtocolsResolved;
1673 continue;
1674 }
1675
1676 // Did we find a type?
1677 if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) {
1678 diagnoseTypo(corrected,
1679 PDiag(diag::err_unknown_typename_suggest)
1680 << identifiers[i]);
1681 lookupKind = LookupOrdinaryName;
1682 typeDecls[i] = typeDecl;
1683 ++numTypeDeclsResolved;
1684 continue;
1685 }
1686
1687 // Did we find an Objective-C class?
1688 if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1689 diagnoseTypo(corrected,
1690 PDiag(diag::err_unknown_type_or_class_name_suggest)
1691 << identifiers[i] << true);
1692 lookupKind = LookupOrdinaryName;
1693 typeDecls[i] = objcClass;
1694 ++numTypeDeclsResolved;
1695 continue;
1696 }
1697 }
1698
1699 // We couldn't find anything.
1700 Diag(identifierLocs[i],
1701 (lookupKind == LookupAnyName ? diag::err_objc_type_arg_missing
1702 : lookupKind == LookupObjCProtocolName ? diag::err_undeclared_protocol
1703 : diag::err_unknown_typename))
1704 << identifiers[i];
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001705 protocols.clear();
1706 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001707 return;
1708 }
1709
1710 // If all of the names were (corrected to) protocols, these were
1711 // protocol qualifiers.
1712 if (numProtocolsResolved == identifiers.size())
1713 return resolvedAsProtocols();
1714
1715 // Otherwise, all of the names were (corrected to) types.
1716 assert(numTypeDeclsResolved == identifiers.size() && "Not all types?");
1717 return resolvedAsTypeDecls();
1718}
1719
Fariborz Jahanianabf63e7b2009-03-02 19:06:08 +00001720/// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001721/// a class method in its extension.
1722///
Mike Stump11289f42009-09-09 15:08:12 +00001723void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001724 ObjCInterfaceDecl *ID) {
1725 if (!ID)
1726 return; // Possibly due to previous error
1727
1728 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
Aaron Ballmanaff18c02014-03-13 19:03:34 +00001729 for (auto *MD : ID->methods())
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001730 MethodMap[MD->getSelector()] = MD;
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001731
1732 if (MethodMap.empty())
1733 return;
Aaron Ballmanaff18c02014-03-13 19:03:34 +00001734 for (const auto *Method : CAT->methods()) {
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001735 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
Fariborz Jahanian83d674e2014-03-17 17:46:10 +00001736 if (PrevMethod &&
1737 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
1738 !MatchTwoMethodDeclarations(Method, PrevMethod)) {
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001739 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1740 << Method->getDeclName();
1741 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1742 }
1743 }
1744}
1745
James Dennett634962f2012-06-14 21:40:34 +00001746/// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
Douglas Gregorf6102672012-01-01 21:23:57 +00001747Sema::DeclGroupPtrTy
Chris Lattnerda463fe2007-12-12 07:09:47 +00001748Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
Craig Topper0f723bb2015-10-22 05:00:01 +00001749 ArrayRef<IdentifierLocPair> IdentList,
Fariborz Jahanian1470e932008-12-17 01:07:27 +00001750 AttributeList *attrList) {
Douglas Gregorf6102672012-01-01 21:23:57 +00001751 SmallVector<Decl *, 8> DeclsInGroup;
Craig Topper0f723bb2015-10-22 05:00:01 +00001752 for (const IdentifierLocPair &IdentPair : IdentList) {
1753 IdentifierInfo *Ident = IdentPair.first;
1754 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentPair.second,
Richard Smithbecb92d2017-10-10 22:33:17 +00001755 forRedeclarationInCurContext());
Douglas Gregor32c17572012-01-01 20:30:41 +00001756 ObjCProtocolDecl *PDecl
1757 = ObjCProtocolDecl::Create(Context, CurContext, Ident,
Craig Topper0f723bb2015-10-22 05:00:01 +00001758 IdentPair.second, AtProtocolLoc,
Douglas Gregor05a1f4d2012-01-01 22:06:18 +00001759 PrevDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +00001760
1761 PushOnScopeChains(PDecl, TUScope);
Douglas Gregorf6102672012-01-01 21:23:57 +00001762 CheckObjCDeclScope(PDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +00001763
Douglas Gregor42ff1bb2012-01-01 20:33:24 +00001764 if (attrList)
Douglas Gregor758a8692009-06-17 21:51:59 +00001765 ProcessDeclAttributeList(TUScope, PDecl, attrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001766 AddPragmaAttributes(TUScope, PDecl);
1767
Douglas Gregor32c17572012-01-01 20:30:41 +00001768 if (PrevDecl)
1769 mergeDeclAttributes(PDecl, PrevDecl);
1770
Douglas Gregorf6102672012-01-01 21:23:57 +00001771 DeclsInGroup.push_back(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001772 }
Mike Stump11289f42009-09-09 15:08:12 +00001773
Richard Smith3beb7c62017-01-12 02:27:38 +00001774 return BuildDeclaratorGroup(DeclsInGroup);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001775}
1776
John McCall48871652010-08-21 09:40:31 +00001777Decl *Sema::
Chris Lattnerd7352d62008-07-21 22:17:28 +00001778ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
1779 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001780 ObjCTypeParamList *typeParamList,
Chris Lattnerd7352d62008-07-21 22:17:28 +00001781 IdentifierInfo *CategoryName,
1782 SourceLocation CategoryLoc,
John McCall48871652010-08-21 09:40:31 +00001783 Decl * const *ProtoRefs,
Chris Lattnerd7352d62008-07-21 22:17:28 +00001784 unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001785 const SourceLocation *ProtoLocs,
Alex Lorenzf9371392017-03-23 11:44:25 +00001786 SourceLocation EndProtoLoc,
1787 AttributeList *AttrList) {
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001788 ObjCCategoryDecl *CDecl;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001789 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
Ted Kremenek514ff702010-02-23 19:39:46 +00001790
1791 /// Check that class of this category is already completely declared.
Douglas Gregor4123a862011-11-14 22:10:01 +00001792
1793 if (!IDecl
1794 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001795 diag::err_category_forward_interface,
Craig Topperc3ec1492014-05-26 06:22:03 +00001796 CategoryName == nullptr)) {
Ted Kremenek514ff702010-02-23 19:39:46 +00001797 // Create an invalid ObjCCategoryDecl to serve as context for
1798 // the enclosing method declarations. We mark the decl invalid
1799 // to make it clear that this isn't a valid AST.
1800 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001801 ClassLoc, CategoryLoc, CategoryName,
1802 IDecl, typeParamList);
Ted Kremenek514ff702010-02-23 19:39:46 +00001803 CDecl->setInvalidDecl();
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00001804 CurContext->addDecl(CDecl);
Douglas Gregor4123a862011-11-14 22:10:01 +00001805
1806 if (!IDecl)
1807 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001808 return ActOnObjCContainerStartDefinition(CDecl);
Ted Kremenek514ff702010-02-23 19:39:46 +00001809 }
1810
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001811 if (!CategoryName && IDecl->getImplementation()) {
1812 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
1813 Diag(IDecl->getImplementation()->getLocation(),
1814 diag::note_implementation_declared);
Ted Kremenek514ff702010-02-23 19:39:46 +00001815 }
1816
Fariborz Jahanian30a42922010-02-15 21:55:26 +00001817 if (CategoryName) {
1818 /// Check for duplicate interface declaration for this category
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001819 if (ObjCCategoryDecl *Previous
1820 = IDecl->FindCategoryDeclaration(CategoryName)) {
1821 // Class extensions can be declared multiple times, categories cannot.
1822 Diag(CategoryLoc, diag::warn_dup_category_def)
1823 << ClassName << CategoryName;
1824 Diag(Previous->getLocation(), diag::note_previous_definition);
Chris Lattner9018ca82009-02-16 21:26:43 +00001825 }
1826 }
Chris Lattner9018ca82009-02-16 21:26:43 +00001827
Douglas Gregor85f3f952015-07-07 03:57:15 +00001828 // If we have a type parameter list, check it.
1829 if (typeParamList) {
1830 if (auto prevTypeParamList = IDecl->getTypeParamList()) {
1831 if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList,
1832 CategoryName
1833 ? TypeParamListContext::Category
1834 : TypeParamListContext::Extension))
1835 typeParamList = nullptr;
1836 } else {
1837 Diag(typeParamList->getLAngleLoc(),
1838 diag::err_objc_parameterized_category_nonclass)
1839 << (CategoryName != nullptr)
1840 << ClassName
1841 << typeParamList->getSourceRange();
1842
1843 typeParamList = nullptr;
1844 }
1845 }
1846
Argyrios Kyrtzidis3a5094b2011-08-30 19:43:26 +00001847 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001848 ClassLoc, CategoryLoc, CategoryName, IDecl,
1849 typeParamList);
Argyrios Kyrtzidis3a5094b2011-08-30 19:43:26 +00001850 // FIXME: PushOnScopeChains?
1851 CurContext->addDecl(CDecl);
1852
Alex Lorenza9c966d2018-02-23 23:49:43 +00001853 // Process the attributes before looking at protocols to ensure that the
1854 // availability attribute is attached to the category to provide availability
1855 // checking for protocol uses.
1856 if (AttrList)
1857 ProcessDeclAttributeList(TUScope, CDecl, AttrList);
1858 AddPragmaAttributes(TUScope, CDecl);
1859
Chris Lattnerda463fe2007-12-12 07:09:47 +00001860 if (NumProtoRefs) {
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001861 diagnoseUseOfProtocols(*this, CDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1862 NumProtoRefs, ProtoLocs);
1863 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001864 ProtoLocs, Context);
Fariborz Jahanian092cd6e2009-10-05 20:41:32 +00001865 // Protocols in the class extension belong to the class.
Fariborz Jahanian30a42922010-02-15 21:55:26 +00001866 if (CDecl->IsClassExtension())
Roman Divackye6377112012-09-06 15:59:27 +00001867 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001868 NumProtoRefs, Context);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001869 }
Mike Stump11289f42009-09-09 15:08:12 +00001870
Anders Carlssona6b508a2008-11-04 16:57:32 +00001871 CheckObjCDeclScope(CDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001872 return ActOnObjCContainerStartDefinition(CDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001873}
1874
1875/// ActOnStartCategoryImplementation - Perform semantic checks on the
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001876/// category implementation declaration and build an ObjCCategoryImplDecl
Chris Lattnerda463fe2007-12-12 07:09:47 +00001877/// object.
John McCall48871652010-08-21 09:40:31 +00001878Decl *Sema::ActOnStartCategoryImplementation(
Chris Lattnerda463fe2007-12-12 07:09:47 +00001879 SourceLocation AtCatImplLoc,
1880 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1881 IdentifierInfo *CatName, SourceLocation CatLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001882 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
Craig Topperc3ec1492014-05-26 06:22:03 +00001883 ObjCCategoryDecl *CatIDecl = nullptr;
Argyrios Kyrtzidis4af2cb32012-03-02 19:14:29 +00001884 if (IDecl && IDecl->hasDefinition()) {
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001885 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
1886 if (!CatIDecl) {
1887 // Category @implementation with no corresponding @interface.
1888 // Create and install one.
Argyrios Kyrtzidis41fc05c2011-11-23 20:27:26 +00001889 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
1890 ClassLoc, CatLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001891 CatName, IDecl,
1892 /*typeParamList=*/nullptr);
Argyrios Kyrtzidis41fc05c2011-11-23 20:27:26 +00001893 CatIDecl->setImplicit();
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001894 }
1895 }
1896
Mike Stump11289f42009-09-09 15:08:12 +00001897 ObjCCategoryImplDecl *CDecl =
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001898 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
Argyrios Kyrtzidis4996f5f2011-12-09 00:31:40 +00001899 ClassLoc, AtCatImplLoc, CatLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001900 /// Check that class of this category is already completely declared.
Douglas Gregor4123a862011-11-14 22:10:01 +00001901 if (!IDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001902 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
John McCalld2930c22011-07-22 02:45:48 +00001903 CDecl->setInvalidDecl();
Douglas Gregor4123a862011-11-14 22:10:01 +00001904 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1905 diag::err_undef_interface)) {
1906 CDecl->setInvalidDecl();
John McCalld2930c22011-07-22 02:45:48 +00001907 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001908
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001909 // FIXME: PushOnScopeChains?
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001910 CurContext->addDecl(CDecl);
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001911
Douglas Gregor24ae22c2016-04-01 23:23:52 +00001912 // If the interface has the objc_runtime_visible attribute, we
1913 // cannot implement a category for it.
1914 if (IDecl && IDecl->hasAttr<ObjCRuntimeVisibleAttr>()) {
1915 Diag(ClassLoc, diag::err_objc_runtime_visible_category)
1916 << IDecl->getDeclName();
1917 }
1918
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001919 /// Check that CatName, category name, is not used in another implementation.
1920 if (CatIDecl) {
1921 if (CatIDecl->getImplementation()) {
1922 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
1923 << CatName;
1924 Diag(CatIDecl->getImplementation()->getLocation(),
1925 diag::note_previous_definition);
Argyrios Kyrtzidis0f6d5ca2013-05-30 18:53:21 +00001926 CDecl->setInvalidDecl();
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001927 } else {
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001928 CatIDecl->setImplementation(CDecl);
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001929 // Warn on implementating category of deprecated class under
1930 // -Wdeprecated-implementations flag.
Alex Lorenzf81d97e2017-07-13 16:35:59 +00001931 DiagnoseObjCImplementedDeprecations(*this, CatIDecl,
1932 CDecl->getLocation());
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001933 }
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001934 }
Mike Stump11289f42009-09-09 15:08:12 +00001935
Anders Carlssona6b508a2008-11-04 16:57:32 +00001936 CheckObjCDeclScope(CDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001937 return ActOnObjCContainerStartDefinition(CDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001938}
1939
John McCall48871652010-08-21 09:40:31 +00001940Decl *Sema::ActOnStartClassImplementation(
Chris Lattnerda463fe2007-12-12 07:09:47 +00001941 SourceLocation AtClassImplLoc,
1942 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001943 IdentifierInfo *SuperClassname,
Chris Lattnerda463fe2007-12-12 07:09:47 +00001944 SourceLocation SuperClassLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001945 ObjCInterfaceDecl *IDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001946 // Check for another declaration kind with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00001947 NamedDecl *PrevDecl
Douglas Gregorb8eaf292010-04-15 23:40:53 +00001948 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00001949 forRedeclarationInCurContext());
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001950 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001951 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Chris Lattner0369c572008-11-23 23:12:31 +00001952 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor1c283312010-08-11 12:19:30 +00001953 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
Richard Smithdb0ac552015-12-18 22:40:25 +00001954 // FIXME: This will produce an error if the definition of the interface has
1955 // been imported from a module but is not visible.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00001956 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1957 diag::warn_undef_interface);
Douglas Gregor40f7a002010-01-04 17:27:12 +00001958 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001959 // We did not find anything with the name ClassName; try to correct for
Douglas Gregor40f7a002010-01-04 17:27:12 +00001960 // typos in the class name.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001961 TypoCorrection Corrected = CorrectTypo(
1962 DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope,
1963 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(), CTK_NonError);
Richard Smithf9b15102013-08-17 00:46:16 +00001964 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1965 // Suggest the (potentially) correct interface name. Don't provide a
1966 // code-modification hint or use the typo name for recovery, because
1967 // this is just a warning. The program may actually be correct.
1968 diagnoseTypo(Corrected,
1969 PDiag(diag::warn_undef_interface_suggest) << ClassName,
1970 /*ErrorRecovery*/false);
Douglas Gregor40f7a002010-01-04 17:27:12 +00001971 } else {
1972 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
1973 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001974 }
Mike Stump11289f42009-09-09 15:08:12 +00001975
Chris Lattnerda463fe2007-12-12 07:09:47 +00001976 // Check that super class name is valid class name
Craig Topperc3ec1492014-05-26 06:22:03 +00001977 ObjCInterfaceDecl *SDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001978 if (SuperClassname) {
1979 // Check if a different kind of symbol declared in this scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001980 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
1981 LookupOrdinaryName);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001982 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001983 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
1984 << SuperClassname;
Chris Lattner0369c572008-11-23 23:12:31 +00001985 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001986 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001987 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidis3b60cff2012-03-13 01:09:36 +00001988 if (SDecl && !SDecl->hasDefinition())
Craig Topperc3ec1492014-05-26 06:22:03 +00001989 SDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001990 if (!SDecl)
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001991 Diag(SuperClassLoc, diag::err_undef_superclass)
1992 << SuperClassname << ClassName;
Douglas Gregor0b144e12011-12-15 00:29:59 +00001993 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00001994 // This implementation and its interface do not have the same
1995 // super class.
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001996 Diag(SuperClassLoc, diag::err_conflicting_super_class)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001997 << SDecl->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001998 Diag(SDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001999 }
2000 }
2001 }
Mike Stump11289f42009-09-09 15:08:12 +00002002
Chris Lattnerda463fe2007-12-12 07:09:47 +00002003 if (!IDecl) {
2004 // Legacy case of @implementation with no corresponding @interface.
2005 // Build, chain & install the interface decl into the identifier.
Daniel Dunbar73a73f52008-08-20 18:02:42 +00002006
Mike Stump87c57ac2009-05-16 07:39:55 +00002007 // FIXME: Do we support attributes on the @implementation? If so we should
2008 // copy them over.
Mike Stump11289f42009-09-09 15:08:12 +00002009 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00002010 ClassName, /*typeParamList=*/nullptr,
2011 /*PrevDecl=*/nullptr, ClassLoc,
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002012 true);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002013 AddPragmaAttributes(TUScope, IDecl);
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002014 IDecl->startDefinition();
Douglas Gregor16408322011-12-15 22:34:59 +00002015 if (SDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00002016 IDecl->setSuperClass(Context.getTrivialTypeSourceInfo(
2017 Context.getObjCInterfaceType(SDecl),
2018 SuperClassLoc));
Douglas Gregor16408322011-12-15 22:34:59 +00002019 IDecl->setEndOfDefinitionLoc(SuperClassLoc);
2020 } else {
2021 IDecl->setEndOfDefinitionLoc(ClassLoc);
2022 }
2023
Douglas Gregorac345a32009-04-24 00:16:12 +00002024 PushOnScopeChains(IDecl, TUScope);
Douglas Gregor1c283312010-08-11 12:19:30 +00002025 } else {
2026 // Mark the interface as being completed, even if it was just as
2027 // @class ....;
2028 // declaration; the user cannot reopen it.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002029 if (!IDecl->hasDefinition())
2030 IDecl->startDefinition();
Chris Lattnerda463fe2007-12-12 07:09:47 +00002031 }
Mike Stump11289f42009-09-09 15:08:12 +00002032
2033 ObjCImplementationDecl* IMPDecl =
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00002034 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
Argyrios Kyrtzidisfac31622013-05-03 18:05:44 +00002035 ClassLoc, AtClassImplLoc, SuperClassLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002036
Anders Carlssona6b508a2008-11-04 16:57:32 +00002037 if (CheckObjCDeclScope(IMPDecl))
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00002038 return ActOnObjCContainerStartDefinition(IMPDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002039
Chris Lattnerda463fe2007-12-12 07:09:47 +00002040 // Check that there is no duplicate implementation of this class.
Douglas Gregor1c283312010-08-11 12:19:30 +00002041 if (IDecl->getImplementation()) {
2042 // FIXME: Don't leak everything!
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002043 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
Argyrios Kyrtzidis43cee9352009-07-21 00:06:04 +00002044 Diag(IDecl->getImplementation()->getLocation(),
2045 diag::note_previous_definition);
Argyrios Kyrtzidis0f6d5ca2013-05-30 18:53:21 +00002046 IMPDecl->setInvalidDecl();
Douglas Gregor1c283312010-08-11 12:19:30 +00002047 } else { // add it to the list.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002048 IDecl->setImplementation(IMPDecl);
Douglas Gregor79947a22009-04-24 00:11:27 +00002049 PushOnScopeChains(IMPDecl, TUScope);
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00002050 // Warn on implementating deprecated class under
2051 // -Wdeprecated-implementations flag.
Alex Lorenzf81d97e2017-07-13 16:35:59 +00002052 DiagnoseObjCImplementedDeprecations(*this, IDecl, IMPDecl->getLocation());
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002053 }
Douglas Gregor24ae22c2016-04-01 23:23:52 +00002054
2055 // If the superclass has the objc_runtime_visible attribute, we
2056 // cannot implement a subclass of it.
2057 if (IDecl->getSuperClass() &&
2058 IDecl->getSuperClass()->hasAttr<ObjCRuntimeVisibleAttr>()) {
2059 Diag(ClassLoc, diag::err_objc_runtime_visible_subclass)
2060 << IDecl->getDeclName()
2061 << IDecl->getSuperClass()->getDeclName();
2062 }
2063
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00002064 return ActOnObjCContainerStartDefinition(IMPDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002065}
2066
Argyrios Kyrtzidis2e85c5f2012-02-23 21:11:20 +00002067Sema::DeclGroupPtrTy
2068Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
2069 SmallVector<Decl *, 64> DeclsInGroup;
2070 DeclsInGroup.reserve(Decls.size() + 1);
2071
2072 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
2073 Decl *Dcl = Decls[i];
2074 if (!Dcl)
2075 continue;
2076 if (Dcl->getDeclContext()->isFileContext())
2077 Dcl->setTopLevelDeclInObjCContainer();
2078 DeclsInGroup.push_back(Dcl);
2079 }
2080
2081 DeclsInGroup.push_back(ObjCImpDecl);
2082
Richard Smith3beb7c62017-01-12 02:27:38 +00002083 return BuildDeclaratorGroup(DeclsInGroup);
Argyrios Kyrtzidis2e85c5f2012-02-23 21:11:20 +00002084}
2085
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002086void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
2087 ObjCIvarDecl **ivars, unsigned numIvars,
Chris Lattnerda463fe2007-12-12 07:09:47 +00002088 SourceLocation RBrace) {
2089 assert(ImpDecl && "missing implementation decl");
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002090 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
Chris Lattnerda463fe2007-12-12 07:09:47 +00002091 if (!IDecl)
2092 return;
James Dennett634962f2012-06-14 21:40:34 +00002093 /// Check case of non-existing \@interface decl.
2094 /// (legacy objective-c \@implementation decl without an \@interface decl).
Chris Lattnerda463fe2007-12-12 07:09:47 +00002095 /// Add implementations's ivar to the synthesize class's ivar list.
Steve Naroffaac654a2009-04-20 20:09:33 +00002096 if (IDecl->isImplicitInterfaceDecl()) {
Douglas Gregor16408322011-12-15 22:34:59 +00002097 IDecl->setEndOfDefinitionLoc(RBrace);
Fariborz Jahanian20912d62010-02-17 17:00:07 +00002098 // Add ivar's to class's DeclContext.
2099 for (unsigned i = 0, e = numIvars; i != e; ++i) {
Fariborz Jahanianc0309cd2010-02-17 18:10:54 +00002100 ivars[i]->setLexicalDeclContext(ImpDecl);
Richard Smith05afe5e2012-03-13 03:12:56 +00002101 IDecl->makeDeclVisibleInContext(ivars[i]);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00002102 ImpDecl->addDecl(ivars[i]);
Fariborz Jahanian20912d62010-02-17 17:00:07 +00002103 }
2104
Chris Lattnerda463fe2007-12-12 07:09:47 +00002105 return;
2106 }
2107 // If implementation has empty ivar list, just return.
2108 if (numIvars == 0)
2109 return;
Mike Stump11289f42009-09-09 15:08:12 +00002110
Chris Lattnerda463fe2007-12-12 07:09:47 +00002111 assert(ivars && "missing @implementation ivars");
John McCall5fb5df92012-06-20 06:18:46 +00002112 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002113 if (ImpDecl->getSuperClass())
2114 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
2115 for (unsigned i = 0; i < numIvars; i++) {
2116 ObjCIvarDecl* ImplIvar = ivars[i];
2117 if (const ObjCIvarDecl *ClsIvar =
2118 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2119 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2120 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2121 continue;
2122 }
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00002123 // Check class extensions (unnamed categories) for duplicate ivars.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002124 for (const auto *CDecl : IDecl->visible_extensions()) {
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00002125 if (const ObjCIvarDecl *ClsExtIvar =
2126 CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2127 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2128 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
2129 continue;
2130 }
2131 }
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002132 // Instance ivar to Implementation's DeclContext.
2133 ImplIvar->setLexicalDeclContext(ImpDecl);
Richard Smith05afe5e2012-03-13 03:12:56 +00002134 IDecl->makeDeclVisibleInContext(ImplIvar);
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002135 ImpDecl->addDecl(ImplIvar);
2136 }
2137 return;
2138 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002139 // Check interface's Ivar list against those in the implementation.
2140 // names and types must match.
2141 //
Chris Lattnerda463fe2007-12-12 07:09:47 +00002142 unsigned j = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002143 ObjCInterfaceDecl::ivar_iterator
Chris Lattner061227a2007-12-12 17:58:05 +00002144 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
2145 for (; numIvars > 0 && IVI != IVE; ++IVI) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002146 ObjCIvarDecl* ImplIvar = ivars[j++];
David Blaikie40ed2972012-06-06 20:45:41 +00002147 ObjCIvarDecl* ClsIvar = *IVI;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002148 assert (ImplIvar && "missing implementation ivar");
2149 assert (ClsIvar && "missing class ivar");
Mike Stump11289f42009-09-09 15:08:12 +00002150
Steve Naroff157599f2009-03-03 14:49:36 +00002151 // First, make sure the types match.
Richard Smithcaf33902011-10-10 18:28:20 +00002152 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
Chris Lattner3b054132008-11-19 05:08:23 +00002153 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002154 << ImplIvar->getIdentifier()
2155 << ImplIvar->getType() << ClsIvar->getType();
Chris Lattner0369c572008-11-23 23:12:31 +00002156 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
Richard Smithcaf33902011-10-10 18:28:20 +00002157 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
2158 ImplIvar->getBitWidthValue(Context) !=
2159 ClsIvar->getBitWidthValue(Context)) {
2160 Diag(ImplIvar->getBitWidth()->getLocStart(),
2161 diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier();
2162 Diag(ClsIvar->getBitWidth()->getLocStart(),
2163 diag::note_previous_definition);
Mike Stump11289f42009-09-09 15:08:12 +00002164 }
Steve Naroff157599f2009-03-03 14:49:36 +00002165 // Make sure the names are identical.
2166 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002167 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002168 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
Chris Lattner0369c572008-11-23 23:12:31 +00002169 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002170 }
2171 --numIvars;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002172 }
Mike Stump11289f42009-09-09 15:08:12 +00002173
Chris Lattner0f29d982007-12-12 18:11:49 +00002174 if (numIvars > 0)
Alp Tokerfff06742013-12-02 03:50:21 +00002175 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
Chris Lattner0f29d982007-12-12 18:11:49 +00002176 else if (IVI != IVE)
Alp Tokerfff06742013-12-02 03:50:21 +00002177 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002178}
2179
Ted Kremenekf87decd2013-12-13 05:58:44 +00002180static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
2181 ObjCMethodDecl *method,
2182 bool &IncompleteImpl,
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002183 unsigned DiagID,
Craig Topperc3ec1492014-05-26 06:22:03 +00002184 NamedDecl *NeededFor = nullptr) {
Fariborz Jahanian9fc39c42011-06-24 20:31:37 +00002185 // No point warning no definition of method which is 'unavailable'.
Douglas Gregorc2e3d5c2012-12-11 18:53:07 +00002186 switch (method->getAvailability()) {
2187 case AR_Available:
2188 case AR_Deprecated:
2189 break;
2190
2191 // Don't warn about unavailable or not-yet-introduced methods.
2192 case AR_NotYetIntroduced:
2193 case AR_Unavailable:
Fariborz Jahanian9fc39c42011-06-24 20:31:37 +00002194 return;
Douglas Gregorc2e3d5c2012-12-11 18:53:07 +00002195 }
2196
Ted Kremenek65d63572013-03-27 00:02:21 +00002197 // FIXME: For now ignore 'IncompleteImpl'.
2198 // Previously we grouped all unimplemented methods under a single
2199 // warning, but some users strongly voiced that they would prefer
2200 // separate warnings. We will give that approach a try, as that
2201 // matches what we do with protocols.
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002202 {
2203 const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
2204 B << method;
2205 if (NeededFor)
2206 B << NeededFor;
2207 }
Ted Kremenek65d63572013-03-27 00:02:21 +00002208
2209 // Issue a note to the original declaration.
2210 SourceLocation MethodLoc = method->getLocStart();
2211 if (MethodLoc.isValid())
Ted Kremenekf87decd2013-12-13 05:58:44 +00002212 S.Diag(MethodLoc, diag::note_method_declared_at) << method;
Steve Naroff15833ed2008-02-10 21:38:56 +00002213}
2214
David Chisnallb62d15c2010-10-25 17:23:52 +00002215/// Determines if type B can be substituted for type A. Returns true if we can
2216/// guarantee that anything that the user will do to an object of type A can
2217/// also be done to an object of type B. This is trivially true if the two
2218/// types are the same, or if B is a subclass of A. It becomes more complex
2219/// in cases where protocols are involved.
2220///
2221/// Object types in Objective-C describe the minimum requirements for an
2222/// object, rather than providing a complete description of a type. For
2223/// example, if A is a subclass of B, then B* may refer to an instance of A.
2224/// The principle of substitutability means that we may use an instance of A
2225/// anywhere that we may use an instance of B - it will implement all of the
2226/// ivars of B and all of the methods of B.
2227///
2228/// This substitutability is important when type checking methods, because
2229/// the implementation may have stricter type definitions than the interface.
2230/// The interface specifies minimum requirements, but the implementation may
2231/// have more accurate ones. For example, a method may privately accept
2232/// instances of B, but only publish that it accepts instances of A. Any
2233/// object passed to it will be type checked against B, and so will implicitly
2234/// by a valid A*. Similarly, a method may return a subclass of the class that
2235/// it is declared as returning.
2236///
2237/// This is most important when considering subclassing. A method in a
2238/// subclass must accept any object as an argument that its superclass's
2239/// implementation accepts. It may, however, accept a more general type
2240/// without breaking substitutability (i.e. you can still use the subclass
2241/// anywhere that you can use the superclass, but not vice versa). The
2242/// converse requirement applies to return types: the return type for a
2243/// subclass method must be a valid object of the kind that the superclass
2244/// advertises, but it may be specified more accurately. This avoids the need
2245/// for explicit down-casting by callers.
2246///
2247/// Note: This is a stricter requirement than for assignment.
John McCall071df462010-10-28 02:34:38 +00002248static bool isObjCTypeSubstitutable(ASTContext &Context,
2249 const ObjCObjectPointerType *A,
2250 const ObjCObjectPointerType *B,
2251 bool rejectId) {
2252 // Reject a protocol-unqualified id.
2253 if (rejectId && B->isObjCIdType()) return false;
David Chisnallb62d15c2010-10-25 17:23:52 +00002254
2255 // If B is a qualified id, then A must also be a qualified id and it must
2256 // implement all of the protocols in B. It may not be a qualified class.
2257 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
2258 // stricter definition so it is not substitutable for id<A>.
2259 if (B->isObjCQualifiedIdType()) {
2260 return A->isObjCQualifiedIdType() &&
John McCall071df462010-10-28 02:34:38 +00002261 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
2262 QualType(B,0),
2263 false);
David Chisnallb62d15c2010-10-25 17:23:52 +00002264 }
2265
2266 /*
2267 // id is a special type that bypasses type checking completely. We want a
2268 // warning when it is used in one place but not another.
2269 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
2270
2271
2272 // If B is a qualified id, then A must also be a qualified id (which it isn't
2273 // if we've got this far)
2274 if (B->isObjCQualifiedIdType()) return false;
2275 */
2276
2277 // Now we know that A and B are (potentially-qualified) class types. The
2278 // normal rules for assignment apply.
John McCall071df462010-10-28 02:34:38 +00002279 return Context.canAssignObjCInterfaces(A, B);
David Chisnallb62d15c2010-10-25 17:23:52 +00002280}
2281
John McCall071df462010-10-28 02:34:38 +00002282static SourceRange getTypeRange(TypeSourceInfo *TSI) {
2283 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
2284}
2285
Douglas Gregor813a0662015-06-19 18:14:38 +00002286/// Determine whether two set of Objective-C declaration qualifiers conflict.
2287static bool objcModifiersConflict(Decl::ObjCDeclQualifier x,
2288 Decl::ObjCDeclQualifier y) {
2289 return (x & ~Decl::OBJC_TQ_CSNullability) !=
2290 (y & ~Decl::OBJC_TQ_CSNullability);
2291}
2292
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002293static bool CheckMethodOverrideReturn(Sema &S,
John McCall071df462010-10-28 02:34:38 +00002294 ObjCMethodDecl *MethodImpl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002295 ObjCMethodDecl *MethodDecl,
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002296 bool IsProtocolMethodDecl,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002297 bool IsOverridingMode,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002298 bool Warn) {
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002299 if (IsProtocolMethodDecl &&
Douglas Gregor813a0662015-06-19 18:14:38 +00002300 objcModifiersConflict(MethodDecl->getObjCDeclQualifier(),
2301 MethodImpl->getObjCDeclQualifier())) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002302 if (Warn) {
Alp Toker314cc812014-01-25 16:55:45 +00002303 S.Diag(MethodImpl->getLocation(),
2304 (IsOverridingMode
2305 ? diag::warn_conflicting_overriding_ret_type_modifiers
2306 : diag::warn_conflicting_ret_type_modifiers))
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002307 << MethodImpl->getDeclName()
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002308 << MethodImpl->getReturnTypeSourceRange();
Alp Toker314cc812014-01-25 16:55:45 +00002309 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002310 << MethodDecl->getReturnTypeSourceRange();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002311 }
2312 else
2313 return false;
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002314 }
Douglas Gregor813a0662015-06-19 18:14:38 +00002315 if (Warn && IsOverridingMode &&
2316 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2317 !S.Context.hasSameNullabilityTypeQualifier(MethodImpl->getReturnType(),
2318 MethodDecl->getReturnType(),
2319 false)) {
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002320 auto nullabilityMethodImpl =
2321 *MethodImpl->getReturnType()->getNullability(S.Context);
2322 auto nullabilityMethodDecl =
2323 *MethodDecl->getReturnType()->getNullability(S.Context);
Douglas Gregor813a0662015-06-19 18:14:38 +00002324 S.Diag(MethodImpl->getLocation(),
2325 diag::warn_conflicting_nullability_attr_overriding_ret_types)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002326 << DiagNullabilityKind(
2327 nullabilityMethodImpl,
2328 ((MethodImpl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2329 != 0))
2330 << DiagNullabilityKind(
2331 nullabilityMethodDecl,
2332 ((MethodDecl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2333 != 0));
Douglas Gregor813a0662015-06-19 18:14:38 +00002334 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2335 }
2336
Alp Toker314cc812014-01-25 16:55:45 +00002337 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
2338 MethodDecl->getReturnType()))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002339 return true;
2340 if (!Warn)
2341 return false;
John McCall071df462010-10-28 02:34:38 +00002342
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002343 unsigned DiagID =
2344 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
2345 : diag::warn_conflicting_ret_types;
John McCall071df462010-10-28 02:34:38 +00002346
2347 // Mismatches between ObjC pointers go into a different warning
2348 // category, and sometimes they're even completely whitelisted.
2349 if (const ObjCObjectPointerType *ImplPtrTy =
Alp Toker314cc812014-01-25 16:55:45 +00002350 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
John McCall071df462010-10-28 02:34:38 +00002351 if (const ObjCObjectPointerType *IfacePtrTy =
Alp Toker314cc812014-01-25 16:55:45 +00002352 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
John McCall071df462010-10-28 02:34:38 +00002353 // Allow non-matching return types as long as they don't violate
2354 // the principle of substitutability. Specifically, we permit
2355 // return types that are subclasses of the declared return type,
2356 // or that are more-qualified versions of the declared type.
2357 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002358 return false;
John McCall071df462010-10-28 02:34:38 +00002359
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002360 DiagID =
2361 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002362 : diag::warn_non_covariant_ret_types;
John McCall071df462010-10-28 02:34:38 +00002363 }
2364 }
2365
2366 S.Diag(MethodImpl->getLocation(), DiagID)
Alp Toker314cc812014-01-25 16:55:45 +00002367 << MethodImpl->getDeclName() << MethodDecl->getReturnType()
2368 << MethodImpl->getReturnType()
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002369 << MethodImpl->getReturnTypeSourceRange();
Alp Toker314cc812014-01-25 16:55:45 +00002370 S.Diag(MethodDecl->getLocation(), IsOverridingMode
2371 ? diag::note_previous_declaration
2372 : diag::note_previous_definition)
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002373 << MethodDecl->getReturnTypeSourceRange();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002374 return false;
John McCall071df462010-10-28 02:34:38 +00002375}
2376
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002377static bool CheckMethodOverrideParam(Sema &S,
John McCall071df462010-10-28 02:34:38 +00002378 ObjCMethodDecl *MethodImpl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002379 ObjCMethodDecl *MethodDecl,
John McCall071df462010-10-28 02:34:38 +00002380 ParmVarDecl *ImplVar,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002381 ParmVarDecl *IfaceVar,
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002382 bool IsProtocolMethodDecl,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002383 bool IsOverridingMode,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002384 bool Warn) {
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002385 if (IsProtocolMethodDecl &&
Douglas Gregor813a0662015-06-19 18:14:38 +00002386 objcModifiersConflict(ImplVar->getObjCDeclQualifier(),
2387 IfaceVar->getObjCDeclQualifier())) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002388 if (Warn) {
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002389 if (IsOverridingMode)
2390 S.Diag(ImplVar->getLocation(),
2391 diag::warn_conflicting_overriding_param_modifiers)
2392 << getTypeRange(ImplVar->getTypeSourceInfo())
2393 << MethodImpl->getDeclName();
2394 else S.Diag(ImplVar->getLocation(),
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002395 diag::warn_conflicting_param_modifiers)
2396 << getTypeRange(ImplVar->getTypeSourceInfo())
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002397 << MethodImpl->getDeclName();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002398 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
2399 << getTypeRange(IfaceVar->getTypeSourceInfo());
2400 }
2401 else
2402 return false;
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002403 }
2404
John McCall071df462010-10-28 02:34:38 +00002405 QualType ImplTy = ImplVar->getType();
2406 QualType IfaceTy = IfaceVar->getType();
Douglas Gregor813a0662015-06-19 18:14:38 +00002407 if (Warn && IsOverridingMode &&
2408 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2409 !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) {
Douglas Gregor813a0662015-06-19 18:14:38 +00002410 S.Diag(ImplVar->getLocation(),
2411 diag::warn_conflicting_nullability_attr_overriding_param_types)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002412 << DiagNullabilityKind(
2413 *ImplTy->getNullability(S.Context),
2414 ((ImplVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2415 != 0))
2416 << DiagNullabilityKind(
2417 *IfaceTy->getNullability(S.Context),
2418 ((IfaceVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2419 != 0));
2420 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration);
Douglas Gregor813a0662015-06-19 18:14:38 +00002421 }
John McCall071df462010-10-28 02:34:38 +00002422 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002423 return true;
Manman Renc5705ba2016-09-13 17:41:05 +00002424
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002425 if (!Warn)
2426 return false;
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002427 unsigned DiagID =
2428 IsOverridingMode ? diag::warn_conflicting_overriding_param_types
2429 : diag::warn_conflicting_param_types;
John McCall071df462010-10-28 02:34:38 +00002430
2431 // Mismatches between ObjC pointers go into a different warning
2432 // category, and sometimes they're even completely whitelisted.
2433 if (const ObjCObjectPointerType *ImplPtrTy =
2434 ImplTy->getAs<ObjCObjectPointerType>()) {
2435 if (const ObjCObjectPointerType *IfacePtrTy =
2436 IfaceTy->getAs<ObjCObjectPointerType>()) {
2437 // Allow non-matching argument types as long as they don't
2438 // violate the principle of substitutability. Specifically, the
2439 // implementation must accept any objects that the superclass
2440 // accepts, however it may also accept others.
2441 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002442 return false;
John McCall071df462010-10-28 02:34:38 +00002443
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002444 DiagID =
2445 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002446 : diag::warn_non_contravariant_param_types;
John McCall071df462010-10-28 02:34:38 +00002447 }
2448 }
2449
2450 S.Diag(ImplVar->getLocation(), DiagID)
2451 << getTypeRange(ImplVar->getTypeSourceInfo())
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002452 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
2453 S.Diag(IfaceVar->getLocation(),
2454 (IsOverridingMode ? diag::note_previous_declaration
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002455 : diag::note_previous_definition))
John McCall071df462010-10-28 02:34:38 +00002456 << getTypeRange(IfaceVar->getTypeSourceInfo());
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002457 return false;
John McCall071df462010-10-28 02:34:38 +00002458}
John McCall31168b02011-06-15 23:02:42 +00002459
2460/// In ARC, check whether the conventional meanings of the two methods
2461/// match. If they don't, it's a hard error.
2462static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
2463 ObjCMethodDecl *decl) {
2464 ObjCMethodFamily implFamily = impl->getMethodFamily();
2465 ObjCMethodFamily declFamily = decl->getMethodFamily();
2466 if (implFamily == declFamily) return false;
2467
2468 // Since conventions are sorted by selector, the only possibility is
2469 // that the types differ enough to cause one selector or the other
2470 // to fall out of the family.
2471 assert(implFamily == OMF_None || declFamily == OMF_None);
2472
2473 // No further diagnostics required on invalid declarations.
2474 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
2475
2476 const ObjCMethodDecl *unmatched = impl;
2477 ObjCMethodFamily family = declFamily;
2478 unsigned errorID = diag::err_arc_lost_method_convention;
2479 unsigned noteID = diag::note_arc_lost_method_convention;
2480 if (declFamily == OMF_None) {
2481 unmatched = decl;
2482 family = implFamily;
2483 errorID = diag::err_arc_gained_method_convention;
2484 noteID = diag::note_arc_gained_method_convention;
2485 }
2486
2487 // Indexes into a %select clause in the diagnostic.
2488 enum FamilySelector {
2489 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
2490 };
2491 FamilySelector familySelector = FamilySelector();
2492
2493 switch (family) {
2494 case OMF_None: llvm_unreachable("logic error, no method convention");
2495 case OMF_retain:
2496 case OMF_release:
2497 case OMF_autorelease:
2498 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +00002499 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002500 case OMF_retainCount:
2501 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002502 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002503 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00002504 // Mismatches for these methods don't change ownership
2505 // conventions, so we don't care.
2506 return false;
2507
2508 case OMF_init: familySelector = F_init; break;
2509 case OMF_alloc: familySelector = F_alloc; break;
2510 case OMF_copy: familySelector = F_copy; break;
2511 case OMF_mutableCopy: familySelector = F_mutableCopy; break;
2512 case OMF_new: familySelector = F_new; break;
2513 }
2514
2515 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
2516 ReasonSelector reasonSelector;
2517
2518 // The only reason these methods don't fall within their families is
2519 // due to unusual result types.
Alp Toker314cc812014-01-25 16:55:45 +00002520 if (unmatched->getReturnType()->isObjCObjectPointerType()) {
John McCall31168b02011-06-15 23:02:42 +00002521 reasonSelector = R_UnrelatedReturn;
2522 } else {
2523 reasonSelector = R_NonObjectReturn;
2524 }
2525
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00002526 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
2527 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
John McCall31168b02011-06-15 23:02:42 +00002528
2529 return true;
2530}
John McCall071df462010-10-28 02:34:38 +00002531
Fariborz Jahanian7988d7d2008-12-05 18:18:52 +00002532void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002533 ObjCMethodDecl *MethodDecl,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002534 bool IsProtocolMethodDecl) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002535 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002536 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
2537 return;
2538
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002539 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002540 IsProtocolMethodDecl, false,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002541 true);
Mike Stump11289f42009-09-09 15:08:12 +00002542
Chris Lattner67f35b02009-04-11 19:58:42 +00002543 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002544 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2545 EF = MethodDecl->param_end();
2546 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002547 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002548 IsProtocolMethodDecl, false, true);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002549 }
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002550
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002551 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002552 Diag(ImpMethodDecl->getLocation(),
2553 diag::warn_conflicting_variadic);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002554 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002555 }
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002556}
2557
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002558void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2559 ObjCMethodDecl *Overridden,
2560 bool IsProtocolMethodDecl) {
2561
2562 CheckMethodOverrideReturn(*this, Method, Overridden,
2563 IsProtocolMethodDecl, true,
2564 true);
2565
2566 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002567 IF = Overridden->param_begin(), EM = Method->param_end(),
2568 EF = Overridden->param_end();
2569 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002570 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
2571 IsProtocolMethodDecl, true, true);
2572 }
2573
2574 if (Method->isVariadic() != Overridden->isVariadic()) {
2575 Diag(Method->getLocation(),
2576 diag::warn_conflicting_overriding_variadic);
2577 Diag(Overridden->getLocation(), diag::note_previous_declaration);
2578 }
2579}
2580
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002581/// WarnExactTypedMethods - This routine issues a warning if method
2582/// implementation declaration matches exactly that of its declaration.
2583void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2584 ObjCMethodDecl *MethodDecl,
2585 bool IsProtocolMethodDecl) {
2586 // don't issue warning when protocol method is optional because primary
2587 // class is not required to implement it and it is safe for protocol
2588 // to implement it.
2589 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
2590 return;
2591 // don't issue warning when primary class's method is
2592 // depecated/unavailable.
2593 if (MethodDecl->hasAttr<UnavailableAttr>() ||
2594 MethodDecl->hasAttr<DeprecatedAttr>())
2595 return;
2596
2597 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2598 IsProtocolMethodDecl, false, false);
2599 if (match)
2600 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002601 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2602 EF = MethodDecl->param_end();
2603 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002604 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
2605 *IM, *IF,
2606 IsProtocolMethodDecl, false, false);
2607 if (!match)
2608 break;
2609 }
2610 if (match)
2611 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
David Chisnall92918512011-08-08 17:32:19 +00002612 if (match)
2613 match = !(MethodDecl->isClassMethod() &&
2614 MethodDecl->getSelector() == GetNullarySelector("load", Context));
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002615
2616 if (match) {
2617 Diag(ImpMethodDecl->getLocation(),
2618 diag::warn_category_method_impl_match);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002619 Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
2620 << MethodDecl->getDeclName();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002621 }
2622}
2623
Mike Stump87c57ac2009-05-16 07:39:55 +00002624/// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
2625/// improve the efficiency of selector lookups and type checking by associating
2626/// with each protocol / interface / category the flattened instance tables. If
2627/// we used an immutable set to keep the table then it wouldn't add significant
2628/// memory cost and it would be handy for lookups.
Daniel Dunbar4684f372008-08-27 05:40:03 +00002629
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002630typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
Ahmed Charlesaf94d562014-03-09 11:34:25 +00002631typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002632
2633static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
2634 ProtocolNameSet &PNS) {
2635 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
2636 PNS.insert(PDecl->getIdentifier());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002637 for (const auto *PI : PDecl->protocols())
2638 findProtocolsWithExplicitImpls(PI, PNS);
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002639}
2640
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002641/// Recursively populates a set with all conformed protocols in a class
2642/// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
2643/// attribute.
2644static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
2645 ProtocolNameSet &PNS) {
2646 if (!Super)
2647 return;
2648
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002649 for (const auto *I : Super->all_referenced_protocols())
2650 findProtocolsWithExplicitImpls(I, PNS);
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002651
2652 findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002653}
2654
Steve Naroffa36992242008-02-08 22:06:17 +00002655/// CheckProtocolMethodDefs - This routine checks unimplemented methods
Chris Lattnerda463fe2007-12-12 07:09:47 +00002656/// Declared in protocol, and those referenced by it.
Ted Kremenek285ee852013-12-13 06:26:10 +00002657static void CheckProtocolMethodDefs(Sema &S,
2658 SourceLocation ImpLoc,
2659 ObjCProtocolDecl *PDecl,
2660 bool& IncompleteImpl,
2661 const Sema::SelectorSet &InsMap,
2662 const Sema::SelectorSet &ClsMap,
Ted Kremenek33e430f2013-12-13 06:26:14 +00002663 ObjCContainerDecl *CDecl,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002664 LazyProtocolNameSet &ProtocolsExplictImpl) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002665 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
2666 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
2667 : dyn_cast<ObjCInterfaceDecl>(CDecl);
Fariborz Jahanian2e8074b2010-03-27 21:10:05 +00002668 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
2669
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002670 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
Craig Topperc3ec1492014-05-26 06:22:03 +00002671 ObjCInterfaceDecl *NSIDecl = nullptr;
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002672
2673 // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
2674 // then we should check if any class in the super class hierarchy also
2675 // conforms to this protocol, either directly or via protocol inheritance.
2676 // If so, we can skip checking this protocol completely because we
2677 // know that a parent class already satisfies this protocol.
2678 //
2679 // Note: we could generalize this logic for all protocols, and merely
2680 // add the limit on looking at the super class chain for just
2681 // specially marked protocols. This may be a good optimization. This
2682 // change is restricted to 'objc_protocol_requires_explicit_implementation'
2683 // protocols for now for controlled evaluation.
2684 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
Ahmed Charlesaf94d562014-03-09 11:34:25 +00002685 if (!ProtocolsExplictImpl) {
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002686 ProtocolsExplictImpl.reset(new ProtocolNameSet);
2687 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
2688 }
2689 if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
2690 ProtocolsExplictImpl->end())
2691 return;
2692
2693 // If no super class conforms to the protocol, we should not search
2694 // for methods in the super class to implicitly satisfy the protocol.
Craig Topperc3ec1492014-05-26 06:22:03 +00002695 Super = nullptr;
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002696 }
2697
Ted Kremenek285ee852013-12-13 06:26:10 +00002698 if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
Mike Stump11289f42009-09-09 15:08:12 +00002699 // check to see if class implements forwardInvocation method and objects
2700 // of this class are derived from 'NSProxy' so that to forward requests
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002701 // from one object to another.
Mike Stump11289f42009-09-09 15:08:12 +00002702 // Under such conditions, which means that every method possible is
2703 // implemented in the class, we should not issue "Method definition not
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002704 // found" warnings.
2705 // FIXME: Use a general GetUnarySelector method for this.
Ted Kremenek285ee852013-12-13 06:26:10 +00002706 IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
2707 Selector fISelector = S.Context.Selectors.getSelector(1, &II);
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002708 if (InsMap.count(fISelector))
2709 // Is IDecl derived from 'NSProxy'? If so, no instance methods
2710 // need be implemented in the implementation.
Ted Kremenek285ee852013-12-13 06:26:10 +00002711 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002712 }
Mike Stump11289f42009-09-09 15:08:12 +00002713
Fariborz Jahanianc41cf052013-01-07 19:21:03 +00002714 // If this is a forward protocol declaration, get its definition.
2715 if (!PDecl->isThisDeclarationADefinition() &&
2716 PDecl->getDefinition())
2717 PDecl = PDecl->getDefinition();
2718
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002719 // If a method lookup fails locally we still need to look and see if
2720 // the method was implemented by a base class or an inherited
2721 // protocol. This lookup is slow, but occurs rarely in correct code
2722 // and otherwise would terminate in a warning.
2723
Chris Lattnerda463fe2007-12-12 07:09:47 +00002724 // check unimplemented instance methods.
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002725 if (!NSIDecl)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002726 for (auto *method : PDecl->instance_methods()) {
Mike Stump11289f42009-09-09 15:08:12 +00002727 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
Jordan Rosed01e83a2012-10-10 16:42:25 +00002728 !method->isPropertyAccessor() &&
2729 !InsMap.count(method->getSelector()) &&
Ted Kremenek00781502013-11-23 01:01:29 +00002730 (!Super || !Super->lookupMethod(method->getSelector(),
2731 true /* instance */,
2732 false /* shallowCategory */,
Ted Kremenek28eace62013-11-23 01:01:34 +00002733 true /* followsSuper */,
Craig Topperc3ec1492014-05-26 06:22:03 +00002734 nullptr /* category */))) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002735 // If a method is not implemented in the category implementation but
2736 // has been declared in its primary class, superclass,
2737 // or in one of their protocols, no need to issue the warning.
2738 // This is because method will be implemented in the primary class
2739 // or one of its super class implementation.
2740
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002741 // Ugly, but necessary. Method declared in protocol might have
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002742 // have been synthesized due to a property declared in the class which
2743 // uses the protocol.
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002744 if (ObjCMethodDecl *MethodInClass =
Ted Kremenek00781502013-11-23 01:01:29 +00002745 IDecl->lookupMethod(method->getSelector(),
2746 true /* instance */,
2747 true /* shallowCategoryLookup */,
2748 false /* followSuper */))
Jordan Rosed01e83a2012-10-10 16:42:25 +00002749 if (C || MethodInClass->isPropertyAccessor())
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002750 continue;
2751 unsigned DIAG = diag::warn_unimplemented_protocol_method;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002752 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
Ted Kremenek285ee852013-12-13 06:26:10 +00002753 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002754 PDecl);
Fariborz Jahanian97752f72010-03-27 19:02:17 +00002755 }
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002756 }
2757 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002758 // check unimplemented class methods
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002759 for (auto *method : PDecl->class_methods()) {
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002760 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
2761 !ClsMap.count(method->getSelector()) &&
Ted Kremenek00781502013-11-23 01:01:29 +00002762 (!Super || !Super->lookupMethod(method->getSelector(),
2763 false /* class method */,
2764 false /* shallowCategoryLookup */,
Ted Kremenek28eace62013-11-23 01:01:34 +00002765 true /* followSuper */,
Craig Topperc3ec1492014-05-26 06:22:03 +00002766 nullptr /* category */))) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002767 // See above comment for instance method lookups.
Ted Kremenek00781502013-11-23 01:01:29 +00002768 if (C && IDecl->lookupMethod(method->getSelector(),
2769 false /* class */,
2770 true /* shallowCategoryLookup */,
2771 false /* followSuper */))
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002772 continue;
Ted Kremenek00781502013-11-23 01:01:29 +00002773
Fariborz Jahanianc1fb8622010-03-31 18:23:33 +00002774 unsigned DIAG = diag::warn_unimplemented_protocol_method;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002775 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
Ted Kremenek285ee852013-12-13 06:26:10 +00002776 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
Fariborz Jahanianc1fb8622010-03-31 18:23:33 +00002777 }
Fariborz Jahanian97752f72010-03-27 19:02:17 +00002778 }
Steve Naroff3ce37a62007-12-14 23:37:57 +00002779 }
Chris Lattner390d39a2008-07-21 21:32:27 +00002780 // Check on this protocols's referenced protocols, recursively.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002781 for (auto *PI : PDecl->protocols())
2782 CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002783 CDecl, ProtocolsExplictImpl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002784}
2785
Fariborz Jahanianf9ae68a2011-07-16 00:08:33 +00002786/// MatchAllMethodDeclarations - Check methods declared in interface
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002787/// or protocol against those declared in their implementations.
2788///
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002789void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
2790 const SelectorSet &ClsMap,
2791 SelectorSet &InsMapSeen,
2792 SelectorSet &ClsMapSeen,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002793 ObjCImplDecl* IMPDecl,
2794 ObjCContainerDecl* CDecl,
2795 bool &IncompleteImpl,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002796 bool ImmediateClass,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002797 bool WarnCategoryMethodImpl) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002798 // Check and see if instance methods in class interface have been
2799 // implemented in the implementation class. If so, their types match.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002800 for (auto *I : CDecl->instance_methods()) {
David Blaikie82e95a32014-11-19 07:49:47 +00002801 if (!InsMapSeen.insert(I->getSelector()).second)
Benjamin Kramer9f8e2d72013-10-14 15:16:10 +00002802 continue;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002803 if (!I->isPropertyAccessor() &&
2804 !InsMap.count(I->getSelector())) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002805 if (ImmediateClass)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002806 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
Ted Kremenek65d63572013-03-27 00:02:21 +00002807 diag::warn_undef_method_impl);
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002808 continue;
Mike Stump12b8ce12009-08-04 21:02:39 +00002809 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002810 ObjCMethodDecl *ImpMethodDecl =
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002811 IMPDecl->getInstanceMethod(I->getSelector());
Manman Rena58f92f2016-10-11 21:18:20 +00002812 assert(CDecl->getInstanceMethod(I->getSelector(), true/*AllowHidden*/) &&
Argyrios Kyrtzidis342e08f2011-08-30 19:43:21 +00002813 "Expected to find the method through lookup as well");
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002814 // ImpMethodDecl may be null as in a @dynamic property.
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002815 if (ImpMethodDecl) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002816 if (!WarnCategoryMethodImpl)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002817 WarnConflictingTypedMethods(ImpMethodDecl, I,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002818 isa<ObjCProtocolDecl>(CDecl));
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002819 else if (!I->isPropertyAccessor())
2820 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002821 }
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002822 }
2823 }
Mike Stump11289f42009-09-09 15:08:12 +00002824
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002825 // Check and see if class methods in class interface have been
2826 // implemented in the implementation class. If so, their types match.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002827 for (auto *I : CDecl->class_methods()) {
David Blaikie82e95a32014-11-19 07:49:47 +00002828 if (!ClsMapSeen.insert(I->getSelector()).second)
Benjamin Kramer9f8e2d72013-10-14 15:16:10 +00002829 continue;
Manman Rend36f7d52016-01-27 20:10:32 +00002830 if (!I->isPropertyAccessor() &&
2831 !ClsMap.count(I->getSelector())) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002832 if (ImmediateClass)
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002833 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
Ted Kremenek65d63572013-03-27 00:02:21 +00002834 diag::warn_undef_method_impl);
Mike Stump12b8ce12009-08-04 21:02:39 +00002835 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002836 ObjCMethodDecl *ImpMethodDecl =
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002837 IMPDecl->getClassMethod(I->getSelector());
Manman Rena58f92f2016-10-11 21:18:20 +00002838 assert(CDecl->getClassMethod(I->getSelector(), true/*AllowHidden*/) &&
Argyrios Kyrtzidis342e08f2011-08-30 19:43:21 +00002839 "Expected to find the method through lookup as well");
Manman Rend36f7d52016-01-27 20:10:32 +00002840 // ImpMethodDecl may be null as in a @dynamic property.
2841 if (ImpMethodDecl) {
2842 if (!WarnCategoryMethodImpl)
2843 WarnConflictingTypedMethods(ImpMethodDecl, I,
2844 isa<ObjCProtocolDecl>(CDecl));
2845 else if (!I->isPropertyAccessor())
2846 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2847 }
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002848 }
2849 }
Fariborz Jahanian73853e52010-10-08 22:59:25 +00002850
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002851 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
2852 // Also, check for methods declared in protocols inherited by
2853 // this protocol.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002854 for (auto *PI : PD->protocols())
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002855 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002856 IMPDecl, PI, IncompleteImpl, false,
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002857 WarnCategoryMethodImpl);
2858 }
2859
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002860 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002861 // when checking that methods in implementation match their declaration,
2862 // i.e. when WarnCategoryMethodImpl is false, check declarations in class
2863 // extension; as well as those in categories.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002864 if (!WarnCategoryMethodImpl) {
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002865 for (auto *Cat : I->visible_categories())
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002866 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Argyrios Kyrtzidis3a437542015-10-13 23:27:34 +00002867 IMPDecl, Cat, IncompleteImpl,
2868 ImmediateClass && Cat->IsClassExtension(),
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002869 WarnCategoryMethodImpl);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002870 } else {
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002871 // Also methods in class extensions need be looked at next.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002872 for (auto *Ext : I->visible_extensions())
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002873 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002874 IMPDecl, Ext, IncompleteImpl, false,
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002875 WarnCategoryMethodImpl);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002876 }
2877
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002878 // Check for any implementation of a methods declared in protocol.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002879 for (auto *PI : I->all_referenced_protocols())
Mike Stump11289f42009-09-09 15:08:12 +00002880 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002881 IMPDecl, PI, IncompleteImpl, false,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002882 WarnCategoryMethodImpl);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002883
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002884 // FIXME. For now, we are not checking for extact match of methods
2885 // in category implementation and its primary class's super class.
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002886 if (!WarnCategoryMethodImpl && I->getSuperClass())
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002887 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Mike Stump11289f42009-09-09 15:08:12 +00002888 IMPDecl,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002889 I->getSuperClass(), IncompleteImpl, false);
2890 }
2891}
2892
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002893/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2894/// category matches with those implemented in its primary class and
2895/// warns each time an exact match is found.
2896void Sema::CheckCategoryVsClassMethodMatches(
2897 ObjCCategoryImplDecl *CatIMPDecl) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002898 // Get category's primary class.
2899 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
2900 if (!CatDecl)
2901 return;
2902 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
2903 if (!IDecl)
2904 return;
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002905 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
2906 SelectorSet InsMap, ClsMap;
2907
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002908 for (const auto *I : CatIMPDecl->instance_methods()) {
2909 Selector Sel = I->getSelector();
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002910 // When checking for methods implemented in the category, skip over
2911 // those declared in category class's super class. This is because
2912 // the super class must implement the method.
2913 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
2914 continue;
2915 InsMap.insert(Sel);
2916 }
2917
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002918 for (const auto *I : CatIMPDecl->class_methods()) {
2919 Selector Sel = I->getSelector();
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002920 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
2921 continue;
2922 ClsMap.insert(Sel);
2923 }
2924 if (InsMap.empty() && ClsMap.empty())
2925 return;
2926
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002927 SelectorSet InsMapSeen, ClsMapSeen;
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002928 bool IncompleteImpl = false;
2929 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2930 CatIMPDecl, IDecl,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002931 IncompleteImpl, false,
2932 true /*WarnCategoryMethodImpl*/);
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002933}
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002934
Fariborz Jahanian25491a22010-05-05 21:52:17 +00002935void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002936 ObjCContainerDecl* CDecl,
Chris Lattner9ef10f42009-03-01 00:56:52 +00002937 bool IncompleteImpl) {
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002938 SelectorSet InsMap;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002939 // Check and see if instance methods in class interface have been
2940 // implemented in the implementation class.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002941 for (const auto *I : IMPDecl->instance_methods())
2942 InsMap.insert(I->getSelector());
Mike Stump11289f42009-09-09 15:08:12 +00002943
Douglas Gregoracf4fd32015-11-03 01:15:46 +00002944 // Add the selectors for getters/setters of @dynamic properties.
2945 for (const auto *PImpl : IMPDecl->property_impls()) {
2946 // We only care about @dynamic implementations.
2947 if (PImpl->getPropertyImplementation() != ObjCPropertyImplDecl::Dynamic)
2948 continue;
2949
2950 const auto *P = PImpl->getPropertyDecl();
2951 if (!P) continue;
2952
2953 InsMap.insert(P->getGetterName());
2954 if (!P->getSetterName().isNull())
2955 InsMap.insert(P->getSetterName());
2956 }
2957
Fariborz Jahanian6c6aea92009-04-14 23:15:21 +00002958 // Check and see if properties declared in the interface have either 1)
2959 // an implementation or 2) there is a @synthesize/@dynamic implementation
2960 // of the property in the @implementation.
Ted Kremenek348e88c2014-02-21 19:41:34 +00002961 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2962 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
2963 LangOpts.ObjCRuntime.isNonFragile() &&
2964 !IDecl->isObjCRequiresPropertyDefs();
2965 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
2966 }
2967
Douglas Gregor849ebc22015-06-19 18:14:46 +00002968 // Diagnose null-resettable synthesized setters.
2969 diagnoseNullResettableSynthesizedSetters(IMPDecl);
2970
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002971 SelectorSet ClsMap;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002972 for (const auto *I : IMPDecl->class_methods())
2973 ClsMap.insert(I->getSelector());
Mike Stump11289f42009-09-09 15:08:12 +00002974
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002975 // Check for type conflict of methods declared in a class/protocol and
2976 // its implementation; if any.
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002977 SelectorSet InsMapSeen, ClsMapSeen;
Mike Stump11289f42009-09-09 15:08:12 +00002978 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2979 IMPDecl, CDecl,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002980 IncompleteImpl, true);
Fariborz Jahanian2bda1b62011-08-03 18:21:12 +00002981
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002982 // check all methods implemented in category against those declared
2983 // in its primary class.
2984 if (ObjCCategoryImplDecl *CatDecl =
2985 dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
2986 CheckCategoryVsClassMethodMatches(CatDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002987
Chris Lattnerda463fe2007-12-12 07:09:47 +00002988 // Check the protocol list for unimplemented methods in the @implementation
2989 // class.
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002990 // Check and see if class methods in class interface have been
2991 // implemented in the implementation class.
Mike Stump11289f42009-09-09 15:08:12 +00002992
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002993 LazyProtocolNameSet ExplicitImplProtocols;
2994
Chris Lattner9ef10f42009-03-01 00:56:52 +00002995 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002996 for (auto *PI : I->all_referenced_protocols())
2997 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl,
2998 InsMap, ClsMap, I, ExplicitImplProtocols);
Chris Lattner9ef10f42009-03-01 00:56:52 +00002999 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahanian8764c742009-10-05 21:32:49 +00003000 // For extended class, unimplemented methods in its protocols will
3001 // be reported in the primary class.
Fariborz Jahanian30a42922010-02-15 21:55:26 +00003002 if (!C->IsClassExtension()) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003003 for (auto *P : C->protocols())
3004 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00003005 IncompleteImpl, InsMap, ClsMap, CDecl,
3006 ExplicitImplProtocols);
Ted Kremenek348e88c2014-02-21 19:41:34 +00003007 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
Nico Weber2e0c8f72014-12-27 03:58:08 +00003008 /*SynthesizeProperties=*/false);
Fariborz Jahanian4f8a5712010-01-20 19:36:21 +00003009 }
Chris Lattner9ef10f42009-03-01 00:56:52 +00003010 } else
David Blaikie83d382b2011-09-23 05:06:16 +00003011 llvm_unreachable("invalid ObjCContainerDecl type.");
Chris Lattnerda463fe2007-12-12 07:09:47 +00003012}
3013
Fariborz Jahanian3a039e32011-08-27 20:50:59 +00003014Sema::DeclGroupPtrTy
Chris Lattnerda463fe2007-12-12 07:09:47 +00003015Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
Chris Lattner99a83312009-02-16 19:25:52 +00003016 IdentifierInfo **IdentList,
Ted Kremeneka26da852009-11-17 23:12:20 +00003017 SourceLocation *IdentLocs,
Douglas Gregor85f3f952015-07-07 03:57:15 +00003018 ArrayRef<ObjCTypeParamList *> TypeParamLists,
Chris Lattner99a83312009-02-16 19:25:52 +00003019 unsigned NumElts) {
Fariborz Jahanian3a039e32011-08-27 20:50:59 +00003020 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003021 for (unsigned i = 0; i != NumElts; ++i) {
3022 // Check for another declaration kind with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00003023 NamedDecl *PrevDecl
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003024 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
Richard Smithbecb92d2017-10-10 22:33:17 +00003025 LookupOrdinaryName, forRedeclarationInCurContext());
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003026 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Steve Naroff946166f2008-06-05 22:57:10 +00003027 // GCC apparently allows the following idiom:
3028 //
3029 // typedef NSObject < XCElementTogglerP > XCElementToggler;
3030 // @class XCElementToggler;
3031 //
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003032 // Here we have chosen to ignore the forward class declaration
3033 // with a warning. Since this is the implied behavior.
Richard Smithdda56e42011-04-15 14:24:37 +00003034 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
John McCall8b07ec22010-05-15 11:32:37 +00003035 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003036 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
Chris Lattner0369c572008-11-23 23:12:31 +00003037 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall8b07ec22010-05-15 11:32:37 +00003038 } else {
Mike Stump12b8ce12009-08-04 21:02:39 +00003039 // a forward class declaration matching a typedef name of a class refers
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003040 // to the underlying class. Just ignore the forward class with a warning
Nico Weber2e0c8f72014-12-27 03:58:08 +00003041 // as this will force the intended behavior which is to lookup the
3042 // typedef name.
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003043 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003044 Diag(AtClassLoc, diag::warn_forward_class_redefinition)
3045 << IdentList[i];
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003046 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3047 continue;
3048 }
Fariborz Jahanian0d451812009-05-07 21:49:26 +00003049 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003050 }
Douglas Gregordc9166c2011-12-15 20:29:51 +00003051
3052 // Create a declaration to describe this forward declaration.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003053 ObjCInterfaceDecl *PrevIDecl
3054 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidisdd710632013-06-18 21:26:33 +00003055
3056 IdentifierInfo *ClassName = IdentList[i];
3057 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
3058 // A previous decl with a different name is because of
3059 // @compatibility_alias, for example:
3060 // \code
3061 // @class NewImage;
3062 // @compatibility_alias OldImage NewImage;
3063 // \endcode
3064 // A lookup for 'OldImage' will return the 'NewImage' decl.
3065 //
3066 // In such a case use the real declaration name, instead of the alias one,
3067 // otherwise we will break IdentifierResolver and redecls-chain invariants.
3068 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
3069 // has been aliased.
3070 ClassName = PrevIDecl->getIdentifier();
3071 }
3072
Douglas Gregor85f3f952015-07-07 03:57:15 +00003073 // If this forward declaration has type parameters, compare them with the
3074 // type parameters of the previous declaration.
3075 ObjCTypeParamList *TypeParams = TypeParamLists[i];
3076 if (PrevIDecl && TypeParams) {
3077 if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) {
3078 // Check for consistency with the previous declaration.
3079 if (checkTypeParamListConsistency(
3080 *this, PrevTypeParams, TypeParams,
3081 TypeParamListContext::ForwardDeclaration)) {
3082 TypeParams = nullptr;
3083 }
3084 } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
3085 // The @interface does not have type parameters. Complain.
3086 Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class)
3087 << ClassName
3088 << TypeParams->getSourceRange();
3089 Diag(Def->getLocation(), diag::note_defined_here)
3090 << ClassName;
3091
3092 TypeParams = nullptr;
3093 }
3094 }
3095
Douglas Gregordc9166c2011-12-15 20:29:51 +00003096 ObjCInterfaceDecl *IDecl
3097 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00003098 ClassName, TypeParams, PrevIDecl,
3099 IdentLocs[i]);
Douglas Gregordc9166c2011-12-15 20:29:51 +00003100 IDecl->setAtEndRange(IdentLocs[i]);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003101
Douglas Gregordc9166c2011-12-15 20:29:51 +00003102 PushOnScopeChains(IDecl, TUScope);
Douglas Gregordeafd0b2011-12-27 22:43:10 +00003103 CheckObjCDeclScope(IDecl);
3104 DeclsInGroup.push_back(IDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003105 }
Rafael Espindolaab417692013-07-09 12:05:01 +00003106
Richard Smith3beb7c62017-01-12 02:27:38 +00003107 return BuildDeclaratorGroup(DeclsInGroup);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003108}
3109
John McCall54507ab2011-06-16 01:15:19 +00003110static bool tryMatchRecordTypes(ASTContext &Context,
3111 Sema::MethodMatchStrategy strategy,
3112 const Type *left, const Type *right);
3113
John McCall31168b02011-06-15 23:02:42 +00003114static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
3115 QualType leftQT, QualType rightQT) {
3116 const Type *left =
3117 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
3118 const Type *right =
3119 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
3120
3121 if (left == right) return true;
3122
3123 // If we're doing a strict match, the types have to match exactly.
3124 if (strategy == Sema::MMS_strict) return false;
3125
3126 if (left->isIncompleteType() || right->isIncompleteType()) return false;
3127
3128 // Otherwise, use this absurdly complicated algorithm to try to
3129 // validate the basic, low-level compatibility of the two types.
3130
3131 // As a minimum, require the sizes and alignments to match.
David Majnemer34b57492014-07-30 01:30:47 +00003132 TypeInfo LeftTI = Context.getTypeInfo(left);
3133 TypeInfo RightTI = Context.getTypeInfo(right);
3134 if (LeftTI.Width != RightTI.Width)
3135 return false;
3136
3137 if (LeftTI.Align != RightTI.Align)
John McCall31168b02011-06-15 23:02:42 +00003138 return false;
3139
3140 // Consider all the kinds of non-dependent canonical types:
3141 // - functions and arrays aren't possible as return and parameter types
3142
3143 // - vector types of equal size can be arbitrarily mixed
3144 if (isa<VectorType>(left)) return isa<VectorType>(right);
3145 if (isa<VectorType>(right)) return false;
3146
3147 // - references should only match references of identical type
John McCall54507ab2011-06-16 01:15:19 +00003148 // - structs, unions, and Objective-C objects must match more-or-less
3149 // exactly
John McCall31168b02011-06-15 23:02:42 +00003150 // - everything else should be a scalar
3151 if (!left->isScalarType() || !right->isScalarType())
John McCall54507ab2011-06-16 01:15:19 +00003152 return tryMatchRecordTypes(Context, strategy, left, right);
John McCall31168b02011-06-15 23:02:42 +00003153
John McCall9320b872011-09-09 05:25:32 +00003154 // Make scalars agree in kind, except count bools as chars, and group
3155 // all non-member pointers together.
John McCall31168b02011-06-15 23:02:42 +00003156 Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
3157 Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
3158 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
3159 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
John McCall9320b872011-09-09 05:25:32 +00003160 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
3161 leftSK = Type::STK_ObjCObjectPointer;
3162 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
3163 rightSK = Type::STK_ObjCObjectPointer;
John McCall31168b02011-06-15 23:02:42 +00003164
3165 // Note that data member pointers and function member pointers don't
3166 // intermix because of the size differences.
3167
3168 return (leftSK == rightSK);
3169}
Chris Lattnerda463fe2007-12-12 07:09:47 +00003170
John McCall54507ab2011-06-16 01:15:19 +00003171static bool tryMatchRecordTypes(ASTContext &Context,
3172 Sema::MethodMatchStrategy strategy,
3173 const Type *lt, const Type *rt) {
3174 assert(lt && rt && lt != rt);
3175
3176 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
3177 RecordDecl *left = cast<RecordType>(lt)->getDecl();
3178 RecordDecl *right = cast<RecordType>(rt)->getDecl();
3179
3180 // Require union-hood to match.
3181 if (left->isUnion() != right->isUnion()) return false;
3182
3183 // Require an exact match if either is non-POD.
3184 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
3185 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
3186 return false;
3187
3188 // Require size and alignment to match.
David Majnemer34b57492014-07-30 01:30:47 +00003189 TypeInfo LeftTI = Context.getTypeInfo(lt);
3190 TypeInfo RightTI = Context.getTypeInfo(rt);
3191 if (LeftTI.Width != RightTI.Width)
3192 return false;
3193
3194 if (LeftTI.Align != RightTI.Align)
3195 return false;
John McCall54507ab2011-06-16 01:15:19 +00003196
3197 // Require fields to match.
3198 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
3199 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
3200 for (; li != le && ri != re; ++li, ++ri) {
3201 if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
3202 return false;
3203 }
3204 return (li == le && ri == re);
3205}
3206
Chris Lattnerda463fe2007-12-12 07:09:47 +00003207/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
3208/// returns true, or false, accordingly.
3209/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
John McCall31168b02011-06-15 23:02:42 +00003210bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
3211 const ObjCMethodDecl *right,
3212 MethodMatchStrategy strategy) {
Alp Toker314cc812014-01-25 16:55:45 +00003213 if (!matchTypes(Context, strategy, left->getReturnType(),
3214 right->getReturnType()))
John McCall31168b02011-06-15 23:02:42 +00003215 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003216
Douglas Gregor560b7fa2013-02-07 19:13:24 +00003217 // If either is hidden, it is not considered to match.
3218 if (left->isHidden() || right->isHidden())
3219 return false;
3220
David Blaikiebbafb8a2012-03-11 07:00:24 +00003221 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003222 (left->hasAttr<NSReturnsRetainedAttr>()
3223 != right->hasAttr<NSReturnsRetainedAttr>() ||
3224 left->hasAttr<NSConsumesSelfAttr>()
3225 != right->hasAttr<NSConsumesSelfAttr>()))
3226 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003227
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00003228 ObjCMethodDecl::param_const_iterator
Douglas Gregor0bf70f42012-05-17 23:13:29 +00003229 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
3230 re = right->param_end();
Mike Stump11289f42009-09-09 15:08:12 +00003231
Douglas Gregor0bf70f42012-05-17 23:13:29 +00003232 for (; li != le && ri != re; ++li, ++ri) {
John McCall31168b02011-06-15 23:02:42 +00003233 assert(ri != right->param_end() && "Param mismatch");
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00003234 const ParmVarDecl *lparm = *li, *rparm = *ri;
John McCall31168b02011-06-15 23:02:42 +00003235
3236 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
3237 return false;
3238
David Blaikiebbafb8a2012-03-11 07:00:24 +00003239 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003240 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
3241 return false;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003242 }
3243 return true;
3244}
3245
Manman Ren71224532016-04-09 18:59:48 +00003246static bool isMethodContextSameForKindofLookup(ObjCMethodDecl *Method,
3247 ObjCMethodDecl *MethodInList) {
3248 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3249 auto *MethodInListProtocol =
3250 dyn_cast<ObjCProtocolDecl>(MethodInList->getDeclContext());
3251 // If this method belongs to a protocol but the method in list does not, or
3252 // vice versa, we say the context is not the same.
3253 if ((MethodProtocol && !MethodInListProtocol) ||
3254 (!MethodProtocol && MethodInListProtocol))
3255 return false;
3256
3257 if (MethodProtocol && MethodInListProtocol)
3258 return true;
3259
3260 ObjCInterfaceDecl *MethodInterface = Method->getClassInterface();
3261 ObjCInterfaceDecl *MethodInListInterface =
3262 MethodInList->getClassInterface();
3263 return MethodInterface == MethodInListInterface;
3264}
3265
Nico Weber2e0c8f72014-12-27 03:58:08 +00003266void Sema::addMethodToGlobalList(ObjCMethodList *List,
3267 ObjCMethodDecl *Method) {
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003268 // Record at the head of the list whether there were 0, 1, or >= 2 methods
3269 // inside categories.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003270 if (ObjCCategoryDecl *CD =
3271 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
Argyrios Kyrtzidis04703a62013-04-27 00:10:12 +00003272 if (!CD->IsClassExtension() && List->getBits() < 2)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003273 List->setBits(List->getBits() + 1);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003274
Douglas Gregorc454afe2012-01-25 00:19:56 +00003275 // If the list is empty, make it a singleton list.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003276 if (List->getMethod() == nullptr) {
3277 List->setMethod(Method);
Craig Topperc3ec1492014-05-26 06:22:03 +00003278 List->setNext(nullptr);
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003279 return;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003280 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003281
Douglas Gregorc454afe2012-01-25 00:19:56 +00003282 // We've seen a method with this name, see if we have already seen this type
3283 // signature.
3284 ObjCMethodList *Previous = List;
Manman Ren051d0b62016-04-13 23:43:56 +00003285 ObjCMethodList *ListWithSameDeclaration = nullptr;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003286 for (; List; Previous = List, List = List->getNext()) {
Douglas Gregor600a2f52013-06-21 00:20:25 +00003287 // If we are building a module, keep all of the methods.
Richard Smithbbcc9f02016-08-26 00:14:38 +00003288 if (getLangOpts().isCompilingModule())
Douglas Gregor600a2f52013-06-21 00:20:25 +00003289 continue;
3290
Manman Ren051d0b62016-04-13 23:43:56 +00003291 bool SameDeclaration = MatchTwoMethodDeclarations(Method,
3292 List->getMethod());
Manman Ren71224532016-04-09 18:59:48 +00003293 // Looking for method with a type bound requires the correct context exists.
Manman Ren051d0b62016-04-13 23:43:56 +00003294 // We need to insert a method into the list if the context is different.
3295 // If the method's declaration matches the list
3296 // a> the method belongs to a different context: we need to insert it, in
3297 // order to emit the availability message, we need to prioritize over
3298 // availability among the methods with the same declaration.
3299 // b> the method belongs to the same context: there is no need to insert a
3300 // new entry.
3301 // If the method's declaration does not match the list, we insert it to the
3302 // end.
3303 if (!SameDeclaration ||
Manman Ren71224532016-04-09 18:59:48 +00003304 !isMethodContextSameForKindofLookup(Method, List->getMethod())) {
Fariborz Jahaniand436b2a2015-04-07 16:56:27 +00003305 // Even if two method types do not match, we would like to say
3306 // there is more than one declaration so unavailability/deprecated
3307 // warning is not too noisy.
3308 if (!Method->isDefined())
3309 List->setHasMoreThanOneDecl(true);
Manman Ren051d0b62016-04-13 23:43:56 +00003310
3311 // For methods with the same declaration, the one that is deprecated
3312 // should be put in the front for better diagnostics.
3313 if (Method->isDeprecated() && SameDeclaration &&
3314 !ListWithSameDeclaration && !List->getMethod()->isDeprecated())
3315 ListWithSameDeclaration = List;
3316
3317 if (Method->isUnavailable() && SameDeclaration &&
3318 !ListWithSameDeclaration &&
3319 List->getMethod()->getAvailability() < AR_Deprecated)
3320 ListWithSameDeclaration = List;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003321 continue;
Fariborz Jahaniand436b2a2015-04-07 16:56:27 +00003322 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003323
3324 ObjCMethodDecl *PrevObjCMethod = List->getMethod();
Douglas Gregorc454afe2012-01-25 00:19:56 +00003325
3326 // Propagate the 'defined' bit.
3327 if (Method->isDefined())
3328 PrevObjCMethod->setDefined(true);
Nico Webere3b11042014-12-27 07:09:37 +00003329 else {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003330 // Objective-C doesn't allow an @interface for a class after its
3331 // @implementation. So if Method is not defined and there already is
3332 // an entry for this type signature, Method has to be for a different
3333 // class than PrevObjCMethod.
3334 List->setHasMoreThanOneDecl(true);
3335 }
3336
Douglas Gregorc454afe2012-01-25 00:19:56 +00003337 // If a method is deprecated, push it in the global pool.
3338 // This is used for better diagnostics.
3339 if (Method->isDeprecated()) {
3340 if (!PrevObjCMethod->isDeprecated())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003341 List->setMethod(Method);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003342 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003343 // If the new method is unavailable, push it into global pool
Douglas Gregorc454afe2012-01-25 00:19:56 +00003344 // unless previous one is deprecated.
3345 if (Method->isUnavailable()) {
3346 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003347 List->setMethod(Method);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003348 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003349
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003350 return;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003351 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003352
Douglas Gregorc454afe2012-01-25 00:19:56 +00003353 // We have a new signature for an existing method - add it.
3354 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
Douglas Gregore1716012012-01-25 00:49:42 +00003355 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
Manman Ren71224532016-04-09 18:59:48 +00003356
Manman Ren051d0b62016-04-13 23:43:56 +00003357 // We insert it right before ListWithSameDeclaration.
3358 if (ListWithSameDeclaration) {
3359 auto *List = new (Mem) ObjCMethodList(*ListWithSameDeclaration);
3360 // FIXME: should we clear the other bits in ListWithSameDeclaration?
3361 ListWithSameDeclaration->setMethod(Method);
3362 ListWithSameDeclaration->setNext(List);
Manman Ren71224532016-04-09 18:59:48 +00003363 return;
3364 }
3365
Nico Weber2e0c8f72014-12-27 03:58:08 +00003366 Previous->setNext(new (Mem) ObjCMethodList(Method));
Douglas Gregorc454afe2012-01-25 00:19:56 +00003367}
3368
Sebastian Redl75d8a322010-08-02 23:18:59 +00003369/// \brief Read the contents of the method pool for a given selector from
3370/// external storage.
Douglas Gregore1716012012-01-25 00:49:42 +00003371void Sema::ReadMethodPool(Selector Sel) {
Douglas Gregorc78d3462009-04-24 21:10:55 +00003372 assert(ExternalSource && "We need an external AST source");
Douglas Gregore1716012012-01-25 00:49:42 +00003373 ExternalSource->ReadMethodPool(Sel);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003374}
3375
Manman Rena0f31a02016-04-29 19:04:05 +00003376void Sema::updateOutOfDateSelector(Selector Sel) {
3377 if (!ExternalSource)
3378 return;
3379 ExternalSource->updateOutOfDateSelector(Sel);
3380}
3381
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003382void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
Sebastian Redl75d8a322010-08-02 23:18:59 +00003383 bool instance) {
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00003384 // Ignore methods of invalid containers.
3385 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003386 return;
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00003387
Douglas Gregor70f449b2012-01-25 00:59:09 +00003388 if (ExternalSource)
3389 ReadMethodPool(Method->getSelector());
3390
Sebastian Redl75d8a322010-08-02 23:18:59 +00003391 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
Douglas Gregor70f449b2012-01-25 00:59:09 +00003392 if (Pos == MethodPool.end())
3393 Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
3394 GlobalMethods())).first;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003395
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003396 Method->setDefined(impl);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003397
Sebastian Redl75d8a322010-08-02 23:18:59 +00003398 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003399 addMethodToGlobalList(&Entry, Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003400}
3401
John McCall31168b02011-06-15 23:02:42 +00003402/// Determines if this is an "acceptable" loose mismatch in the global
3403/// method pool. This exists mostly as a hack to get around certain
3404/// global mismatches which we can't afford to make warnings / errors.
3405/// Really, what we want is a way to take a method out of the global
3406/// method pool.
3407static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
3408 ObjCMethodDecl *other) {
3409 if (!chosen->isInstanceMethod())
3410 return false;
3411
3412 Selector sel = chosen->getSelector();
3413 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
3414 return false;
3415
3416 // Don't complain about mismatches for -length if the method we
3417 // chose has an integral result type.
Alp Toker314cc812014-01-25 16:55:45 +00003418 return (chosen->getReturnType()->isIntegerType());
John McCall31168b02011-06-15 23:02:42 +00003419}
3420
Manman Ren7ed4f982016-04-07 19:32:24 +00003421/// Return true if the given method is wthin the type bound.
3422static bool FilterMethodsByTypeBound(ObjCMethodDecl *Method,
3423 const ObjCObjectType *TypeBound) {
3424 if (!TypeBound)
3425 return true;
3426
3427 if (TypeBound->isObjCId())
3428 // FIXME: should we handle the case of bounding to id<A, B> differently?
3429 return true;
3430
3431 auto *BoundInterface = TypeBound->getInterface();
3432 assert(BoundInterface && "unexpected object type!");
3433
3434 // Check if the Method belongs to a protocol. We should allow any method
3435 // defined in any protocol, because any subclass could adopt the protocol.
3436 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3437 if (MethodProtocol) {
3438 return true;
3439 }
3440
3441 // If the Method belongs to a class, check if it belongs to the class
3442 // hierarchy of the class bound.
3443 if (ObjCInterfaceDecl *MethodInterface = Method->getClassInterface()) {
3444 // We allow methods declared within classes that are part of the hierarchy
3445 // of the class bound (superclass of, subclass of, or the same as the class
3446 // bound).
3447 return MethodInterface == BoundInterface ||
3448 MethodInterface->isSuperClassOf(BoundInterface) ||
3449 BoundInterface->isSuperClassOf(MethodInterface);
3450 }
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003451 llvm_unreachable("unknown method context");
Manman Ren7ed4f982016-04-07 19:32:24 +00003452}
3453
Manman Rend2a3cd72016-04-07 19:30:20 +00003454/// We first select the type of the method: Instance or Factory, then collect
3455/// all methods with that type.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003456bool Sema::CollectMultipleMethodsInGlobalPool(
Manman Rend2a3cd72016-04-07 19:30:20 +00003457 Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods,
Manman Ren7ed4f982016-04-07 19:32:24 +00003458 bool InstanceFirst, bool CheckTheOther,
3459 const ObjCObjectType *TypeBound) {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003460 if (ExternalSource)
3461 ReadMethodPool(Sel);
3462
3463 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3464 if (Pos == MethodPool.end())
3465 return false;
Manman Rend2a3cd72016-04-07 19:30:20 +00003466
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003467 // Gather the non-hidden methods.
Manman Rend2a3cd72016-04-07 19:30:20 +00003468 ObjCMethodList &MethList = InstanceFirst ? Pos->second.first :
3469 Pos->second.second;
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003470 for (ObjCMethodList *M = &MethList; M; M = M->getNext())
Manman Ren7ed4f982016-04-07 19:32:24 +00003471 if (M->getMethod() && !M->getMethod()->isHidden()) {
3472 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3473 Methods.push_back(M->getMethod());
3474 }
Manman Rend2a3cd72016-04-07 19:30:20 +00003475
3476 // Return if we find any method with the desired kind.
3477 if (!Methods.empty())
3478 return Methods.size() > 1;
3479
3480 if (!CheckTheOther)
3481 return false;
3482
3483 // Gather the other kind.
3484 ObjCMethodList &MethList2 = InstanceFirst ? Pos->second.second :
3485 Pos->second.first;
3486 for (ObjCMethodList *M = &MethList2; M; M = M->getNext())
Manman Ren7ed4f982016-04-07 19:32:24 +00003487 if (M->getMethod() && !M->getMethod()->isHidden()) {
3488 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3489 Methods.push_back(M->getMethod());
3490 }
Manman Rend2a3cd72016-04-07 19:30:20 +00003491
Nico Weber2e0c8f72014-12-27 03:58:08 +00003492 return Methods.size() > 1;
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003493}
3494
Manman Rend2a3cd72016-04-07 19:30:20 +00003495bool Sema::AreMultipleMethodsInGlobalPool(
3496 Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R,
3497 bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl *> &Methods) {
3498 // Diagnose finding more than one method in global pool.
3499 SmallVector<ObjCMethodDecl *, 4> FilteredMethods;
3500 FilteredMethods.push_back(BestMethod);
3501
3502 for (auto *M : Methods)
3503 if (M != BestMethod && !M->hasAttr<UnavailableAttr>())
3504 FilteredMethods.push_back(M);
3505
3506 if (FilteredMethods.size() > 1)
3507 DiagnoseMultipleMethodInGlobalPool(FilteredMethods, Sel, R,
3508 receiverIdOrClass);
3509
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003510 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
Nico Weber2e0c8f72014-12-27 03:58:08 +00003511 // Test for no method in the pool which should not trigger any warning by
3512 // caller.
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003513 if (Pos == MethodPool.end())
3514 return true;
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003515 ObjCMethodList &MethList =
3516 BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003517 return MethList.hasMoreThanOneDecl();
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003518}
3519
Sebastian Redl75d8a322010-08-02 23:18:59 +00003520ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00003521 bool receiverIdOrClass,
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003522 bool instance) {
Douglas Gregor70f449b2012-01-25 00:59:09 +00003523 if (ExternalSource)
3524 ReadMethodPool(Sel);
3525
Sebastian Redl75d8a322010-08-02 23:18:59 +00003526 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
Douglas Gregor70f449b2012-01-25 00:59:09 +00003527 if (Pos == MethodPool.end())
Craig Topperc3ec1492014-05-26 06:22:03 +00003528 return nullptr;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003529
Douglas Gregor77f49a42013-01-16 18:47:38 +00003530 // Gather the non-hidden methods.
Sebastian Redl75d8a322010-08-02 23:18:59 +00003531 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00003532 SmallVector<ObjCMethodDecl *, 4> Methods;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003533 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003534 if (M->getMethod() && !M->getMethod()->isHidden())
3535 return M->getMethod();
Douglas Gregorc78d3462009-04-24 21:10:55 +00003536 }
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003537 return nullptr;
3538}
Douglas Gregor77f49a42013-01-16 18:47:38 +00003539
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003540void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3541 Selector Sel, SourceRange R,
3542 bool receiverIdOrClass) {
Douglas Gregor77f49a42013-01-16 18:47:38 +00003543 // We found multiple methods, so we may have to complain.
3544 bool issueDiagnostic = false, issueError = false;
Jonathan Roelofs74411362015-04-28 18:04:44 +00003545
Douglas Gregor77f49a42013-01-16 18:47:38 +00003546 // We support a warning which complains about *any* difference in
3547 // method signature.
3548 bool strictSelectorMatch =
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003549 receiverIdOrClass &&
3550 !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
Douglas Gregor77f49a42013-01-16 18:47:38 +00003551 if (strictSelectorMatch) {
3552 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3553 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
3554 issueDiagnostic = true;
3555 break;
3556 }
3557 }
3558 }
Jonathan Roelofs74411362015-04-28 18:04:44 +00003559
Douglas Gregor77f49a42013-01-16 18:47:38 +00003560 // If we didn't see any strict differences, we won't see any loose
3561 // differences. In ARC, however, we also need to check for loose
3562 // mismatches, because most of them are errors.
3563 if (!strictSelectorMatch ||
3564 (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
3565 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3566 // This checks if the methods differ in type mismatch.
3567 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
3568 !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
3569 issueDiagnostic = true;
3570 if (getLangOpts().ObjCAutoRefCount)
3571 issueError = true;
3572 break;
3573 }
3574 }
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003575
Douglas Gregor77f49a42013-01-16 18:47:38 +00003576 if (issueDiagnostic) {
3577 if (issueError)
3578 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
3579 else if (strictSelectorMatch)
3580 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
3581 else
3582 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003583
Douglas Gregor77f49a42013-01-16 18:47:38 +00003584 Diag(Methods[0]->getLocStart(),
3585 issueError ? diag::note_possibility : diag::note_using)
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003586 << Methods[0]->getSourceRange();
Douglas Gregor77f49a42013-01-16 18:47:38 +00003587 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3588 Diag(Methods[I]->getLocStart(), diag::note_also_found)
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003589 << Methods[I]->getSourceRange();
3590 }
Douglas Gregor77f49a42013-01-16 18:47:38 +00003591 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003592}
3593
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003594ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
Sebastian Redl75d8a322010-08-02 23:18:59 +00003595 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3596 if (Pos == MethodPool.end())
Craig Topperc3ec1492014-05-26 06:22:03 +00003597 return nullptr;
Sebastian Redl75d8a322010-08-02 23:18:59 +00003598
3599 GlobalMethods &Methods = Pos->second;
Fariborz Jahanianec762bd2014-03-26 20:59:26 +00003600 for (const ObjCMethodList *Method = &Methods.first; Method;
3601 Method = Method->getNext())
Fariborz Jahanian4019c7f2015-02-19 21:52:41 +00003602 if (Method->getMethod() &&
3603 (Method->getMethod()->isDefined() ||
3604 Method->getMethod()->isPropertyAccessor()))
Nico Weber2e0c8f72014-12-27 03:58:08 +00003605 return Method->getMethod();
Fariborz Jahanianec762bd2014-03-26 20:59:26 +00003606
3607 for (const ObjCMethodList *Method = &Methods.second; Method;
3608 Method = Method->getNext())
Fariborz Jahanian4019c7f2015-02-19 21:52:41 +00003609 if (Method->getMethod() &&
3610 (Method->getMethod()->isDefined() ||
3611 Method->getMethod()->isPropertyAccessor()))
Nico Weber2e0c8f72014-12-27 03:58:08 +00003612 return Method->getMethod();
Craig Topperc3ec1492014-05-26 06:22:03 +00003613 return nullptr;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003614}
3615
Fariborz Jahanian42f89382013-05-30 21:48:58 +00003616static void
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003617HelperSelectorsForTypoCorrection(
3618 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
3619 StringRef Typo, const ObjCMethodDecl * Method) {
3620 const unsigned MaxEditDistance = 1;
3621 unsigned BestEditDistance = MaxEditDistance + 1;
Richard Trieuea8d3702013-06-06 02:22:29 +00003622 std::string MethodName = Method->getSelector().getAsString();
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003623
3624 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
3625 if (MinPossibleEditDistance > 0 &&
3626 Typo.size() / MinPossibleEditDistance < 1)
3627 return;
3628 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
3629 if (EditDistance > MaxEditDistance)
3630 return;
3631 if (EditDistance == BestEditDistance)
3632 BestMethod.push_back(Method);
3633 else if (EditDistance < BestEditDistance) {
3634 BestMethod.clear();
3635 BestMethod.push_back(Method);
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003636 }
3637}
3638
Fariborz Jahanian75481672013-06-17 17:10:54 +00003639static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
3640 QualType ObjectType) {
3641 if (ObjectType.isNull())
3642 return true;
3643 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
3644 return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003645 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
3646 nullptr;
Fariborz Jahanian75481672013-06-17 17:10:54 +00003647}
3648
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003649const ObjCMethodDecl *
Fariborz Jahanian75481672013-06-17 17:10:54 +00003650Sema::SelectorsForTypoCorrection(Selector Sel,
3651 QualType ObjectType) {
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003652 unsigned NumArgs = Sel.getNumArgs();
3653 SmallVector<const ObjCMethodDecl *, 8> Methods;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003654 bool ObjectIsId = true, ObjectIsClass = true;
3655 if (ObjectType.isNull())
3656 ObjectIsId = ObjectIsClass = false;
3657 else if (!ObjectType->isObjCObjectPointerType())
Craig Topperc3ec1492014-05-26 06:22:03 +00003658 return nullptr;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003659 else if (const ObjCObjectPointerType *ObjCPtr =
3660 ObjectType->getAsObjCInterfacePointerType()) {
3661 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
3662 ObjectIsId = ObjectIsClass = false;
3663 }
3664 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
3665 ObjectIsClass = false;
3666 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
3667 ObjectIsId = false;
3668 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003669 return nullptr;
3670
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003671 for (GlobalMethodPool::iterator b = MethodPool.begin(),
3672 e = MethodPool.end(); b != e; b++) {
3673 // instance methods
3674 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003675 if (M->getMethod() &&
3676 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3677 (M->getMethod()->getSelector() != Sel)) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003678 if (ObjectIsId)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003679 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003680 else if (!ObjectIsClass &&
Nico Weber2e0c8f72014-12-27 03:58:08 +00003681 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3682 ObjectType))
3683 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003684 }
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003685 // class methods
3686 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003687 if (M->getMethod() &&
3688 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3689 (M->getMethod()->getSelector() != Sel)) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003690 if (ObjectIsClass)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003691 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003692 else if (!ObjectIsId &&
Nico Weber2e0c8f72014-12-27 03:58:08 +00003693 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3694 ObjectType))
3695 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003696 }
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003697 }
3698
3699 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
3700 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
3701 HelperSelectorsForTypoCorrection(SelectedMethods,
3702 Sel.getAsString(), Methods[i]);
3703 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003704 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003705}
3706
Fariborz Jahanian42f89382013-05-30 21:48:58 +00003707/// DiagnoseDuplicateIvars -
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003708/// Check for duplicate ivars in the entire class at the start of
James Dennett634962f2012-06-14 21:40:34 +00003709/// \@implementation. This becomes necesssary because class extension can
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003710/// add ivars to a class in random order which will not be known until
James Dennett634962f2012-06-14 21:40:34 +00003711/// class's \@implementation is seen.
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003712void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
3713 ObjCInterfaceDecl *SID) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00003714 for (auto *Ivar : ID->ivars()) {
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003715 if (Ivar->isInvalidDecl())
3716 continue;
3717 if (IdentifierInfo *II = Ivar->getIdentifier()) {
3718 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
3719 if (prevIvar) {
3720 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3721 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
3722 Ivar->setInvalidDecl();
3723 }
3724 }
3725 }
3726}
3727
John McCallb61e14e2015-10-27 04:54:50 +00003728/// Diagnose attempts to define ARC-__weak ivars when __weak is disabled.
3729static void DiagnoseWeakIvars(Sema &S, ObjCImplementationDecl *ID) {
3730 if (S.getLangOpts().ObjCWeak) return;
3731
3732 for (auto ivar = ID->getClassInterface()->all_declared_ivar_begin();
3733 ivar; ivar = ivar->getNextIvar()) {
3734 if (ivar->isInvalidDecl()) continue;
3735 if (ivar->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
3736 if (S.getLangOpts().ObjCWeakRuntime) {
3737 S.Diag(ivar->getLocation(), diag::err_arc_weak_disabled);
3738 } else {
3739 S.Diag(ivar->getLocation(), diag::err_arc_weak_no_runtime);
3740 }
3741 }
3742 }
3743}
3744
Volodymyr Sapsai30680e92017-10-23 22:01:41 +00003745/// Diagnose attempts to use flexible array member with retainable object type.
3746static void DiagnoseRetainableFlexibleArrayMember(Sema &S,
3747 ObjCInterfaceDecl *ID) {
3748 if (!S.getLangOpts().ObjCAutoRefCount)
3749 return;
3750
3751 for (auto ivar = ID->all_declared_ivar_begin(); ivar;
3752 ivar = ivar->getNextIvar()) {
3753 if (ivar->isInvalidDecl())
3754 continue;
3755 QualType IvarTy = ivar->getType();
3756 if (IvarTy->isIncompleteArrayType() &&
3757 (IvarTy.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) &&
3758 IvarTy->isObjCLifetimeType()) {
3759 S.Diag(ivar->getLocation(), diag::err_flexible_array_arc_retainable);
3760 ivar->setInvalidDecl();
3761 }
3762 }
3763}
3764
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003765Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
3766 switch (CurContext->getDeclKind()) {
3767 case Decl::ObjCInterface:
3768 return Sema::OCK_Interface;
3769 case Decl::ObjCProtocol:
3770 return Sema::OCK_Protocol;
3771 case Decl::ObjCCategory:
Benjamin Kramera008d3a2015-04-10 11:37:55 +00003772 if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003773 return Sema::OCK_ClassExtension;
Benjamin Kramera008d3a2015-04-10 11:37:55 +00003774 return Sema::OCK_Category;
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003775 case Decl::ObjCImplementation:
3776 return Sema::OCK_Implementation;
3777 case Decl::ObjCCategoryImpl:
3778 return Sema::OCK_CategoryImplementation;
3779
3780 default:
3781 return Sema::OCK_None;
3782 }
3783}
3784
Volodymyr Sapsai30680e92017-10-23 22:01:41 +00003785static bool IsVariableSizedType(QualType T) {
3786 if (T->isIncompleteArrayType())
3787 return true;
3788 const auto *RecordTy = T->getAs<RecordType>();
3789 return (RecordTy && RecordTy->getDecl()->hasFlexibleArrayMember());
3790}
3791
3792static void DiagnoseVariableSizedIvars(Sema &S, ObjCContainerDecl *OCD) {
3793 ObjCInterfaceDecl *IntfDecl = nullptr;
3794 ObjCInterfaceDecl::ivar_range Ivars = llvm::make_range(
3795 ObjCInterfaceDecl::ivar_iterator(), ObjCInterfaceDecl::ivar_iterator());
3796 if ((IntfDecl = dyn_cast<ObjCInterfaceDecl>(OCD))) {
3797 Ivars = IntfDecl->ivars();
3798 } else if (auto *ImplDecl = dyn_cast<ObjCImplementationDecl>(OCD)) {
3799 IntfDecl = ImplDecl->getClassInterface();
3800 Ivars = ImplDecl->ivars();
3801 } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(OCD)) {
3802 if (CategoryDecl->IsClassExtension()) {
3803 IntfDecl = CategoryDecl->getClassInterface();
3804 Ivars = CategoryDecl->ivars();
3805 }
3806 }
3807
3808 // Check if variable sized ivar is in interface and visible to subclasses.
3809 if (!isa<ObjCInterfaceDecl>(OCD)) {
3810 for (auto ivar : Ivars) {
3811 if (!ivar->isInvalidDecl() && IsVariableSizedType(ivar->getType())) {
3812 S.Diag(ivar->getLocation(), diag::warn_variable_sized_ivar_visibility)
3813 << ivar->getDeclName() << ivar->getType();
3814 }
3815 }
3816 }
3817
3818 // Subsequent checks require interface decl.
3819 if (!IntfDecl)
3820 return;
3821
3822 // Check if variable sized ivar is followed by another ivar.
3823 for (ObjCIvarDecl *ivar = IntfDecl->all_declared_ivar_begin(); ivar;
3824 ivar = ivar->getNextIvar()) {
3825 if (ivar->isInvalidDecl() || !ivar->getNextIvar())
3826 continue;
3827 QualType IvarTy = ivar->getType();
3828 bool IsInvalidIvar = false;
3829 if (IvarTy->isIncompleteArrayType()) {
3830 S.Diag(ivar->getLocation(), diag::err_flexible_array_not_at_end)
3831 << ivar->getDeclName() << IvarTy
3832 << TTK_Class; // Use "class" for Obj-C.
3833 IsInvalidIvar = true;
3834 } else if (const RecordType *RecordTy = IvarTy->getAs<RecordType>()) {
3835 if (RecordTy->getDecl()->hasFlexibleArrayMember()) {
3836 S.Diag(ivar->getLocation(),
3837 diag::err_objc_variable_sized_type_not_at_end)
3838 << ivar->getDeclName() << IvarTy;
3839 IsInvalidIvar = true;
3840 }
3841 }
3842 if (IsInvalidIvar) {
3843 S.Diag(ivar->getNextIvar()->getLocation(),
3844 diag::note_next_ivar_declaration)
3845 << ivar->getNextIvar()->getSynthesize();
3846 ivar->setInvalidDecl();
3847 }
3848 }
3849
3850 // Check if ObjC container adds ivars after variable sized ivar in superclass.
3851 // Perform the check only if OCD is the first container to declare ivars to
3852 // avoid multiple warnings for the same ivar.
3853 ObjCIvarDecl *FirstIvar =
3854 (Ivars.begin() == Ivars.end()) ? nullptr : *Ivars.begin();
3855 if (FirstIvar && (FirstIvar == IntfDecl->all_declared_ivar_begin())) {
3856 const ObjCInterfaceDecl *SuperClass = IntfDecl->getSuperClass();
3857 while (SuperClass && SuperClass->ivar_empty())
3858 SuperClass = SuperClass->getSuperClass();
3859 if (SuperClass) {
3860 auto IvarIter = SuperClass->ivar_begin();
3861 std::advance(IvarIter, SuperClass->ivar_size() - 1);
3862 const ObjCIvarDecl *LastIvar = *IvarIter;
3863 if (IsVariableSizedType(LastIvar->getType())) {
3864 S.Diag(FirstIvar->getLocation(),
3865 diag::warn_superclass_variable_sized_type_not_at_end)
3866 << FirstIvar->getDeclName() << LastIvar->getDeclName()
3867 << LastIvar->getType() << SuperClass->getDeclName();
3868 S.Diag(LastIvar->getLocation(), diag::note_entity_declared_at)
3869 << LastIvar->getDeclName();
3870 }
3871 }
3872 }
3873}
3874
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003875// Note: For class/category implementations, allMethods is always null.
Robert Wilhelm57c67112013-07-17 21:14:35 +00003876Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
Fariborz Jahaniandfb76872013-07-17 00:05:08 +00003877 ArrayRef<DeclGroupPtrTy> allTUVars) {
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003878 if (getObjCContainerKind() == Sema::OCK_None)
Craig Topperc3ec1492014-05-26 06:22:03 +00003879 return nullptr;
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003880
3881 assert(AtEnd.isValid() && "Invalid location for '@end'");
3882
George Burgess IV00f70bd2018-03-01 05:43:23 +00003883 auto *OCD = cast<ObjCContainerDecl>(CurContext);
3884 Decl *ClassDecl = OCD;
3885
Mike Stump11289f42009-09-09 15:08:12 +00003886 bool isInterfaceDeclKind =
Chris Lattner219b3e92008-03-16 21:17:37 +00003887 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
3888 || isa<ObjCProtocolDecl>(ClassDecl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003889 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
Steve Naroffb3a87982009-01-09 15:36:25 +00003890
Steve Naroff35c62ae2009-01-08 17:28:14 +00003891 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
3892 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
3893 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
3894
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003895 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003896 ObjCMethodDecl *Method =
John McCall48871652010-08-21 09:40:31 +00003897 cast_or_null<ObjCMethodDecl>(allMethods[i]);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003898
3899 if (!Method) continue; // Already issued a diagnostic.
Douglas Gregorffca3a22009-01-09 17:18:27 +00003900 if (Method->isInstanceMethod()) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00003901 /// Check for instance method of the same name with incompatible types
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003902 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
Mike Stump11289f42009-09-09 15:08:12 +00003903 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
Chris Lattnerda463fe2007-12-12 07:09:47 +00003904 : false;
Mike Stump11289f42009-09-09 15:08:12 +00003905 if ((isInterfaceDeclKind && PrevMethod && !match)
Eli Friedman42b1e9e2008-12-16 20:15:50 +00003906 || (checkIdenticalMethods && match)) {
Chris Lattner0369c572008-11-23 23:12:31 +00003907 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00003908 << Method->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003909 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Douglas Gregor87e92752010-12-21 17:34:17 +00003910 Method->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00003911 } else {
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003912 if (PrevMethod) {
Argyrios Kyrtzidisdcaaa212011-10-14 08:02:31 +00003913 Method->setAsRedeclaration(PrevMethod);
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003914 if (!Context.getSourceManager().isInSystemHeader(
3915 Method->getLocation()))
3916 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3917 << Method->getDeclName();
3918 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3919 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003920 InsMap[Method->getSelector()] = Method;
3921 /// The following allows us to typecheck messages to "id".
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003922 AddInstanceMethodToGlobalPool(Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003923 }
Mike Stump12b8ce12009-08-04 21:02:39 +00003924 } else {
Chris Lattnerda463fe2007-12-12 07:09:47 +00003925 /// Check for class method of the same name with incompatible types
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003926 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
Mike Stump11289f42009-09-09 15:08:12 +00003927 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
Chris Lattnerda463fe2007-12-12 07:09:47 +00003928 : false;
Mike Stump11289f42009-09-09 15:08:12 +00003929 if ((isInterfaceDeclKind && PrevMethod && !match)
Eli Friedman42b1e9e2008-12-16 20:15:50 +00003930 || (checkIdenticalMethods && match)) {
Chris Lattner0369c572008-11-23 23:12:31 +00003931 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00003932 << Method->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003933 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Douglas Gregor87e92752010-12-21 17:34:17 +00003934 Method->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00003935 } else {
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003936 if (PrevMethod) {
Argyrios Kyrtzidisdcaaa212011-10-14 08:02:31 +00003937 Method->setAsRedeclaration(PrevMethod);
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003938 if (!Context.getSourceManager().isInSystemHeader(
3939 Method->getLocation()))
3940 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3941 << Method->getDeclName();
3942 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3943 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003944 ClsMap[Method->getSelector()] = Method;
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003945 AddFactoryMethodToGlobalPool(Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003946 }
3947 }
3948 }
Douglas Gregorb8982092013-01-21 19:42:21 +00003949 if (isa<ObjCInterfaceDecl>(ClassDecl)) {
3950 // Nothing to do here.
Steve Naroffb3a87982009-01-09 15:36:25 +00003951 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
Fariborz Jahanian62293f42008-12-06 19:59:02 +00003952 // Categories are used to extend the class by declaring new methods.
Mike Stump11289f42009-09-09 15:08:12 +00003953 // By the same token, they are also used to add new properties. No
Fariborz Jahanian62293f42008-12-06 19:59:02 +00003954 // need to compare the added property to those in the class.
Daniel Dunbar4684f372008-08-27 05:40:03 +00003955
Fariborz Jahanianc21f5432010-12-10 23:36:33 +00003956 if (C->IsClassExtension()) {
3957 ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
3958 DiagnoseClassExtensionDupMethods(C, CCPrimary);
Fariborz Jahanianc21f5432010-12-10 23:36:33 +00003959 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003960 }
Steve Naroffb3a87982009-01-09 15:36:25 +00003961 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
Fariborz Jahanian30a42922010-02-15 21:55:26 +00003962 if (CDecl->getIdentifier())
3963 // ProcessPropertyDecl is responsible for diagnosing conflicts with any
3964 // user-defined setter/getter. It also synthesizes setter/getter methods
3965 // and adds them to the DeclContext and global method pools.
Manman Renefe1bac2016-01-27 20:00:32 +00003966 for (auto *I : CDecl->properties())
Douglas Gregore17765e2015-11-03 17:02:34 +00003967 ProcessPropertyDecl(I);
Ted Kremenekc7c64312010-01-07 01:20:12 +00003968 CDecl->setAtEndRange(AtEnd);
Steve Naroffb3a87982009-01-09 15:36:25 +00003969 }
3970 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
Ted Kremenekc7c64312010-01-07 01:20:12 +00003971 IC->setAtEndRange(AtEnd);
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00003972 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003973 // Any property declared in a class extension might have user
3974 // declared setter or getter in current class extension or one
3975 // of the other class extensions. Mark them as synthesized as
3976 // property will be synthesized when property with same name is
3977 // seen in the @implementation.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00003978 for (const auto *Ext : IDecl->visible_extensions()) {
Manman Rena7a8b1f2016-01-26 18:05:23 +00003979 for (const auto *Property : Ext->instance_properties()) {
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003980 // Skip over properties declared @dynamic
3981 if (const ObjCPropertyImplDecl *PIDecl
Manman Ren5b786402016-01-28 18:49:28 +00003982 = IC->FindPropertyImplDecl(Property->getIdentifier(),
3983 Property->getQueryKind()))
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003984 if (PIDecl->getPropertyImplementation()
3985 == ObjCPropertyImplDecl::Dynamic)
3986 continue;
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003987
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00003988 for (const auto *Ext : IDecl->visible_extensions()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003989 if (ObjCMethodDecl *GetterMethod
3990 = Ext->getInstanceMethod(Property->getGetterName()))
Jordan Rosed01e83a2012-10-10 16:42:25 +00003991 GetterMethod->setPropertyAccessor(true);
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003992 if (!Property->isReadOnly())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003993 if (ObjCMethodDecl *SetterMethod
3994 = Ext->getInstanceMethod(Property->getSetterName()))
Jordan Rosed01e83a2012-10-10 16:42:25 +00003995 SetterMethod->setPropertyAccessor(true);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003996 }
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003997 }
3998 }
Fariborz Jahanian25491a22010-05-05 21:52:17 +00003999 ImplMethodsVsClassMethods(S, IC, IDecl);
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00004000 AtomicPropertySetterGetterRules(IC, IDecl);
John McCall31168b02011-06-15 23:02:42 +00004001 DiagnoseOwningPropertyGetterSynthesis(IC);
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004002 DiagnoseUnusedBackingIvarInAccessor(S, IC);
Fariborz Jahanian20cfff32015-03-11 16:59:48 +00004003 if (IDecl->hasDesignatedInitializers())
4004 DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
John McCallb61e14e2015-10-27 04:54:50 +00004005 DiagnoseWeakIvars(*this, IC);
Volodymyr Sapsai30680e92017-10-23 22:01:41 +00004006 DiagnoseRetainableFlexibleArrayMember(*this, IDecl);
Argyrios Kyrtzidisdb5ce0f2013-12-03 21:11:54 +00004007
Patrick Beardacfbe9e2012-04-06 18:12:22 +00004008 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
Craig Topperc3ec1492014-05-26 06:22:03 +00004009 if (IDecl->getSuperClass() == nullptr) {
Patrick Beardacfbe9e2012-04-06 18:12:22 +00004010 // This class has no superclass, so check that it has been marked with
4011 // __attribute((objc_root_class)).
4012 if (!HasRootClassAttr) {
4013 SourceLocation DeclLoc(IDecl->getLocation());
Alp Tokerb6cc5922014-05-03 03:45:55 +00004014 SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
Patrick Beardacfbe9e2012-04-06 18:12:22 +00004015 Diag(DeclLoc, diag::warn_objc_root_class_missing)
4016 << IDecl->getIdentifier();
4017 // See if NSObject is in the current scope, and if it is, suggest
4018 // adding " : NSObject " to the class declaration.
4019 NamedDecl *IF = LookupSingleName(TUScope,
4020 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
4021 DeclLoc, LookupOrdinaryName);
4022 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
4023 if (NSObjectDecl && NSObjectDecl->getDefinition()) {
4024 Diag(SuperClassLoc, diag::note_objc_needs_superclass)
4025 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
4026 } else {
4027 Diag(SuperClassLoc, diag::note_objc_needs_superclass);
4028 }
4029 }
4030 } else if (HasRootClassAttr) {
4031 // Complain that only root classes may have this attribute.
4032 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
4033 }
4034
Alex Lorenza8c44ba2016-10-28 10:25:10 +00004035 if (const ObjCInterfaceDecl *Super = IDecl->getSuperClass()) {
4036 // An interface can subclass another interface with a
4037 // objc_subclassing_restricted attribute when it has that attribute as
4038 // well (because of interfaces imported from Swift). Therefore we have
4039 // to check if we can subclass in the implementation as well.
4040 if (IDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
4041 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
4042 Diag(IC->getLocation(), diag::err_restricted_superclass_mismatch);
4043 Diag(Super->getLocation(), diag::note_class_declared);
4044 }
4045 }
4046
John McCall5fb5df92012-06-20 06:18:46 +00004047 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian545643c2010-02-23 23:41:11 +00004048 while (IDecl->getSuperClass()) {
4049 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
4050 IDecl = IDecl->getSuperClass();
4051 }
Patrick Beardacfbe9e2012-04-06 18:12:22 +00004052 }
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00004053 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004054 SetIvarInitializers(IC);
Mike Stump11289f42009-09-09 15:08:12 +00004055 } else if (ObjCCategoryImplDecl* CatImplClass =
Steve Naroffb3a87982009-01-09 15:36:25 +00004056 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
Ted Kremenekc7c64312010-01-07 01:20:12 +00004057 CatImplClass->setAtEndRange(AtEnd);
Mike Stump11289f42009-09-09 15:08:12 +00004058
Chris Lattnerda463fe2007-12-12 07:09:47 +00004059 // Find category interface decl and then check that all methods declared
Daniel Dunbar4684f372008-08-27 05:40:03 +00004060 // in this interface are implemented in the category @implementation.
Chris Lattner41fd42e2009-02-16 18:32:47 +00004061 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00004062 if (ObjCCategoryDecl *Cat
4063 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
4064 ImplMethodsVsClassMethods(S, CatImplClass, Cat);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004065 }
4066 }
Alex Lorenza8c44ba2016-10-28 10:25:10 +00004067 } else if (const auto *IntfDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
4068 if (const ObjCInterfaceDecl *Super = IntfDecl->getSuperClass()) {
4069 if (!IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
4070 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
4071 Diag(IntfDecl->getLocation(), diag::err_restricted_superclass_mismatch);
4072 Diag(Super->getLocation(), diag::note_class_declared);
4073 }
4074 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00004075 }
Volodymyr Sapsai30680e92017-10-23 22:01:41 +00004076 DiagnoseVariableSizedIvars(*this, OCD);
Chris Lattner5bbb3c82009-03-29 16:50:03 +00004077 if (isInterfaceDeclKind) {
4078 // Reject invalid vardecls.
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00004079 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00004080 DeclGroupRef DG = allTUVars[i].get();
Chris Lattner5bbb3c82009-03-29 16:50:03 +00004081 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
4082 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
Daniel Dunbar0ca16602009-04-14 02:25:56 +00004083 if (!VDecl->hasExternalStorage())
Steve Naroff42959b22009-04-13 17:58:46 +00004084 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
Fariborz Jahanian629aed92009-03-21 18:06:45 +00004085 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00004086 }
Fariborz Jahanian3654e652009-03-18 22:33:24 +00004087 }
Fariborz Jahanian4327b322011-08-29 17:33:12 +00004088 ActOnObjCContainerFinishDefinition();
Argyrios Kyrtzidisbd8b1502011-10-17 19:48:13 +00004089
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00004090 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00004091 DeclGroupRef DG = allTUVars[i].get();
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004092 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
4093 (*I)->setTopLevelDeclInObjCContainer();
Argyrios Kyrtzidisbd8b1502011-10-17 19:48:13 +00004094 Consumer.HandleTopLevelDeclInObjCContainer(DG);
4095 }
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00004096
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +00004097 ActOnDocumentableDecl(ClassDecl);
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00004098 return ClassDecl;
Chris Lattnerda463fe2007-12-12 07:09:47 +00004099}
4100
Chris Lattnerda463fe2007-12-12 07:09:47 +00004101/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
4102/// objective-c's type qualifier from the parser version of the same info.
Mike Stump11289f42009-09-09 15:08:12 +00004103static Decl::ObjCDeclQualifier
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004104CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
John McCallca872902011-05-01 03:04:29 +00004105 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
Chris Lattnerda463fe2007-12-12 07:09:47 +00004106}
4107
Douglas Gregor33823722011-06-11 01:09:30 +00004108/// \brief Check whether the declared result type of the given Objective-C
4109/// method declaration is compatible with the method's class.
4110///
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004111static Sema::ResultTypeCompatibilityKind
Douglas Gregor33823722011-06-11 01:09:30 +00004112CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
4113 ObjCInterfaceDecl *CurrentClass) {
Alp Toker314cc812014-01-25 16:55:45 +00004114 QualType ResultType = Method->getReturnType();
4115
Douglas Gregor33823722011-06-11 01:09:30 +00004116 // If an Objective-C method inherits its related result type, then its
4117 // declared result type must be compatible with its own class type. The
4118 // declared result type is compatible if:
4119 if (const ObjCObjectPointerType *ResultObjectType
4120 = ResultType->getAs<ObjCObjectPointerType>()) {
4121 // - it is id or qualified id, or
4122 if (ResultObjectType->isObjCIdType() ||
4123 ResultObjectType->isObjCQualifiedIdType())
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004124 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00004125
4126 if (CurrentClass) {
4127 if (ObjCInterfaceDecl *ResultClass
4128 = ResultObjectType->getInterfaceDecl()) {
4129 // - it is the same as the method's class type, or
Douglas Gregor0b144e12011-12-15 00:29:59 +00004130 if (declaresSameEntity(CurrentClass, ResultClass))
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004131 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00004132
4133 // - it is a superclass of the method's class type
4134 if (ResultClass->isSuperClassOf(CurrentClass))
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004135 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00004136 }
Douglas Gregorbab8a962011-09-08 01:46:34 +00004137 } else {
4138 // Any Objective-C pointer type might be acceptable for a protocol
4139 // method; we just don't know.
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004140 return Sema::RTC_Unknown;
Douglas Gregor33823722011-06-11 01:09:30 +00004141 }
4142 }
4143
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004144 return Sema::RTC_Incompatible;
Douglas Gregor33823722011-06-11 01:09:30 +00004145}
4146
John McCalld2930c22011-07-22 02:45:48 +00004147namespace {
4148/// A helper class for searching for methods which a particular method
4149/// overrides.
4150class OverrideSearch {
Daniel Dunbard6d74c32012-02-29 03:04:05 +00004151public:
John McCalld2930c22011-07-22 02:45:48 +00004152 Sema &S;
4153 ObjCMethodDecl *Method;
Akira Hatanaka4c687f32018-02-06 23:44:40 +00004154 llvm::SmallSetVector<ObjCMethodDecl*, 4> Overridden;
John McCalld2930c22011-07-22 02:45:48 +00004155 bool Recursive;
4156
4157public:
4158 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
4159 Selector selector = method->getSelector();
4160
4161 // Bypass this search if we've never seen an instance/class method
4162 // with this selector before.
4163 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
4164 if (it == S.MethodPool.end()) {
Axel Naumanndd433f02012-10-18 19:05:02 +00004165 if (!S.getExternalSource()) return;
Douglas Gregore1716012012-01-25 00:49:42 +00004166 S.ReadMethodPool(selector);
4167
4168 it = S.MethodPool.find(selector);
4169 if (it == S.MethodPool.end())
4170 return;
John McCalld2930c22011-07-22 02:45:48 +00004171 }
4172 ObjCMethodList &list =
4173 method->isInstanceMethod() ? it->second.first : it->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00004174 if (!list.getMethod()) return;
John McCalld2930c22011-07-22 02:45:48 +00004175
4176 ObjCContainerDecl *container
4177 = cast<ObjCContainerDecl>(method->getDeclContext());
4178
4179 // Prevent the search from reaching this container again. This is
4180 // important with categories, which override methods from the
4181 // interface and each other.
Douglas Gregorcf4ac442012-05-03 21:25:24 +00004182 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) {
4183 searchFromContainer(container);
Douglas Gregorc5928af2012-05-17 22:39:14 +00004184 if (ObjCInterfaceDecl *Interface = Category->getClassInterface())
4185 searchFromContainer(Interface);
Douglas Gregorcf4ac442012-05-03 21:25:24 +00004186 } else {
4187 searchFromContainer(container);
4188 }
Douglas Gregor33823722011-06-11 01:09:30 +00004189 }
John McCalld2930c22011-07-22 02:45:48 +00004190
Akira Hatanaka4c687f32018-02-06 23:44:40 +00004191 typedef decltype(Overridden)::iterator iterator;
John McCalld2930c22011-07-22 02:45:48 +00004192 iterator begin() const { return Overridden.begin(); }
4193 iterator end() const { return Overridden.end(); }
4194
4195private:
4196 void searchFromContainer(ObjCContainerDecl *container) {
4197 if (container->isInvalidDecl()) return;
4198
4199 switch (container->getDeclKind()) {
4200#define OBJCCONTAINER(type, base) \
4201 case Decl::type: \
4202 searchFrom(cast<type##Decl>(container)); \
4203 break;
4204#define ABSTRACT_DECL(expansion)
4205#define DECL(type, base) \
4206 case Decl::type:
4207#include "clang/AST/DeclNodes.inc"
4208 llvm_unreachable("not an ObjC container!");
4209 }
4210 }
4211
4212 void searchFrom(ObjCProtocolDecl *protocol) {
Douglas Gregore6e48b12012-01-01 19:29:29 +00004213 if (!protocol->hasDefinition())
4214 return;
4215
John McCalld2930c22011-07-22 02:45:48 +00004216 // A method in a protocol declaration overrides declarations from
4217 // referenced ("parent") protocols.
4218 search(protocol->getReferencedProtocols());
4219 }
4220
4221 void searchFrom(ObjCCategoryDecl *category) {
4222 // A method in a category declaration overrides declarations from
4223 // the main class and from protocols the category references.
Douglas Gregorcf4ac442012-05-03 21:25:24 +00004224 // The main class is handled in the constructor.
John McCalld2930c22011-07-22 02:45:48 +00004225 search(category->getReferencedProtocols());
4226 }
4227
4228 void searchFrom(ObjCCategoryImplDecl *impl) {
4229 // A method in a category definition that has a category
4230 // declaration overrides declarations from the category
4231 // declaration.
4232 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
4233 search(category);
Douglas Gregorc5928af2012-05-17 22:39:14 +00004234 if (ObjCInterfaceDecl *Interface = category->getClassInterface())
4235 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00004236
4237 // Otherwise it overrides declarations from the class.
Douglas Gregorc5928af2012-05-17 22:39:14 +00004238 } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) {
4239 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00004240 }
4241 }
4242
4243 void searchFrom(ObjCInterfaceDecl *iface) {
4244 // A method in a class declaration overrides declarations from
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00004245 if (!iface->hasDefinition())
4246 return;
4247
John McCalld2930c22011-07-22 02:45:48 +00004248 // - categories,
Aaron Ballman15063e12014-03-13 21:35:02 +00004249 for (auto *Cat : iface->known_categories())
4250 search(Cat);
John McCalld2930c22011-07-22 02:45:48 +00004251
4252 // - the super class, and
4253 if (ObjCInterfaceDecl *super = iface->getSuperClass())
4254 search(super);
4255
4256 // - any referenced protocols.
4257 search(iface->getReferencedProtocols());
4258 }
4259
4260 void searchFrom(ObjCImplementationDecl *impl) {
4261 // A method in a class implementation overrides declarations from
4262 // the class interface.
Douglas Gregorc5928af2012-05-17 22:39:14 +00004263 if (ObjCInterfaceDecl *Interface = impl->getClassInterface())
4264 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00004265 }
4266
John McCalld2930c22011-07-22 02:45:48 +00004267 void search(const ObjCProtocolList &protocols) {
4268 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
4269 i != e; ++i)
4270 search(*i);
4271 }
4272
4273 void search(ObjCContainerDecl *container) {
John McCalld2930c22011-07-22 02:45:48 +00004274 // Check for a method in this container which matches this selector.
4275 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
Argyrios Kyrtzidisbd8cd3e2013-03-29 21:51:48 +00004276 Method->isInstanceMethod(),
4277 /*AllowHidden=*/true);
John McCalld2930c22011-07-22 02:45:48 +00004278
4279 // If we find one, record it and bail out.
4280 if (meth) {
4281 Overridden.insert(meth);
4282 return;
4283 }
4284
4285 // Otherwise, search for methods that a hypothetical method here
4286 // would have overridden.
4287
4288 // Note that we're now in a recursive case.
4289 Recursive = true;
4290
4291 searchFromContainer(container);
4292 }
4293};
Hans Wennborgdcfba332015-10-06 23:40:43 +00004294} // end anonymous namespace
Douglas Gregor33823722011-06-11 01:09:30 +00004295
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004296void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
4297 ObjCInterfaceDecl *CurrentClass,
4298 ResultTypeCompatibilityKind RTC) {
4299 // Search for overridden methods and merge information down from them.
4300 OverrideSearch overrides(*this, ObjCMethod);
4301 // Keep track if the method overrides any method in the class's base classes,
4302 // its protocols, or its categories' protocols; we will keep that info
4303 // in the ObjCMethodDecl.
4304 // For this info, a method in an implementation is not considered as
4305 // overriding the same method in the interface or its categories.
4306 bool hasOverriddenMethodsInBaseOrProtocol = false;
4307 for (OverrideSearch::iterator
4308 i = overrides.begin(), e = overrides.end(); i != e; ++i) {
4309 ObjCMethodDecl *overridden = *i;
4310
Argyrios Kyrtzidisc2091d52013-04-17 00:09:08 +00004311 if (!hasOverriddenMethodsInBaseOrProtocol) {
4312 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
4313 CurrentClass != overridden->getClassInterface() ||
4314 overridden->isOverriding()) {
4315 hasOverriddenMethodsInBaseOrProtocol = true;
4316
4317 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
4318 // OverrideSearch will return as "overridden" the same method in the
4319 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
4320 // check whether a category of a base class introduced a method with the
4321 // same selector, after the interface method declaration.
4322 // To avoid unnecessary lookups in the majority of cases, we use the
4323 // extra info bits in GlobalMethodPool to check whether there were any
4324 // category methods with this selector.
4325 GlobalMethodPool::iterator It =
4326 MethodPool.find(ObjCMethod->getSelector());
4327 if (It != MethodPool.end()) {
4328 ObjCMethodList &List =
4329 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
4330 unsigned CategCount = List.getBits();
4331 if (CategCount > 0) {
4332 // If the method is in a category we'll do lookup if there were at
4333 // least 2 category methods recorded, otherwise only one will do.
4334 if (CategCount > 1 ||
4335 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
4336 OverrideSearch overrides(*this, overridden);
4337 for (OverrideSearch::iterator
4338 OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) {
4339 ObjCMethodDecl *SuperOverridden = *OI;
Argyrios Kyrtzidis04703a62013-04-27 00:10:12 +00004340 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
4341 CurrentClass != SuperOverridden->getClassInterface()) {
Argyrios Kyrtzidisc2091d52013-04-17 00:09:08 +00004342 hasOverriddenMethodsInBaseOrProtocol = true;
4343 overridden->setOverriding(true);
4344 break;
4345 }
4346 }
4347 }
4348 }
4349 }
4350 }
4351 }
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004352
4353 // Propagate down the 'related result type' bit from overridden methods.
4354 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
4355 ObjCMethod->SetRelatedResultType();
4356
4357 // Then merge the declarations.
4358 mergeObjCMethodDecls(ObjCMethod, overridden);
4359
4360 if (ObjCMethod->isImplicit() && overridden->isImplicit())
4361 continue; // Conflicting properties are detected elsewhere.
4362
4363 // Check for overriding methods
4364 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
4365 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
4366 CheckConflictingOverridingMethod(ObjCMethod, overridden,
4367 isa<ObjCProtocolDecl>(overridden->getDeclContext()));
4368
4369 if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
Fariborz Jahanian31a25682012-07-05 22:26:07 +00004370 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
4371 !overridden->isImplicit() /* not meant for properties */) {
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004372 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
4373 E = ObjCMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +00004374 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
4375 PrevE = overridden->param_end();
4376 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004377 assert(PrevI != overridden->param_end() && "Param mismatch");
4378 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
4379 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
4380 // If type of argument of method in this class does not match its
4381 // respective argument type in the super class method, issue warning;
4382 if (!Context.typesAreCompatible(T1, T2)) {
4383 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
4384 << T1 << T2;
4385 Diag(overridden->getLocation(), diag::note_previous_declaration);
4386 break;
4387 }
4388 }
4389 }
4390 }
4391
4392 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
4393}
4394
Douglas Gregor813a0662015-06-19 18:14:38 +00004395/// Merge type nullability from for a redeclaration of the same entity,
4396/// producing the updated type of the redeclared entity.
4397static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc,
4398 QualType type,
4399 bool usesCSKeyword,
4400 SourceLocation prevLoc,
4401 QualType prevType,
4402 bool prevUsesCSKeyword) {
4403 // Determine the nullability of both types.
4404 auto nullability = type->getNullability(S.Context);
4405 auto prevNullability = prevType->getNullability(S.Context);
4406
4407 // Easy case: both have nullability.
4408 if (nullability.hasValue() == prevNullability.hasValue()) {
4409 // Neither has nullability; continue.
4410 if (!nullability)
4411 return type;
4412
4413 // The nullabilities are equivalent; do nothing.
4414 if (*nullability == *prevNullability)
4415 return type;
4416
4417 // Complain about mismatched nullability.
4418 S.Diag(loc, diag::err_nullability_conflicting)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00004419 << DiagNullabilityKind(*nullability, usesCSKeyword)
4420 << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword);
Douglas Gregor813a0662015-06-19 18:14:38 +00004421 return type;
4422 }
4423
4424 // If it's the redeclaration that has nullability, don't change anything.
4425 if (nullability)
4426 return type;
4427
4428 // Otherwise, provide the result with the same nullability.
4429 return S.Context.getAttributedType(
4430 AttributedType::getNullabilityAttrKind(*prevNullability),
4431 type, type);
4432}
4433
NAKAMURA Takumi2df5c3c2015-06-20 03:52:52 +00004434/// Merge information from the declaration of a method in the \@interface
Douglas Gregor813a0662015-06-19 18:14:38 +00004435/// (or a category/extension) into the corresponding method in the
4436/// @implementation (for a class or category).
4437static void mergeInterfaceMethodToImpl(Sema &S,
4438 ObjCMethodDecl *method,
4439 ObjCMethodDecl *prevMethod) {
4440 // Merge the objc_requires_super attribute.
4441 if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() &&
4442 !method->hasAttr<ObjCRequiresSuperAttr>()) {
4443 // merge the attribute into implementation.
4444 method->addAttr(
4445 ObjCRequiresSuperAttr::CreateImplicit(S.Context,
4446 method->getLocation()));
4447 }
4448
4449 // Merge nullability of the result type.
4450 QualType newReturnType
4451 = mergeTypeNullabilityForRedecl(
4452 S, method->getReturnTypeSourceRange().getBegin(),
4453 method->getReturnType(),
4454 method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4455 prevMethod->getReturnTypeSourceRange().getBegin(),
4456 prevMethod->getReturnType(),
4457 prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4458 method->setReturnType(newReturnType);
4459
4460 // Handle each of the parameters.
4461 unsigned numParams = method->param_size();
4462 unsigned numPrevParams = prevMethod->param_size();
4463 for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) {
4464 ParmVarDecl *param = method->param_begin()[i];
4465 ParmVarDecl *prevParam = prevMethod->param_begin()[i];
4466
4467 // Merge nullability.
4468 QualType newParamType
4469 = mergeTypeNullabilityForRedecl(
4470 S, param->getLocation(), param->getType(),
4471 param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4472 prevParam->getLocation(), prevParam->getType(),
4473 prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4474 param->setType(newParamType);
4475 }
4476}
4477
Alex Lorenza8a372d2017-04-27 10:43:48 +00004478/// Verify that the method parameters/return value have types that are supported
4479/// by the x86 target.
4480static void checkObjCMethodX86VectorTypes(Sema &SemaRef,
4481 const ObjCMethodDecl *Method) {
4482 assert(SemaRef.getASTContext().getTargetInfo().getTriple().getArch() ==
4483 llvm::Triple::x86 &&
4484 "x86-specific check invoked for a different target");
4485 SourceLocation Loc;
4486 QualType T;
4487 for (const ParmVarDecl *P : Method->parameters()) {
4488 if (P->getType()->isVectorType()) {
4489 Loc = P->getLocStart();
4490 T = P->getType();
4491 break;
4492 }
4493 }
4494 if (Loc.isInvalid()) {
4495 if (Method->getReturnType()->isVectorType()) {
4496 Loc = Method->getReturnTypeSourceRange().getBegin();
4497 T = Method->getReturnType();
4498 } else
4499 return;
4500 }
4501
4502 // Vector parameters/return values are not supported by objc_msgSend on x86 in
4503 // iOS < 9 and macOS < 10.11.
4504 const auto &Triple = SemaRef.getASTContext().getTargetInfo().getTriple();
4505 VersionTuple AcceptedInVersion;
4506 if (Triple.getOS() == llvm::Triple::IOS)
4507 AcceptedInVersion = VersionTuple(/*Major=*/9);
4508 else if (Triple.isMacOSX())
4509 AcceptedInVersion = VersionTuple(/*Major=*/10, /*Minor=*/11);
4510 else
4511 return;
Alex Lorenza8a372d2017-04-27 10:43:48 +00004512 if (SemaRef.getASTContext().getTargetInfo().getPlatformMinVersion() >=
Alex Lorenz92824832017-05-05 16:15:17 +00004513 AcceptedInVersion)
Alex Lorenza8a372d2017-04-27 10:43:48 +00004514 return;
4515 SemaRef.Diag(Loc, diag::err_objc_method_unsupported_param_ret_type)
4516 << T << (Method->getReturnType()->isVectorType() ? /*return value*/ 1
4517 : /*parameter*/ 0)
4518 << (Triple.isMacOSX() ? "macOS 10.11" : "iOS 9");
4519}
4520
John McCall48871652010-08-21 09:40:31 +00004521Decl *Sema::ActOnMethodDeclaration(
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004522 Scope *S,
Chris Lattnerda463fe2007-12-12 07:09:47 +00004523 SourceLocation MethodLoc, SourceLocation EndLoc,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004524 tok::TokenKind MethodType,
John McCallba7bf592010-08-24 05:47:05 +00004525 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004526 ArrayRef<SourceLocation> SelectorLocs,
Chris Lattnerda463fe2007-12-12 07:09:47 +00004527 Selector Sel,
4528 // optional arguments. The number of types/arguments is obtained
4529 // from the Sel.getNumArgs().
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004530 ObjCArgInfo *ArgInfo,
Fariborz Jahanian60462092010-04-08 00:30:06 +00004531 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
Chris Lattnerda463fe2007-12-12 07:09:47 +00004532 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
Fariborz Jahanianc677f692011-03-12 18:54:30 +00004533 bool isVariadic, bool MethodDefinition) {
Steve Naroff83777fe2008-02-29 21:48:07 +00004534 // Make sure we can establish a context for the method.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004535 if (!CurContext->isObjCContainer()) {
Richard Smithf8812672016-12-02 22:38:31 +00004536 Diag(MethodLoc, diag::err_missing_method_context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004537 return nullptr;
Steve Naroff83777fe2008-02-29 21:48:07 +00004538 }
George Burgess IV00f70bd2018-03-01 05:43:23 +00004539 Decl *ClassDecl = cast<ObjCContainerDecl>(CurContext);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004540 QualType resultDeclType;
Mike Stump11289f42009-09-09 15:08:12 +00004541
Douglas Gregorbab8a962011-09-08 01:46:34 +00004542 bool HasRelatedResultType = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00004543 TypeSourceInfo *ReturnTInfo = nullptr;
Steve Naroff32606412009-02-20 22:59:16 +00004544 if (ReturnType) {
Alp Toker314cc812014-01-25 16:55:45 +00004545 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004546
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004547 if (CheckFunctionReturnType(resultDeclType, MethodLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00004548 return nullptr;
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004549
Douglas Gregor813a0662015-06-19 18:14:38 +00004550 QualType bareResultType = resultDeclType;
4551 (void)AttributedType::stripOuterNullability(bareResultType);
4552 HasRelatedResultType = (bareResultType == Context.getObjCInstanceType());
Fariborz Jahanianb5a52ca2011-07-21 17:00:47 +00004553 } else { // get the type for "id".
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004554 resultDeclType = Context.getObjCIdType();
Fariborz Jahanianb21138f2011-07-21 17:38:14 +00004555 Diag(MethodLoc, diag::warn_missing_method_return_type)
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004556 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
Fariborz Jahanianb5a52ca2011-07-21 17:00:47 +00004557 }
Mike Stump11289f42009-09-09 15:08:12 +00004558
Alp Toker314cc812014-01-25 16:55:45 +00004559 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
4560 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
4561 MethodType == tok::minus, isVariadic,
4562 /*isPropertyAccessor=*/false,
4563 /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
4564 MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
4565 : ObjCMethodDecl::Required,
4566 HasRelatedResultType);
Mike Stump11289f42009-09-09 15:08:12 +00004567
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004568 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump11289f42009-09-09 15:08:12 +00004569
Chris Lattner23b0faf2009-04-11 19:42:43 +00004570 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
John McCall856bbea2009-10-23 21:48:59 +00004571 QualType ArgType;
John McCallbcd03502009-12-07 02:54:59 +00004572 TypeSourceInfo *DI;
Mike Stump11289f42009-09-09 15:08:12 +00004573
David Blaikie7d170102013-05-15 07:37:26 +00004574 if (!ArgInfo[i].Type) {
John McCall856bbea2009-10-23 21:48:59 +00004575 ArgType = Context.getObjCIdType();
Craig Topperc3ec1492014-05-26 06:22:03 +00004576 DI = nullptr;
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004577 } else {
John McCall856bbea2009-10-23 21:48:59 +00004578 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004579 }
Mike Stump11289f42009-09-09 15:08:12 +00004580
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004581 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
Richard Smithbecb92d2017-10-10 22:33:17 +00004582 LookupOrdinaryName, forRedeclarationInCurContext());
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004583 LookupName(R, S);
4584 if (R.isSingleResult()) {
4585 NamedDecl *PrevDecl = R.getFoundDecl();
4586 if (S->isDeclScope(PrevDecl)) {
Fariborz Jahanianc677f692011-03-12 18:54:30 +00004587 Diag(ArgInfo[i].NameLoc,
4588 (MethodDefinition ? diag::warn_method_param_redefinition
4589 : diag::warn_method_param_declaration))
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004590 << ArgInfo[i].Name;
4591 Diag(PrevDecl->getLocation(),
4592 diag::note_previous_declaration);
4593 }
4594 }
4595
Abramo Bagnaradff19302011-03-08 08:55:46 +00004596 SourceLocation StartLoc = DI
4597 ? DI->getTypeLoc().getBeginLoc()
4598 : ArgInfo[i].NameLoc;
4599
John McCalld44f4d72011-04-23 02:46:06 +00004600 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
4601 ArgInfo[i].NameLoc, ArgInfo[i].Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004602 ArgType, DI, SC_None);
Mike Stump11289f42009-09-09 15:08:12 +00004603
John McCall82490832011-05-02 00:30:12 +00004604 Param->setObjCMethodScopeInfo(i);
4605
Chris Lattnerc5ffed42008-04-04 06:12:32 +00004606 Param->setObjCDeclQualifier(
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004607 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
Mike Stump11289f42009-09-09 15:08:12 +00004608
Chris Lattner9713a1c2009-04-11 19:34:56 +00004609 // Apply the attributes to the parameter.
Douglas Gregor758a8692009-06-17 21:51:59 +00004610 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00004611 AddPragmaAttributes(TUScope, Param);
Mike Stump11289f42009-09-09 15:08:12 +00004612
Fariborz Jahanian52d02f62012-01-14 18:44:35 +00004613 if (Param->hasAttr<BlocksAttr>()) {
4614 Diag(Param->getLocation(), diag::err_block_on_nonlocal);
4615 Param->setInvalidDecl();
4616 }
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004617 S->AddDecl(Param);
4618 IdResolver.AddDecl(Param);
4619
Chris Lattnerc5ffed42008-04-04 06:12:32 +00004620 Params.push_back(Param);
4621 }
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004622
Fariborz Jahanian60462092010-04-08 00:30:06 +00004623 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +00004624 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
Fariborz Jahanian60462092010-04-08 00:30:06 +00004625 QualType ArgType = Param->getType();
4626 if (ArgType.isNull())
4627 ArgType = Context.getObjCIdType();
4628 else
4629 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
Douglas Gregor84280642011-07-12 04:42:08 +00004630 ArgType = Context.getAdjustedParameterType(ArgType);
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004631
Fariborz Jahanian60462092010-04-08 00:30:06 +00004632 Param->setDeclContext(ObjCMethod);
Fariborz Jahanian60462092010-04-08 00:30:06 +00004633 Params.push_back(Param);
4634 }
4635
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004636 ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004637 ObjCMethod->setObjCDeclQualifier(
4638 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
Daniel Dunbarc136e0c2008-09-26 04:12:28 +00004639
4640 if (AttrList)
Douglas Gregor758a8692009-06-17 21:51:59 +00004641 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00004642 AddPragmaAttributes(TUScope, ObjCMethod);
Mike Stump11289f42009-09-09 15:08:12 +00004643
Douglas Gregor87e92752010-12-21 17:34:17 +00004644 // Add the method now.
Craig Topperc3ec1492014-05-26 06:22:03 +00004645 const ObjCMethodDecl *PrevMethod = nullptr;
John McCalld2930c22011-07-22 02:45:48 +00004646 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00004647 if (MethodType == tok::minus) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004648 PrevMethod = ImpDecl->getInstanceMethod(Sel);
4649 ImpDecl->addInstanceMethod(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004650 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004651 PrevMethod = ImpDecl->getClassMethod(Sel);
4652 ImpDecl->addClassMethod(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004653 }
Douglas Gregor33823722011-06-11 01:09:30 +00004654
Douglas Gregor813a0662015-06-19 18:14:38 +00004655 // Merge information from the @interface declaration into the
4656 // @implementation.
4657 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) {
4658 if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
4659 ObjCMethod->isInstanceMethod())) {
4660 mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD);
4661
4662 // Warn about defining -dealloc in a category.
4663 if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() &&
4664 ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) {
4665 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
4666 << ObjCMethod->getDeclName();
4667 }
4668 }
Fariborz Jahanian7e350d22013-12-17 22:44:28 +00004669 }
Douglas Gregor87e92752010-12-21 17:34:17 +00004670 } else {
4671 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004672 }
John McCalld2930c22011-07-22 02:45:48 +00004673
Chris Lattnerda463fe2007-12-12 07:09:47 +00004674 if (PrevMethod) {
4675 // You can never have two method definitions with the same name.
Chris Lattner0369c572008-11-23 23:12:31 +00004676 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00004677 << ObjCMethod->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00004678 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian096f7c12013-05-13 17:27:00 +00004679 ObjCMethod->setInvalidDecl();
4680 return ObjCMethod;
Mike Stump11289f42009-09-09 15:08:12 +00004681 }
John McCall28a6aea2009-11-04 02:18:39 +00004682
Douglas Gregor33823722011-06-11 01:09:30 +00004683 // If this Objective-C method does not have a related result type, but we
4684 // are allowed to infer related result types, try to do so based on the
4685 // method family.
4686 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
4687 if (!CurrentClass) {
4688 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
4689 CurrentClass = Cat->getClassInterface();
4690 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
4691 CurrentClass = Impl->getClassInterface();
4692 else if (ObjCCategoryImplDecl *CatImpl
4693 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
4694 CurrentClass = CatImpl->getClassInterface();
4695 }
John McCalld2930c22011-07-22 02:45:48 +00004696
Douglas Gregorbab8a962011-09-08 01:46:34 +00004697 ResultTypeCompatibilityKind RTC
4698 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
John McCalld2930c22011-07-22 02:45:48 +00004699
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004700 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
John McCalld2930c22011-07-22 02:45:48 +00004701
John McCall31168b02011-06-15 23:02:42 +00004702 bool ARCError = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004703 if (getLangOpts().ObjCAutoRefCount)
John McCalle48f3892013-04-04 01:38:37 +00004704 ARCError = CheckARCMethodDecl(ObjCMethod);
John McCall31168b02011-06-15 23:02:42 +00004705
Douglas Gregorbab8a962011-09-08 01:46:34 +00004706 // Infer the related result type when possible.
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004707 if (!ARCError && RTC == Sema::RTC_Compatible &&
Douglas Gregorbab8a962011-09-08 01:46:34 +00004708 !ObjCMethod->hasRelatedResultType() &&
4709 LangOpts.ObjCInferRelatedResultType) {
Douglas Gregor33823722011-06-11 01:09:30 +00004710 bool InferRelatedResultType = false;
4711 switch (ObjCMethod->getMethodFamily()) {
4712 case OMF_None:
4713 case OMF_copy:
4714 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +00004715 case OMF_finalize:
Douglas Gregor33823722011-06-11 01:09:30 +00004716 case OMF_mutableCopy:
4717 case OMF_release:
4718 case OMF_retainCount:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00004719 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00004720 case OMF_performSelector:
Douglas Gregor33823722011-06-11 01:09:30 +00004721 break;
4722
4723 case OMF_alloc:
4724 case OMF_new:
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00004725 InferRelatedResultType = ObjCMethod->isClassMethod();
Douglas Gregor33823722011-06-11 01:09:30 +00004726 break;
4727
4728 case OMF_init:
4729 case OMF_autorelease:
4730 case OMF_retain:
4731 case OMF_self:
4732 InferRelatedResultType = ObjCMethod->isInstanceMethod();
4733 break;
4734 }
4735
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00004736 if (InferRelatedResultType &&
4737 !ObjCMethod->getReturnType()->isObjCIndependentClassType())
Douglas Gregor33823722011-06-11 01:09:30 +00004738 ObjCMethod->SetRelatedResultType();
Douglas Gregor33823722011-06-11 01:09:30 +00004739 }
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00004740
Alex Lorenza8a372d2017-04-27 10:43:48 +00004741 if (MethodDefinition &&
4742 Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
4743 checkObjCMethodX86VectorTypes(*this, ObjCMethod);
4744
Steven Wu3bb4aa52018-04-16 23:34:18 +00004745 // + load method cannot have availability attributes. It get called on
4746 // startup, so it has to have the availability of the deployment target.
4747 if (const auto *attr = ObjCMethod->getAttr<AvailabilityAttr>()) {
4748 if (ObjCMethod->isClassMethod() &&
4749 ObjCMethod->getSelector().getAsString() == "load") {
4750 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
4751 << 0;
4752 ObjCMethod->dropAttr<AvailabilityAttr>();
4753 }
4754 }
4755
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00004756 ActOnDocumentableDecl(ObjCMethod);
4757
John McCall48871652010-08-21 09:40:31 +00004758 return ObjCMethod;
Chris Lattnerda463fe2007-12-12 07:09:47 +00004759}
4760
Chris Lattner438e5012008-12-17 07:13:27 +00004761bool Sema::CheckObjCDeclScope(Decl *D) {
Fariborz Jahanianf36734d2011-08-22 18:34:22 +00004762 // Following is also an error. But it is caused by a missing @end
4763 // and diagnostic is issued elsewhere.
Argyrios Kyrtzidis822c4332012-03-23 23:24:23 +00004764 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004765 return false;
Argyrios Kyrtzidis822c4332012-03-23 23:24:23 +00004766
4767 // If we switched context to translation unit while we are still lexically in
4768 // an objc container, it means the parser missed emitting an error.
4769 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
4770 return false;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004771
Anders Carlssona6b508a2008-11-04 16:57:32 +00004772 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
4773 D->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004774
Anders Carlssona6b508a2008-11-04 16:57:32 +00004775 return true;
4776}
Chris Lattner438e5012008-12-17 07:13:27 +00004777
James Dennett634962f2012-06-14 21:40:34 +00004778/// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
Chris Lattner438e5012008-12-17 07:13:27 +00004779/// instance variables of ClassName into Decls.
John McCall48871652010-08-21 09:40:31 +00004780void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
Chris Lattner438e5012008-12-17 07:13:27 +00004781 IdentifierInfo *ClassName,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004782 SmallVectorImpl<Decl*> &Decls) {
Chris Lattner438e5012008-12-17 07:13:27 +00004783 // Check that ClassName is a valid class
Douglas Gregorb2ccf012010-04-15 22:33:43 +00004784 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
Chris Lattner438e5012008-12-17 07:13:27 +00004785 if (!Class) {
4786 Diag(DeclStart, diag::err_undef_interface) << ClassName;
4787 return;
4788 }
John McCall5fb5df92012-06-20 06:18:46 +00004789 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanianece1b2b2009-04-21 20:28:41 +00004790 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
4791 return;
4792 }
Mike Stump11289f42009-09-09 15:08:12 +00004793
Chris Lattner438e5012008-12-17 07:13:27 +00004794 // Collect the instance variables
Jordy Rosea91768e2011-07-22 02:08:32 +00004795 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004796 Context.DeepCollectObjCIvars(Class, true, Ivars);
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004797 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004798 for (unsigned i = 0; i < Ivars.size(); i++) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00004799 const FieldDecl* ID = Ivars[i];
John McCall48871652010-08-21 09:40:31 +00004800 RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
Abramo Bagnaradff19302011-03-08 08:55:46 +00004801 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
4802 /*FIXME: StartL=*/ID->getLocation(),
4803 ID->getLocation(),
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004804 ID->getIdentifier(), ID->getType(),
4805 ID->getBitWidth());
John McCall48871652010-08-21 09:40:31 +00004806 Decls.push_back(FD);
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004807 }
Mike Stump11289f42009-09-09 15:08:12 +00004808
Chris Lattner438e5012008-12-17 07:13:27 +00004809 // Introduce all of these fields into the appropriate scope.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004810 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
Chris Lattner438e5012008-12-17 07:13:27 +00004811 D != Decls.end(); ++D) {
John McCall48871652010-08-21 09:40:31 +00004812 FieldDecl *FD = cast<FieldDecl>(*D);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004813 if (getLangOpts().CPlusPlus)
George Burgess IV00f70bd2018-03-01 05:43:23 +00004814 PushOnScopeChains(FD, S);
John McCall48871652010-08-21 09:40:31 +00004815 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004816 Record->addDecl(FD);
Chris Lattner438e5012008-12-17 07:13:27 +00004817 }
4818}
4819
Douglas Gregorf3564192010-04-26 17:32:49 +00004820/// \brief Build a type-check a new Objective-C exception variable declaration.
Abramo Bagnaradff19302011-03-08 08:55:46 +00004821VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
4822 SourceLocation StartLoc,
4823 SourceLocation IdLoc,
4824 IdentifierInfo *Id,
Douglas Gregorf3564192010-04-26 17:32:49 +00004825 bool Invalid) {
4826 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
4827 // duration shall not be qualified by an address-space qualifier."
4828 // Since all parameters have automatic store duration, they can not have
4829 // an address space.
Alexander Richardson6d989432017-10-15 18:48:14 +00004830 if (T.getAddressSpace() != LangAS::Default) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004831 Diag(IdLoc, diag::err_arg_with_address_space);
Douglas Gregorf3564192010-04-26 17:32:49 +00004832 Invalid = true;
4833 }
4834
4835 // An @catch parameter must be an unqualified object pointer type;
4836 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
4837 if (Invalid) {
4838 // Don't do any further checking.
Douglas Gregorf4e837f2010-04-26 17:57:08 +00004839 } else if (T->isDependentType()) {
4840 // Okay: we don't know what this type will instantiate to.
Douglas Gregorf3564192010-04-26 17:32:49 +00004841 } else if (!T->isObjCObjectPointerType()) {
4842 Invalid = true;
Abramo Bagnaradff19302011-03-08 08:55:46 +00004843 Diag(IdLoc ,diag::err_catch_param_not_objc_type);
Douglas Gregorf3564192010-04-26 17:32:49 +00004844 } else if (T->isObjCQualifiedIdType()) {
4845 Invalid = true;
Abramo Bagnaradff19302011-03-08 08:55:46 +00004846 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00004847 }
4848
Abramo Bagnaradff19302011-03-08 08:55:46 +00004849 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004850 T, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00004851 New->setExceptionVariable(true);
4852
Douglas Gregor8ca0c642011-12-10 01:22:52 +00004853 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004854 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
Douglas Gregor8ca0c642011-12-10 01:22:52 +00004855 Invalid = true;
4856
Douglas Gregorf3564192010-04-26 17:32:49 +00004857 if (Invalid)
4858 New->setInvalidDecl();
4859 return New;
4860}
4861
John McCall48871652010-08-21 09:40:31 +00004862Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
Douglas Gregorf3564192010-04-26 17:32:49 +00004863 const DeclSpec &DS = D.getDeclSpec();
4864
4865 // We allow the "register" storage class on exception variables because
4866 // GCC did, but we drop it completely. Any other storage class is an error.
4867 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
4868 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
4869 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
Richard Smithb4a9e862013-04-12 22:46:28 +00004870 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
Douglas Gregorf3564192010-04-26 17:32:49 +00004871 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
Richard Smithb4a9e862013-04-12 22:46:28 +00004872 << DeclSpec::getSpecifierName(SCS);
4873 }
Richard Smith62f19e72016-06-25 00:15:56 +00004874 if (DS.isInlineSpecified())
4875 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004876 << getLangOpts().CPlusPlus17;
Richard Smithb4a9e862013-04-12 22:46:28 +00004877 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
4878 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
4879 diag::err_invalid_thread)
4880 << DeclSpec::getSpecifierName(TSCS);
Douglas Gregorf3564192010-04-26 17:32:49 +00004881 D.getMutableDeclSpec().ClearStorageClassSpecs();
4882
Richard Smithb1402ae2013-03-18 22:52:47 +00004883 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregorf3564192010-04-26 17:32:49 +00004884
4885 // Check that there are no default arguments inside the type of this
4886 // exception object (C++ only).
David Blaikiebbafb8a2012-03-11 07:00:24 +00004887 if (getLangOpts().CPlusPlus)
Douglas Gregorf3564192010-04-26 17:32:49 +00004888 CheckExtraCXXDefaultArguments(D);
4889
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00004890 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00004891 QualType ExceptionType = TInfo->getType();
Douglas Gregorf3564192010-04-26 17:32:49 +00004892
Abramo Bagnaradff19302011-03-08 08:55:46 +00004893 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
4894 D.getSourceRange().getBegin(),
4895 D.getIdentifierLoc(),
4896 D.getIdentifier(),
Douglas Gregorf3564192010-04-26 17:32:49 +00004897 D.isInvalidType());
4898
4899 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
4900 if (D.getCXXScopeSpec().isSet()) {
4901 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
4902 << D.getCXXScopeSpec().getRange();
4903 New->setInvalidDecl();
4904 }
4905
4906 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00004907 S->AddDecl(New);
Douglas Gregorf3564192010-04-26 17:32:49 +00004908 if (D.getIdentifier())
4909 IdResolver.AddDecl(New);
4910
4911 ProcessDeclAttributes(S, New, D);
4912
4913 if (New->hasAttr<BlocksAttr>())
4914 Diag(New->getLocation(), diag::err_block_on_nonlocal);
John McCall48871652010-08-21 09:40:31 +00004915 return New;
Douglas Gregore11ee112010-04-23 23:01:43 +00004916}
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004917
4918/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004919/// initialization.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004920void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004921 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004922 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
4923 Iv= Iv->getNextIvar()) {
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004924 QualType QT = Context.getBaseElementType(Iv->getType());
Douglas Gregor527786e2010-05-20 02:24:22 +00004925 if (QT->isRecordType())
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004926 Ivars.push_back(Iv);
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004927 }
4928}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004929
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004930void Sema::DiagnoseUseOfUnimplementedSelectors() {
Douglas Gregor72e357f2011-07-28 14:54:22 +00004931 // Load referenced selectors from the external source.
4932 if (ExternalSource) {
4933 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
4934 ExternalSource->ReadReferencedSelectors(Sels);
4935 for (unsigned I = 0, N = Sels.size(); I != N; ++I)
4936 ReferencedSelectors[Sels[I].first] = Sels[I].second;
4937 }
4938
Fariborz Jahanianc9b7c202011-02-04 23:19:27 +00004939 // Warning will be issued only when selector table is
4940 // generated (which means there is at lease one implementation
4941 // in the TU). This is to match gcc's behavior.
4942 if (ReferencedSelectors.empty() ||
4943 !Context.AnyObjCImplementation())
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004944 return;
Chandler Carruth12c8f652015-03-27 00:55:05 +00004945 for (auto &SelectorAndLocation : ReferencedSelectors) {
4946 Selector Sel = SelectorAndLocation.first;
4947 SourceLocation Loc = SelectorAndLocation.second;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004948 if (!LookupImplementedMethodInGlobalPool(Sel))
Chandler Carruth12c8f652015-03-27 00:55:05 +00004949 Diag(Loc, diag::warn_unimplemented_selector) << Sel;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004950 }
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004951}
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004952
4953ObjCIvarDecl *
4954Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4955 const ObjCPropertyDecl *&PDecl) const {
Fariborz Jahanian1cc7ae12014-01-02 17:24:32 +00004956 if (Method->isClassMethod())
Craig Topperc3ec1492014-05-26 06:22:03 +00004957 return nullptr;
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004958 const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
4959 if (!IDecl)
Craig Topperc3ec1492014-05-26 06:22:03 +00004960 return nullptr;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004961 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
4962 /*shallowCategoryLookup=*/false,
4963 /*followSuper=*/false);
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004964 if (!Method || !Method->isPropertyAccessor())
Craig Topperc3ec1492014-05-26 06:22:03 +00004965 return nullptr;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004966 if ((PDecl = Method->findPropertyDecl()))
Fariborz Jahanian122d94f2014-01-27 22:27:43 +00004967 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
4968 // property backing ivar must belong to property's class
4969 // or be a private ivar in class's implementation.
4970 // FIXME. fix the const-ness issue.
4971 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
4972 IV->getIdentifier());
4973 return IV;
4974 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004975 return nullptr;
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004976}
4977
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004978namespace {
4979 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
4980 /// accessor references the backing ivar.
Argyrios Kyrtzidis98045c12014-01-03 19:53:09 +00004981 class UnusedBackingIvarChecker :
Richard Smith50668452015-11-24 03:55:01 +00004982 public RecursiveASTVisitor<UnusedBackingIvarChecker> {
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004983 public:
4984 Sema &S;
4985 const ObjCMethodDecl *Method;
4986 const ObjCIvarDecl *IvarD;
4987 bool AccessedIvar;
4988 bool InvokedSelfMethod;
4989
4990 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
4991 const ObjCIvarDecl *IvarD)
4992 : S(S), Method(Method), IvarD(IvarD),
4993 AccessedIvar(false), InvokedSelfMethod(false) {
4994 assert(IvarD);
4995 }
4996
4997 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
4998 if (E->getDecl() == IvarD) {
4999 AccessedIvar = true;
5000 return false;
5001 }
5002 return true;
5003 }
5004
5005 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
5006 if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
5007 S.isSelfExpr(E->getInstanceReceiver(), Method)) {
5008 InvokedSelfMethod = true;
5009 }
5010 return true;
5011 }
5012 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00005013} // end anonymous namespace
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005014
5015void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
5016 const ObjCImplementationDecl *ImplD) {
5017 if (S->hasUnrecoverableErrorOccurred())
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00005018 return;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005019
Aaron Ballmanf26acce2014-03-13 19:50:17 +00005020 for (const auto *CurMethod : ImplD->instance_methods()) {
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005021 unsigned DIAG = diag::warn_unused_property_backing_ivar;
5022 SourceLocation Loc = CurMethod->getLocation();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005023 if (Diags.isIgnored(DIAG, Loc))
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005024 continue;
5025
5026 const ObjCPropertyDecl *PDecl;
5027 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
5028 if (!IV)
5029 continue;
5030
5031 UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
5032 Checker.TraverseStmt(CurMethod->getBody());
5033 if (Checker.AccessedIvar)
5034 continue;
5035
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00005036 // Do not issue this warning if backing ivar is used somewhere and accessor
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005037 // implementation makes a self call. This is to prevent false positive in
5038 // cases where the ivar is accessed by another method that the accessor
5039 // delegates to.
5040 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
Argyrios Kyrtzidisd8a35322014-01-03 19:39:23 +00005041 Diag(Loc, DIAG) << IV;
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00005042 Diag(PDecl->getLocation(), diag::note_property_declare);
5043 }
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00005044 }
5045}