blob: 75c5ff56be6fd4f275d43326e3db6c8d11ac86fc [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 Lorenze1088dc2017-07-13 16:37:11 +0000269 AvailabilityResult Availability = ND->getAvailability();
270 if (Availability != AR_Deprecated) {
Eric Christopher7aba9782017-07-14 01:42:57 +0000271 if (isa<ObjCMethodDecl>(ND)) {
Alex Lorenze1088dc2017-07-13 16:37:11 +0000272 if (Availability != AR_Unavailable)
273 return;
274 // Warn about implementing unavailable methods.
275 S.Diag(ImplLoc, diag::warn_unavailable_def);
276 S.Diag(ND->getLocation(), diag::note_method_declared_at)
277 << ND->getDeclName();
278 return;
279 }
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000280 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND)) {
281 if (!CD->getClassInterface()->isDeprecated())
282 return;
283 ND = CD->getClassInterface();
284 IsCategory = true;
285 } else
286 return;
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000287 }
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000288 S.Diag(ImplLoc, diag::warn_deprecated_def)
289 << (isa<ObjCMethodDecl>(ND)
290 ? /*Method*/ 0
291 : isa<ObjCCategoryDecl>(ND) || IsCategory ? /*Category*/ 2
292 : /*Class*/ 1);
293 if (isa<ObjCMethodDecl>(ND))
294 S.Diag(ND->getLocation(), diag::note_method_declared_at)
295 << ND->getDeclName();
296 else
297 S.Diag(ND->getLocation(), diag::note_previous_decl)
298 << (isa<ObjCCategoryDecl>(ND) ? "category" : "class");
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000299}
300
Fariborz Jahanianbd0642f2011-08-31 17:37:55 +0000301/// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
302/// pool.
303void Sema::AddAnyMethodToGlobalPool(Decl *D) {
304 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
305
306 // If we don't have a valid method decl, simply return.
307 if (!MDecl)
308 return;
309 if (MDecl->isInstanceMethod())
310 AddInstanceMethodToGlobalPool(MDecl, true);
311 else
312 AddFactoryMethodToGlobalPool(MDecl, true);
313}
314
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000315/// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
316/// has explicit ownership attribute; false otherwise.
317static bool
318HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
319 QualType T = Param->getType();
320
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000321 if (const PointerType *PT = T->getAs<PointerType>()) {
322 T = PT->getPointeeType();
323 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
324 T = RT->getPointeeType();
325 } else {
326 return true;
327 }
328
329 // If we have a lifetime qualifier, but it's local, we must have
330 // inferred it. So, it is implicit.
331 return !T.getLocalQualifiers().hasObjCLifetime();
332}
333
Fariborz Jahanian18d0a5d2012-08-08 23:41:08 +0000334/// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
335/// and user declared, in the method definition's AST.
336void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000337 assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
John McCall48871652010-08-21 09:40:31 +0000338 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
Fariborz Jahanian577574a2012-07-02 23:37:09 +0000339
Steve Naroff542cd5d2008-07-25 17:57:26 +0000340 // If we don't have a valid method decl, simply return.
341 if (!MDecl)
342 return;
Steve Naroff1d2538c2007-12-18 01:30:32 +0000343
Akira Hatanakaff6c4f32018-04-12 06:01:41 +0000344 QualType ResultType = MDecl->getReturnType();
345 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
346 !MDecl->isInvalidDecl() &&
347 RequireCompleteType(MDecl->getLocation(), ResultType,
348 diag::err_func_def_incomplete_result))
349 MDecl->setInvalidDecl();
350
Chris Lattnerda463fe2007-12-12 07:09:47 +0000351 // Allow all of Sema to see that we are entering a method definition.
Douglas Gregor91f84212008-12-11 16:49:14 +0000352 PushDeclContext(FnBodyScope, MDecl);
Douglas Gregor9a28e842010-03-01 23:15:13 +0000353 PushFunctionScope();
354
Chris Lattnerda463fe2007-12-12 07:09:47 +0000355 // Create Decl objects for each parameter, entrring them in the scope for
356 // binding to their use.
Chris Lattnerda463fe2007-12-12 07:09:47 +0000357
358 // Insert the invisible arguments, self and _cmd!
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000359 MDecl->createImplicitParams(Context, MDecl->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000360
Daniel Dunbar279d1cc2008-08-26 06:07:48 +0000361 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
362 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000363
Reid Kleckner5a115802013-06-24 14:38:26 +0000364 // The ObjC parser requires parameter names so there's no need to check.
David Majnemer59f77922016-06-24 04:05:48 +0000365 CheckParmsForFunctionDef(MDecl->parameters(),
Reid Kleckner5a115802013-06-24 14:38:26 +0000366 /*CheckParameterNames=*/false);
367
Chris Lattner58258242008-04-10 02:22:51 +0000368 // Introduce all of the other parameters into this scope.
David Majnemer59f77922016-06-24 04:05:48 +0000369 for (auto *Param : MDecl->parameters()) {
Fariborz Jahanianb3e87122010-09-17 22:07:07 +0000370 if (!Param->isInvalidDecl() &&
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000371 getLangOpts().ObjCAutoRefCount &&
372 !HasExplicitOwnershipAttr(*this, Param))
373 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
374 Param->getType();
Fariborz Jahaniancd278ff2012-08-30 23:56:02 +0000375
Aaron Ballman43b68be2014-03-07 17:50:17 +0000376 if (Param->getIdentifier())
377 PushOnScopeChains(Param, FnBodyScope);
Fariborz Jahanianb3e87122010-09-17 22:07:07 +0000378 }
John McCall31168b02011-06-15 23:02:42 +0000379
380 // In ARC, disallow definition of retain/release/autorelease/retainCount
David Blaikiebbafb8a2012-03-11 07:00:24 +0000381 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +0000382 switch (MDecl->getMethodFamily()) {
383 case OMF_retain:
384 case OMF_retainCount:
385 case OMF_release:
386 case OMF_autorelease:
387 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
Fariborz Jahanian39d1c422013-05-16 19:08:44 +0000388 << 0 << MDecl->getSelector();
John McCall31168b02011-06-15 23:02:42 +0000389 break;
390
391 case OMF_None:
392 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +0000393 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +0000394 case OMF_alloc:
395 case OMF_init:
396 case OMF_mutableCopy:
397 case OMF_copy:
398 case OMF_new:
399 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +0000400 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +0000401 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +0000402 break;
403 }
404 }
405
Nico Weber715abaf2011-08-22 17:25:57 +0000406 // Warn on deprecated methods under -Wdeprecated-implementations,
407 // and prepare for warning on missing super calls.
408 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
Fariborz Jahanian566fff02012-09-07 23:46:23 +0000409 ObjCMethodDecl *IMD =
410 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
411
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000412 if (IMD) {
413 ObjCImplDecl *ImplDeclOfMethodDef =
414 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
415 ObjCContainerDecl *ContDeclOfMethodDecl =
416 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
Craig Topperc3ec1492014-05-26 06:22:03 +0000417 ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000418 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
419 ImplDeclOfMethodDecl = OID->getImplementation();
Fariborz Jahanianed39e7c2014-03-18 16:25:22 +0000420 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
421 if (CD->IsClassExtension()) {
422 if (ObjCInterfaceDecl *OID = CD->getClassInterface())
423 ImplDeclOfMethodDecl = OID->getImplementation();
424 } else
425 ImplDeclOfMethodDecl = CD->getImplementation();
Fariborz Jahanian19a08bb2014-03-18 00:10:37 +0000426 }
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000427 // No need to issue deprecated warning if deprecated mehod in class/category
428 // is being implemented in its own implementation (no overriding is involved).
Fariborz Jahanianed39e7c2014-03-18 16:25:22 +0000429 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000430 DiagnoseObjCImplementedDeprecations(*this, IMD, MDecl->getLocation());
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000431 }
Nico Weber715abaf2011-08-22 17:25:57 +0000432
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000433 if (MDecl->getMethodFamily() == OMF_init) {
434 if (MDecl->isDesignatedInitializerForTheInterface()) {
435 getCurFunction()->ObjCIsDesignatedInit = true;
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +0000436 getCurFunction()->ObjCWarnForNoDesignatedInitChain =
Craig Topperc3ec1492014-05-26 06:22:03 +0000437 IC->getSuperClass() != nullptr;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000438 } else if (IC->hasDesignatedInitializers()) {
439 getCurFunction()->ObjCIsSecondaryInit = true;
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +0000440 getCurFunction()->ObjCWarnForNoInitDelegation = true;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000441 }
442 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +0000443
Nico Weber1fb82662011-08-28 22:35:17 +0000444 // If this is "dealloc" or "finalize", set some bit here.
Nico Weber715abaf2011-08-22 17:25:57 +0000445 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
446 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
447 // Only do this if the current class actually has a superclass.
Jordan Rosed03d99d2013-03-05 01:27:54 +0000448 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
Jordan Rose2afd6612012-10-19 16:05:26 +0000449 ObjCMethodFamily Family = MDecl->getMethodFamily();
450 if (Family == OMF_dealloc) {
451 if (!(getLangOpts().ObjCAutoRefCount ||
452 getLangOpts().getGC() == LangOptions::GCOnly))
453 getCurFunction()->ObjCShouldCallSuper = true;
454
455 } else if (Family == OMF_finalize) {
456 if (Context.getLangOpts().getGC() != LangOptions::NonGC)
457 getCurFunction()->ObjCShouldCallSuper = true;
458
Fariborz Jahaniance4bbb22013-11-05 00:28:21 +0000459 } else {
Jordan Rose2afd6612012-10-19 16:05:26 +0000460 const ObjCMethodDecl *SuperMethod =
Jordan Rosed03d99d2013-03-05 01:27:54 +0000461 SuperClass->lookupMethod(MDecl->getSelector(),
462 MDecl->isInstanceMethod());
Jordan Rose2afd6612012-10-19 16:05:26 +0000463 getCurFunction()->ObjCShouldCallSuper =
464 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
Fariborz Jahaniand6876b22012-09-10 18:04:25 +0000465 }
Nico Weber1fb82662011-08-28 22:35:17 +0000466 }
Nico Weber715abaf2011-08-22 17:25:57 +0000467 }
Chris Lattnerda463fe2007-12-12 07:09:47 +0000468}
469
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000470namespace {
471
472// Callback to only accept typo corrections that are Objective-C classes.
473// If an ObjCInterfaceDecl* is given to the constructor, then the validation
474// function will reject corrections to that class.
475class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback {
476 public:
Craig Topperc3ec1492014-05-26 06:22:03 +0000477 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000478 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
479 : CurrentIDecl(IDecl) {}
480
Craig Toppere14c0f82014-03-12 04:55:44 +0000481 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000482 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
483 return ID && !declaresSameEntity(ID, CurrentIDecl);
484 }
485
486 private:
487 ObjCInterfaceDecl *CurrentIDecl;
488};
489
Hans Wennborgdcfba332015-10-06 23:40:43 +0000490} // end anonymous namespace
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000491
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +0000492static void diagnoseUseOfProtocols(Sema &TheSema,
493 ObjCContainerDecl *CD,
494 ObjCProtocolDecl *const *ProtoRefs,
495 unsigned NumProtoRefs,
496 const SourceLocation *ProtoLocs) {
497 assert(ProtoRefs);
498 // Diagnose availability in the context of the ObjC container.
499 Sema::ContextRAII SavedContext(TheSema, CD);
500 for (unsigned i = 0; i < NumProtoRefs; ++i) {
Alex Lorenzcdd596f2017-07-07 09:15:29 +0000501 (void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i],
502 /*UnknownObjCClass=*/nullptr,
503 /*ObjCPropertyAccess=*/false,
504 /*AvoidPartialAvailabilityChecks=*/true);
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +0000505 }
506}
507
Douglas Gregore9d95f12015-07-07 03:57:35 +0000508void Sema::
509ActOnSuperClassOfClassInterface(Scope *S,
510 SourceLocation AtInterfaceLoc,
511 ObjCInterfaceDecl *IDecl,
512 IdentifierInfo *ClassName,
513 SourceLocation ClassLoc,
514 IdentifierInfo *SuperName,
515 SourceLocation SuperLoc,
516 ArrayRef<ParsedType> SuperTypeArgs,
517 SourceRange SuperTypeArgsRange) {
518 // Check if a different kind of symbol declared in this scope.
519 NamedDecl *PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
520 LookupOrdinaryName);
521
522 if (!PrevDecl) {
523 // Try to correct for a typo in the superclass name without correcting
524 // to the class we're defining.
525 if (TypoCorrection Corrected = CorrectTypo(
526 DeclarationNameInfo(SuperName, SuperLoc),
527 LookupOrdinaryName, TUScope,
Hans Wennborgdcfba332015-10-06 23:40:43 +0000528 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(IDecl),
Douglas Gregore9d95f12015-07-07 03:57:35 +0000529 CTK_ErrorRecovery)) {
530 diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
531 << SuperName << ClassName);
532 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
533 }
534 }
535
536 if (declaresSameEntity(PrevDecl, IDecl)) {
537 Diag(SuperLoc, diag::err_recursive_superclass)
538 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
539 IDecl->setEndOfDefinitionLoc(ClassLoc);
540 } else {
541 ObjCInterfaceDecl *SuperClassDecl =
542 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
543 QualType SuperClassType;
544
545 // Diagnose classes that inherit from deprecated classes.
546 if (SuperClassDecl) {
547 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
548 SuperClassType = Context.getObjCInterfaceType(SuperClassDecl);
549 }
550
Hans Wennborgdcfba332015-10-06 23:40:43 +0000551 if (PrevDecl && !SuperClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +0000552 // The previous declaration was not a class decl. Check if we have a
553 // typedef. If we do, get the underlying class type.
554 if (const TypedefNameDecl *TDecl =
555 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
556 QualType T = TDecl->getUnderlyingType();
557 if (T->isObjCObjectType()) {
558 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
559 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
560 SuperClassType = Context.getTypeDeclType(TDecl);
561
562 // This handles the following case:
563 // @interface NewI @end
564 // typedef NewI DeprI __attribute__((deprecated("blah")))
565 // @interface SI : DeprI /* warn here */ @end
566 (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
567 }
568 }
569 }
570
571 // This handles the following case:
572 //
573 // typedef int SuperClass;
574 // @interface MyClass : SuperClass {} @end
575 //
576 if (!SuperClassDecl) {
577 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
578 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
579 }
580 }
581
582 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
583 if (!SuperClassDecl)
584 Diag(SuperLoc, diag::err_undef_superclass)
585 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
586 else if (RequireCompleteType(SuperLoc,
587 SuperClassType,
588 diag::err_forward_superclass,
589 SuperClassDecl->getDeclName(),
590 ClassName,
591 SourceRange(AtInterfaceLoc, ClassLoc))) {
Hans Wennborgdcfba332015-10-06 23:40:43 +0000592 SuperClassDecl = nullptr;
Douglas Gregore9d95f12015-07-07 03:57:35 +0000593 SuperClassType = QualType();
594 }
595 }
596
597 if (SuperClassType.isNull()) {
598 assert(!SuperClassDecl && "Failed to set SuperClassType?");
599 return;
600 }
601
602 // Handle type arguments on the superclass.
603 TypeSourceInfo *SuperClassTInfo = nullptr;
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000604 if (!SuperTypeArgs.empty()) {
605 TypeResult fullSuperClassType = actOnObjCTypeArgsAndProtocolQualifiers(
606 S,
607 SuperLoc,
608 CreateParsedType(SuperClassType,
609 nullptr),
610 SuperTypeArgsRange.getBegin(),
611 SuperTypeArgs,
612 SuperTypeArgsRange.getEnd(),
613 SourceLocation(),
614 { },
615 { },
616 SourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +0000617 if (!fullSuperClassType.isUsable())
618 return;
619
620 SuperClassType = GetTypeFromParser(fullSuperClassType.get(),
621 &SuperClassTInfo);
622 }
623
624 if (!SuperClassTInfo) {
625 SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType,
626 SuperLoc);
627 }
628
629 IDecl->setSuperClass(SuperClassTInfo);
630 IDecl->setEndOfDefinitionLoc(SuperClassTInfo->getTypeLoc().getLocEnd());
631 }
632}
633
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000634DeclResult Sema::actOnObjCTypeParam(Scope *S,
635 ObjCTypeParamVariance variance,
636 SourceLocation varianceLoc,
637 unsigned index,
Douglas Gregore83b9562015-07-07 03:57:53 +0000638 IdentifierInfo *paramName,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000639 SourceLocation paramLoc,
640 SourceLocation colonLoc,
641 ParsedType parsedTypeBound) {
642 // If there was an explicitly-provided type bound, check it.
643 TypeSourceInfo *typeBoundInfo = nullptr;
644 if (parsedTypeBound) {
645 // The type bound can be any Objective-C pointer type.
646 QualType typeBound = GetTypeFromParser(parsedTypeBound, &typeBoundInfo);
647 if (typeBound->isObjCObjectPointerType()) {
648 // okay
649 } else if (typeBound->isObjCObjectType()) {
650 // The user forgot the * on an Objective-C pointer type, e.g.,
651 // "T : NSView".
Craig Topper07fa1762015-11-15 02:31:46 +0000652 SourceLocation starLoc = getLocForEndOfToken(
Douglas Gregor85f3f952015-07-07 03:57:15 +0000653 typeBoundInfo->getTypeLoc().getEndLoc());
654 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
655 diag::err_objc_type_param_bound_missing_pointer)
656 << typeBound << paramName
657 << FixItHint::CreateInsertion(starLoc, " *");
658
659 // Create a new type location builder so we can update the type
660 // location information we have.
661 TypeLocBuilder builder;
662 builder.pushFullCopy(typeBoundInfo->getTypeLoc());
663
664 // Create the Objective-C pointer type.
665 typeBound = Context.getObjCObjectPointerType(typeBound);
666 ObjCObjectPointerTypeLoc newT
667 = builder.push<ObjCObjectPointerTypeLoc>(typeBound);
668 newT.setStarLoc(starLoc);
669
670 // Form the new type source information.
671 typeBoundInfo = builder.getTypeSourceInfo(Context, typeBound);
672 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +0000673 // Not a valid type bound.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000674 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
675 diag::err_objc_type_param_bound_nonobject)
676 << typeBound << paramName;
677
678 // Forget the bound; we'll default to id later.
679 typeBoundInfo = nullptr;
680 }
Douglas Gregore83b9562015-07-07 03:57:53 +0000681
John McCall69975252015-09-23 22:14:21 +0000682 // Type bounds cannot have qualifiers (even indirectly) or explicit
683 // nullability.
Douglas Gregore83b9562015-07-07 03:57:53 +0000684 if (typeBoundInfo) {
John McCall69975252015-09-23 22:14:21 +0000685 QualType typeBound = typeBoundInfo->getType();
686 TypeLoc qual = typeBoundInfo->getTypeLoc().findExplicitQualifierLoc();
687 if (qual || typeBound.hasQualifiers()) {
688 bool diagnosed = false;
689 SourceRange rangeToRemove;
690 if (qual) {
691 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
692 rangeToRemove = attr.getLocalSourceRange();
693 if (attr.getTypePtr()->getImmediateNullability()) {
694 Diag(attr.getLocStart(),
695 diag::err_objc_type_param_bound_explicit_nullability)
696 << paramName << typeBound
697 << FixItHint::CreateRemoval(rangeToRemove);
698 diagnosed = true;
699 }
700 }
701 }
702
703 if (!diagnosed) {
704 Diag(qual ? qual.getLocStart()
705 : typeBoundInfo->getTypeLoc().getLocStart(),
706 diag::err_objc_type_param_bound_qualified)
707 << paramName << typeBound << typeBound.getQualifiers().getAsString()
708 << FixItHint::CreateRemoval(rangeToRemove);
709 }
710
711 // If the type bound has qualifiers other than CVR, we need to strip
712 // them or we'll probably assert later when trying to apply new
713 // qualifiers.
714 Qualifiers quals = typeBound.getQualifiers();
715 quals.removeCVRQualifiers();
716 if (!quals.empty()) {
717 typeBoundInfo =
718 Context.getTrivialTypeSourceInfo(typeBound.getUnqualifiedType());
719 }
Douglas Gregore83b9562015-07-07 03:57:53 +0000720 }
721 }
Douglas Gregor85f3f952015-07-07 03:57:15 +0000722 }
723
724 // If there was no explicit type bound (or we removed it due to an error),
725 // use 'id' instead.
726 if (!typeBoundInfo) {
727 colonLoc = SourceLocation();
728 typeBoundInfo = Context.getTrivialTypeSourceInfo(Context.getObjCIdType());
729 }
730
731 // Create the type parameter.
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000732 return ObjCTypeParamDecl::Create(Context, CurContext, variance, varianceLoc,
733 index, paramLoc, paramName, colonLoc,
734 typeBoundInfo);
Douglas Gregor85f3f952015-07-07 03:57:15 +0000735}
736
737ObjCTypeParamList *Sema::actOnObjCTypeParamList(Scope *S,
738 SourceLocation lAngleLoc,
739 ArrayRef<Decl *> typeParamsIn,
740 SourceLocation rAngleLoc) {
741 // We know that the array only contains Objective-C type parameters.
742 ArrayRef<ObjCTypeParamDecl *>
743 typeParams(
744 reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()),
745 typeParamsIn.size());
746
747 // Diagnose redeclarations of type parameters.
748 // We do this now because Objective-C type parameters aren't pushed into
749 // scope until later (after the instance variable block), but we want the
750 // diagnostics to occur right after we parse the type parameter list.
751 llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams;
752 for (auto typeParam : typeParams) {
753 auto known = knownParams.find(typeParam->getIdentifier());
754 if (known != knownParams.end()) {
755 Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl)
756 << typeParam->getIdentifier()
757 << SourceRange(known->second->getLocation());
758
759 typeParam->setInvalidDecl();
760 } else {
761 knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam));
762
763 // Push the type parameter into scope.
764 PushOnScopeChains(typeParam, S, /*AddToContext=*/false);
765 }
766 }
767
768 // Create the parameter list.
769 return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc);
770}
771
772void Sema::popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList) {
773 for (auto typeParam : *typeParamList) {
774 if (!typeParam->isInvalidDecl()) {
775 S->RemoveDecl(typeParam);
776 IdResolver.RemoveDecl(typeParam);
777 }
778 }
779}
780
781namespace {
782 /// The context in which an Objective-C type parameter list occurs, for use
783 /// in diagnostics.
784 enum class TypeParamListContext {
785 ForwardDeclaration,
786 Definition,
787 Category,
788 Extension
789 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000790} // end anonymous namespace
Douglas Gregor85f3f952015-07-07 03:57:15 +0000791
792/// Check consistency between two Objective-C type parameter lists, e.g.,
NAKAMURA Takumi4c3ab452015-07-08 02:35:56 +0000793/// between a category/extension and an \@interface or between an \@class and an
794/// \@interface.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000795static bool checkTypeParamListConsistency(Sema &S,
796 ObjCTypeParamList *prevTypeParams,
797 ObjCTypeParamList *newTypeParams,
798 TypeParamListContext newContext) {
799 // If the sizes don't match, complain about that.
800 if (prevTypeParams->size() != newTypeParams->size()) {
801 SourceLocation diagLoc;
802 if (newTypeParams->size() > prevTypeParams->size()) {
803 diagLoc = newTypeParams->begin()[prevTypeParams->size()]->getLocation();
804 } else {
Craig Topper07fa1762015-11-15 02:31:46 +0000805 diagLoc = S.getLocForEndOfToken(newTypeParams->back()->getLocEnd());
Douglas Gregor85f3f952015-07-07 03:57:15 +0000806 }
807
808 S.Diag(diagLoc, diag::err_objc_type_param_arity_mismatch)
809 << static_cast<unsigned>(newContext)
810 << (newTypeParams->size() > prevTypeParams->size())
811 << prevTypeParams->size()
812 << newTypeParams->size();
813
814 return true;
815 }
816
817 // Match up the type parameters.
818 for (unsigned i = 0, n = prevTypeParams->size(); i != n; ++i) {
819 ObjCTypeParamDecl *prevTypeParam = prevTypeParams->begin()[i];
820 ObjCTypeParamDecl *newTypeParam = newTypeParams->begin()[i];
821
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000822 // Check for consistency of the variance.
823 if (newTypeParam->getVariance() != prevTypeParam->getVariance()) {
824 if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant &&
825 newContext != TypeParamListContext::Definition) {
826 // When the new type parameter is invariant and is not part
827 // of the definition, just propagate the variance.
828 newTypeParam->setVariance(prevTypeParam->getVariance());
829 } else if (prevTypeParam->getVariance()
830 == ObjCTypeParamVariance::Invariant &&
831 !(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) &&
832 cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext())
833 ->getDefinition() == prevTypeParam->getDeclContext())) {
834 // When the old parameter is invariant and was not part of the
835 // definition, just ignore the difference because it doesn't
836 // matter.
837 } else {
838 {
839 // Diagnose the conflict and update the second declaration.
840 SourceLocation diagLoc = newTypeParam->getVarianceLoc();
841 if (diagLoc.isInvalid())
842 diagLoc = newTypeParam->getLocStart();
843
844 auto diag = S.Diag(diagLoc,
845 diag::err_objc_type_param_variance_conflict)
846 << static_cast<unsigned>(newTypeParam->getVariance())
847 << newTypeParam->getDeclName()
848 << static_cast<unsigned>(prevTypeParam->getVariance())
849 << prevTypeParam->getDeclName();
850 switch (prevTypeParam->getVariance()) {
851 case ObjCTypeParamVariance::Invariant:
852 diag << FixItHint::CreateRemoval(newTypeParam->getVarianceLoc());
853 break;
854
855 case ObjCTypeParamVariance::Covariant:
856 case ObjCTypeParamVariance::Contravariant: {
857 StringRef newVarianceStr
858 = prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant
859 ? "__covariant"
860 : "__contravariant";
861 if (newTypeParam->getVariance()
862 == ObjCTypeParamVariance::Invariant) {
863 diag << FixItHint::CreateInsertion(newTypeParam->getLocStart(),
864 (newVarianceStr + " ").str());
865 } else {
866 diag << FixItHint::CreateReplacement(newTypeParam->getVarianceLoc(),
867 newVarianceStr);
868 }
869 }
870 }
871 }
872
873 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
874 << prevTypeParam->getDeclName();
875
876 // Override the variance.
877 newTypeParam->setVariance(prevTypeParam->getVariance());
878 }
879 }
880
Douglas Gregor85f3f952015-07-07 03:57:15 +0000881 // If the bound types match, there's nothing to do.
882 if (S.Context.hasSameType(prevTypeParam->getUnderlyingType(),
883 newTypeParam->getUnderlyingType()))
884 continue;
885
886 // If the new type parameter's bound was explicit, complain about it being
887 // different from the original.
888 if (newTypeParam->hasExplicitBound()) {
889 SourceRange newBoundRange = newTypeParam->getTypeSourceInfo()
890 ->getTypeLoc().getSourceRange();
891 S.Diag(newBoundRange.getBegin(), diag::err_objc_type_param_bound_conflict)
892 << newTypeParam->getUnderlyingType()
893 << newTypeParam->getDeclName()
894 << prevTypeParam->hasExplicitBound()
895 << prevTypeParam->getUnderlyingType()
896 << (newTypeParam->getDeclName() == prevTypeParam->getDeclName())
897 << prevTypeParam->getDeclName()
898 << FixItHint::CreateReplacement(
899 newBoundRange,
900 prevTypeParam->getUnderlyingType().getAsString(
901 S.Context.getPrintingPolicy()));
902
903 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
904 << prevTypeParam->getDeclName();
905
906 // Override the new type parameter's bound type with the previous type,
907 // so that it's consistent.
908 newTypeParam->setTypeSourceInfo(
909 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
910 continue;
911 }
912
913 // The new type parameter got the implicit bound of 'id'. That's okay for
914 // categories and extensions (overwrite it later), but not for forward
915 // declarations and @interfaces, because those must be standalone.
916 if (newContext == TypeParamListContext::ForwardDeclaration ||
917 newContext == TypeParamListContext::Definition) {
918 // Diagnose this problem for forward declarations and definitions.
919 SourceLocation insertionLoc
Craig Topper07fa1762015-11-15 02:31:46 +0000920 = S.getLocForEndOfToken(newTypeParam->getLocation());
Douglas Gregor85f3f952015-07-07 03:57:15 +0000921 std::string newCode
922 = " : " + prevTypeParam->getUnderlyingType().getAsString(
923 S.Context.getPrintingPolicy());
924 S.Diag(newTypeParam->getLocation(),
925 diag::err_objc_type_param_bound_missing)
926 << prevTypeParam->getUnderlyingType()
927 << newTypeParam->getDeclName()
928 << (newContext == TypeParamListContext::ForwardDeclaration)
929 << FixItHint::CreateInsertion(insertionLoc, newCode);
930
931 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
932 << prevTypeParam->getDeclName();
933 }
934
935 // Update the new type parameter's bound to match the previous one.
936 newTypeParam->setTypeSourceInfo(
937 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
938 }
939
940 return false;
941}
942
John McCall48871652010-08-21 09:40:31 +0000943Decl *Sema::
Douglas Gregore9d95f12015-07-07 03:57:35 +0000944ActOnStartClassInterface(Scope *S, SourceLocation AtInterfaceLoc,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000945 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000946 ObjCTypeParamList *typeParamList,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000947 IdentifierInfo *SuperName, SourceLocation SuperLoc,
Douglas Gregore9d95f12015-07-07 03:57:35 +0000948 ArrayRef<ParsedType> SuperTypeArgs,
949 SourceRange SuperTypeArgsRange,
John McCall48871652010-08-21 09:40:31 +0000950 Decl * const *ProtoRefs, unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +0000951 const SourceLocation *ProtoLocs,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000952 SourceLocation EndProtoLoc, AttributeList *AttrList) {
Chris Lattnerda463fe2007-12-12 07:09:47 +0000953 assert(ClassName && "Missing class identifier");
Mike Stump11289f42009-09-09 15:08:12 +0000954
Chris Lattnerda463fe2007-12-12 07:09:47 +0000955 // Check for another declaration kind with the same name.
Richard Smithbecb92d2017-10-10 22:33:17 +0000956 NamedDecl *PrevDecl =
957 LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
958 forRedeclarationInCurContext());
Douglas Gregor5101c242008-12-05 18:15:24 +0000959
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000960 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +0000961 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Chris Lattner0369c572008-11-23 23:12:31 +0000962 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +0000963 }
Mike Stump11289f42009-09-09 15:08:12 +0000964
Douglas Gregordc9166c2011-12-15 20:29:51 +0000965 // Create a declaration to describe this @interface.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +0000966 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidisdd710632013-06-18 21:26:33 +0000967
968 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
969 // A previous decl with a different name is because of
970 // @compatibility_alias, for example:
971 // \code
972 // @class NewImage;
973 // @compatibility_alias OldImage NewImage;
974 // \endcode
975 // A lookup for 'OldImage' will return the 'NewImage' decl.
976 //
977 // In such a case use the real declaration name, instead of the alias one,
978 // otherwise we will break IdentifierResolver and redecls-chain invariants.
979 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
980 // has been aliased.
981 ClassName = PrevIDecl->getIdentifier();
982 }
983
Douglas Gregor85f3f952015-07-07 03:57:15 +0000984 // If there was a forward declaration with type parameters, check
985 // for consistency.
986 if (PrevIDecl) {
987 if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) {
988 if (typeParamList) {
989 // Both have type parameter lists; check for consistency.
990 if (checkTypeParamListConsistency(*this, prevTypeParamList,
991 typeParamList,
992 TypeParamListContext::Definition)) {
993 typeParamList = nullptr;
994 }
995 } else {
996 Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first)
997 << ClassName;
998 Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl)
999 << ClassName;
1000
1001 // Clone the type parameter list.
1002 SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams;
1003 for (auto typeParam : *prevTypeParamList) {
1004 clonedTypeParams.push_back(
1005 ObjCTypeParamDecl::Create(
1006 Context,
1007 CurContext,
Douglas Gregor1ac1b632015-07-07 03:58:54 +00001008 typeParam->getVariance(),
1009 SourceLocation(),
Douglas Gregore83b9562015-07-07 03:57:53 +00001010 typeParam->getIndex(),
Douglas Gregor85f3f952015-07-07 03:57:15 +00001011 SourceLocation(),
1012 typeParam->getIdentifier(),
1013 SourceLocation(),
1014 Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType())));
1015 }
1016
1017 typeParamList = ObjCTypeParamList::create(Context,
1018 SourceLocation(),
1019 clonedTypeParams,
1020 SourceLocation());
1021 }
1022 }
1023 }
1024
Douglas Gregordc9166c2011-12-15 20:29:51 +00001025 ObjCInterfaceDecl *IDecl
1026 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001027 typeParamList, PrevIDecl, ClassLoc);
Douglas Gregordc9166c2011-12-15 20:29:51 +00001028 if (PrevIDecl) {
1029 // Class already seen. Was it a definition?
1030 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
1031 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
1032 << PrevIDecl->getDeclName();
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001033 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregordc9166c2011-12-15 20:29:51 +00001034 IDecl->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00001035 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001036 }
Douglas Gregordc9166c2011-12-15 20:29:51 +00001037
1038 if (AttrList)
1039 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001040 AddPragmaAttributes(TUScope, IDecl);
Douglas Gregordc9166c2011-12-15 20:29:51 +00001041 PushOnScopeChains(IDecl, TUScope);
Mike Stump11289f42009-09-09 15:08:12 +00001042
Douglas Gregordc9166c2011-12-15 20:29:51 +00001043 // Start the definition of this class. If we're in a redefinition case, there
1044 // may already be a definition, so we'll end up adding to it.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001045 if (!IDecl->hasDefinition())
1046 IDecl->startDefinition();
1047
Chris Lattnerda463fe2007-12-12 07:09:47 +00001048 if (SuperName) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001049 // Diagnose availability in the context of the @interface.
1050 ContextRAII SavedContext(*this, IDecl);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001051
Douglas Gregore9d95f12015-07-07 03:57:35 +00001052 ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl,
1053 ClassName, ClassLoc,
1054 SuperName, SuperLoc, SuperTypeArgs,
1055 SuperTypeArgsRange);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001056 } else { // we have a root class.
Douglas Gregor16408322011-12-15 22:34:59 +00001057 IDecl->setEndOfDefinitionLoc(ClassLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001058 }
Mike Stump11289f42009-09-09 15:08:12 +00001059
Sebastian Redle7c1fe62010-08-13 00:28:03 +00001060 // Check then save referenced protocols.
Chris Lattnerdf59f5a2008-07-26 04:13:19 +00001061 if (NumProtoRefs) {
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001062 diagnoseUseOfProtocols(*this, IDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1063 NumProtoRefs, ProtoLocs);
Roman Divackye6377112012-09-06 15:59:27 +00001064 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001065 ProtoLocs, Context);
Douglas Gregor16408322011-12-15 22:34:59 +00001066 IDecl->setEndOfDefinitionLoc(EndProtoLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001067 }
Mike Stump11289f42009-09-09 15:08:12 +00001068
Anders Carlssona6b508a2008-11-04 16:57:32 +00001069 CheckObjCDeclScope(IDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001070 return ActOnObjCContainerStartDefinition(IDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001071}
1072
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001073/// ActOnTypedefedProtocols - this action finds protocol list as part of the
1074/// typedef'ed use for a qualified super class and adds them to the list
1075/// of the protocols.
1076void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
Argyrios Kyrtzidisf95a0002016-11-09 02:47:07 +00001077 SmallVectorImpl<SourceLocation> &ProtocolLocs,
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001078 IdentifierInfo *SuperName,
1079 SourceLocation SuperLoc) {
1080 if (!SuperName)
1081 return;
1082 NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
1083 LookupOrdinaryName);
1084 if (!IDecl)
1085 return;
1086
1087 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
1088 QualType T = TDecl->getUnderlyingType();
1089 if (T->isObjCObjectType())
Argyrios Kyrtzidisf95a0002016-11-09 02:47:07 +00001090 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>()) {
Benjamin Kramerf9890422015-02-17 16:48:30 +00001091 ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
Argyrios Kyrtzidisf95a0002016-11-09 02:47:07 +00001092 // FIXME: Consider whether this should be an invalid loc since the loc
1093 // is not actually pointing to a protocol name reference but to the
1094 // typedef reference. Note that the base class name loc is also pointing
1095 // at the typedef.
1096 ProtocolLocs.append(OPT->getNumProtocols(), SuperLoc);
1097 }
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001098 }
1099}
1100
Richard Smithac4e36d2012-08-08 23:32:13 +00001101/// ActOnCompatibilityAlias - this action is called after complete parsing of
James Dennett634962f2012-06-14 21:40:34 +00001102/// a \@compatibility_alias declaration. It sets up the alias relationships.
Richard Smithac4e36d2012-08-08 23:32:13 +00001103Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
1104 IdentifierInfo *AliasName,
1105 SourceLocation AliasLocation,
1106 IdentifierInfo *ClassName,
1107 SourceLocation ClassLocation) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00001108 // Look for previous declaration of alias name
Richard Smithbecb92d2017-10-10 22:33:17 +00001109 NamedDecl *ADecl =
1110 LookupSingleName(TUScope, AliasName, AliasLocation, LookupOrdinaryName,
1111 forRedeclarationInCurContext());
Chris Lattnerda463fe2007-12-12 07:09:47 +00001112 if (ADecl) {
Eli Friedmanfd6b3f82013-06-21 01:49:53 +00001113 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
Chris Lattnerd0685032008-11-23 23:20:13 +00001114 Diag(ADecl->getLocation(), diag::note_previous_declaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001115 return nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001116 }
1117 // Check for class declaration
Richard Smithbecb92d2017-10-10 22:33:17 +00001118 NamedDecl *CDeclU =
1119 LookupSingleName(TUScope, ClassName, ClassLocation, LookupOrdinaryName,
1120 forRedeclarationInCurContext());
Richard Smithdda56e42011-04-15 14:24:37 +00001121 if (const TypedefNameDecl *TDecl =
1122 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001123 QualType T = TDecl->getUnderlyingType();
John McCall8b07ec22010-05-15 11:32:37 +00001124 if (T->isObjCObjectType()) {
1125 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001126 ClassName = IDecl->getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001127 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
Richard Smithbecb92d2017-10-10 22:33:17 +00001128 LookupOrdinaryName,
1129 forRedeclarationInCurContext());
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001130 }
1131 }
1132 }
Chris Lattner219b3e92008-03-16 21:17:37 +00001133 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
Craig Topperc3ec1492014-05-26 06:22:03 +00001134 if (!CDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001135 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
Chris Lattner219b3e92008-03-16 21:17:37 +00001136 if (CDeclU)
Chris Lattnerd0685032008-11-23 23:20:13 +00001137 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001138 return nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001139 }
Mike Stump11289f42009-09-09 15:08:12 +00001140
Chris Lattner219b3e92008-03-16 21:17:37 +00001141 // Everything checked out, instantiate a new alias declaration AST.
Mike Stump11289f42009-09-09 15:08:12 +00001142 ObjCCompatibleAliasDecl *AliasDecl =
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001143 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001144
Anders Carlssona6b508a2008-11-04 16:57:32 +00001145 if (!CheckObjCDeclScope(AliasDecl))
Douglas Gregor38feed82009-04-24 02:57:34 +00001146 PushOnScopeChains(AliasDecl, TUScope);
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001147
John McCall48871652010-08-21 09:40:31 +00001148 return AliasDecl;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001149}
1150
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001151bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
Steve Naroff41d09ad2009-03-05 15:22:01 +00001152 IdentifierInfo *PName,
1153 SourceLocation &Ploc, SourceLocation PrevLoc,
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001154 const ObjCList<ObjCProtocolDecl> &PList) {
1155
1156 bool res = false;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001157 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
1158 E = PList.end(); I != E; ++I) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001159 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
1160 Ploc)) {
Steve Naroff41d09ad2009-03-05 15:22:01 +00001161 if (PDecl->getIdentifier() == PName) {
1162 Diag(Ploc, diag::err_protocol_has_circular_dependency);
1163 Diag(PrevLoc, diag::note_previous_definition);
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001164 res = true;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001165 }
Douglas Gregore6e48b12012-01-01 19:29:29 +00001166
1167 if (!PDecl->hasDefinition())
1168 continue;
1169
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001170 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
1171 PDecl->getLocation(), PDecl->getReferencedProtocols()))
1172 res = true;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001173 }
1174 }
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001175 return res;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001176}
1177
John McCall48871652010-08-21 09:40:31 +00001178Decl *
Chris Lattner3bbae002008-07-26 04:03:38 +00001179Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
1180 IdentifierInfo *ProtocolName,
1181 SourceLocation ProtocolLoc,
John McCall48871652010-08-21 09:40:31 +00001182 Decl * const *ProtoRefs,
Chris Lattner3bbae002008-07-26 04:03:38 +00001183 unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001184 const SourceLocation *ProtoLocs,
Daniel Dunbar26e2ab42008-09-26 04:48:09 +00001185 SourceLocation EndProtoLoc,
1186 AttributeList *AttrList) {
Fariborz Jahaniancadf7c52011-05-12 22:04:39 +00001187 bool err = false;
Daniel Dunbar26e2ab42008-09-26 04:48:09 +00001188 // FIXME: Deal with AttrList.
Chris Lattnerda463fe2007-12-12 07:09:47 +00001189 assert(ProtocolName && "Missing protocol identifier");
Douglas Gregor32c17572012-01-01 20:30:41 +00001190 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
Richard Smithbecb92d2017-10-10 22:33:17 +00001191 forRedeclarationInCurContext());
Craig Topperc3ec1492014-05-26 06:22:03 +00001192 ObjCProtocolDecl *PDecl = nullptr;
1193 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
Douglas Gregor32c17572012-01-01 20:30:41 +00001194 // If we already have a definition, complain.
1195 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
1196 Diag(Def->getLocation(), diag::note_previous_definition);
Mike Stump11289f42009-09-09 15:08:12 +00001197
Douglas Gregor32c17572012-01-01 20:30:41 +00001198 // Create a new protocol that is completely distinct from previous
1199 // declarations, and do not make this protocol available for name lookup.
1200 // That way, we'll end up completely ignoring the duplicate.
1201 // FIXME: Can we turn this into an error?
1202 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
1203 ProtocolLoc, AtProtoInterfaceLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +00001204 /*PrevDecl=*/nullptr);
Douglas Gregor32c17572012-01-01 20:30:41 +00001205 PDecl->startDefinition();
1206 } else {
1207 if (PrevDecl) {
1208 // Check for circular dependencies among protocol declarations. This can
1209 // only happen if this protocol was forward-declared.
Argyrios Kyrtzidis95dfc122011-11-13 22:08:30 +00001210 ObjCList<ObjCProtocolDecl> PList;
1211 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
1212 err = CheckForwardProtocolDeclarationForCircularDependency(
Douglas Gregor32c17572012-01-01 20:30:41 +00001213 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
Argyrios Kyrtzidis95dfc122011-11-13 22:08:30 +00001214 }
Douglas Gregor32c17572012-01-01 20:30:41 +00001215
1216 // Create the new declaration.
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001217 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
Argyrios Kyrtzidis1f4bee52011-10-17 19:48:06 +00001218 ProtocolLoc, AtProtoInterfaceLoc,
Douglas Gregor05a1f4d2012-01-01 22:06:18 +00001219 /*PrevDecl=*/PrevDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +00001220
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001221 PushOnScopeChains(PDecl, TUScope);
Douglas Gregore6e48b12012-01-01 19:29:29 +00001222 PDecl->startDefinition();
Chris Lattnerf87ca0a2008-03-16 01:23:04 +00001223 }
Douglas Gregore6e48b12012-01-01 19:29:29 +00001224
Fariborz Jahanian1470e932008-12-17 01:07:27 +00001225 if (AttrList)
Douglas Gregor758a8692009-06-17 21:51:59 +00001226 ProcessDeclAttributeList(TUScope, PDecl, AttrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001227 AddPragmaAttributes(TUScope, PDecl);
1228
Douglas Gregor32c17572012-01-01 20:30:41 +00001229 // Merge attributes from previous declarations.
1230 if (PrevDecl)
1231 mergeDeclAttributes(PDecl, PrevDecl);
1232
Fariborz Jahaniancadf7c52011-05-12 22:04:39 +00001233 if (!err && NumProtoRefs ) {
Chris Lattneracc04a92008-03-16 20:19:15 +00001234 /// Check then save referenced protocols.
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001235 diagnoseUseOfProtocols(*this, PDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1236 NumProtoRefs, ProtoLocs);
Roman Divackye6377112012-09-06 15:59:27 +00001237 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001238 ProtoLocs, Context);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001239 }
Mike Stump11289f42009-09-09 15:08:12 +00001240
1241 CheckObjCDeclScope(PDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001242 return ActOnObjCContainerStartDefinition(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001243}
1244
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001245static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
1246 ObjCProtocolDecl *&UndefinedProtocol) {
1247 if (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()) {
1248 UndefinedProtocol = PDecl;
1249 return true;
1250 }
1251
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001252 for (auto *PI : PDecl->protocols())
1253 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
1254 UndefinedProtocol = PI;
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001255 return true;
1256 }
1257 return false;
1258}
1259
Chris Lattnerda463fe2007-12-12 07:09:47 +00001260/// FindProtocolDeclaration - This routine looks up protocols and
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00001261/// issues an error if they are not declared. It returns list of
1262/// protocol declarations in its 'Protocols' argument.
Chris Lattnerda463fe2007-12-12 07:09:47 +00001263void
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001264Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
Craig Toppera9247eb2015-10-22 04:59:56 +00001265 ArrayRef<IdentifierLocPair> ProtocolId,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001266 SmallVectorImpl<Decl *> &Protocols) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001267 for (const IdentifierLocPair &Pair : ProtocolId) {
1268 ObjCProtocolDecl *PDecl = LookupProtocol(Pair.first, Pair.second);
Chris Lattner9c1842b2008-07-26 03:47:43 +00001269 if (!PDecl) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001270 TypoCorrection Corrected = CorrectTypo(
Craig Toppera9247eb2015-10-22 04:59:56 +00001271 DeclarationNameInfo(Pair.first, Pair.second),
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001272 LookupObjCProtocolName, TUScope, nullptr,
1273 llvm::make_unique<DeclFilterCCC<ObjCProtocolDecl>>(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001274 CTK_ErrorRecovery);
Richard Smithf9b15102013-08-17 00:46:16 +00001275 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
1276 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
Craig Toppera9247eb2015-10-22 04:59:56 +00001277 << Pair.first);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001278 }
1279
1280 if (!PDecl) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001281 Diag(Pair.second, diag::err_undeclared_protocol) << Pair.first;
Chris Lattner9c1842b2008-07-26 03:47:43 +00001282 continue;
1283 }
Fariborz Jahanianada44a22013-04-09 17:52:29 +00001284 // If this is a forward protocol declaration, get its definition.
1285 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
1286 PDecl = PDecl->getDefinition();
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001287
1288 // For an objc container, delay protocol reference checking until after we
1289 // can set the objc decl as the availability context, otherwise check now.
1290 if (!ForObjCContainer) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001291 (void)DiagnoseUseOfDecl(PDecl, Pair.second);
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001292 }
Chris Lattner9c1842b2008-07-26 03:47:43 +00001293
1294 // If this is a forward declaration and we are supposed to warn in this
1295 // case, do it.
Douglas Gregoreed49792013-01-17 00:38:46 +00001296 // FIXME: Recover nicely in the hidden case.
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001297 ObjCProtocolDecl *UndefinedProtocol;
1298
Douglas Gregoreed49792013-01-17 00:38:46 +00001299 if (WarnOnDeclarations &&
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001300 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001301 Diag(Pair.second, diag::warn_undef_protocolref) << Pair.first;
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001302 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
1303 << UndefinedProtocol;
1304 }
John McCall48871652010-08-21 09:40:31 +00001305 Protocols.push_back(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001306 }
1307}
1308
Benjamin Kramer8b851d02015-07-13 20:42:13 +00001309namespace {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001310// Callback to only accept typo corrections that are either
1311// Objective-C protocols or valid Objective-C type arguments.
1312class ObjCTypeArgOrProtocolValidatorCCC : public CorrectionCandidateCallback {
1313 ASTContext &Context;
1314 Sema::LookupNameKind LookupKind;
1315 public:
1316 ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context,
1317 Sema::LookupNameKind lookupKind)
1318 : Context(context), LookupKind(lookupKind) { }
1319
1320 bool ValidateCandidate(const TypoCorrection &candidate) override {
1321 // If we're allowed to find protocols and we have a protocol, accept it.
1322 if (LookupKind != Sema::LookupOrdinaryName) {
1323 if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>())
1324 return true;
1325 }
1326
1327 // If we're allowed to find type names and we have one, accept it.
1328 if (LookupKind != Sema::LookupObjCProtocolName) {
1329 // If we have a type declaration, we might accept this result.
1330 if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) {
1331 // If we found a tag declaration outside of C++, skip it. This
1332 // can happy because we look for any name when there is no
1333 // bias to protocol or type names.
1334 if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus)
1335 return false;
1336
1337 // Make sure the type is something we would accept as a type
1338 // argument.
1339 auto type = Context.getTypeDeclType(typeDecl);
1340 if (type->isObjCObjectPointerType() ||
1341 type->isBlockPointerType() ||
1342 type->isDependentType() ||
1343 type->isObjCObjectType())
1344 return true;
1345
1346 return false;
1347 }
1348
1349 // If we have an Objective-C class type, accept it; there will
1350 // be another fix to add the '*'.
1351 if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>())
1352 return true;
1353
1354 return false;
1355 }
1356
1357 return false;
1358 }
1359};
Benjamin Kramer8b851d02015-07-13 20:42:13 +00001360} // end anonymous namespace
Douglas Gregore9d95f12015-07-07 03:57:35 +00001361
Bruno Cardoso Lopesc54768f2016-04-13 20:59:07 +00001362void Sema::DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
1363 SourceLocation ProtocolLoc,
1364 IdentifierInfo *TypeArgId,
1365 SourceLocation TypeArgLoc,
1366 bool SelectProtocolFirst) {
1367 Diag(TypeArgLoc, diag::err_objc_type_args_and_protocols)
1368 << SelectProtocolFirst << TypeArgId << ProtocolId
1369 << SourceRange(ProtocolLoc);
1370}
1371
Douglas Gregore9d95f12015-07-07 03:57:35 +00001372void Sema::actOnObjCTypeArgsOrProtocolQualifiers(
1373 Scope *S,
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001374 ParsedType baseType,
Douglas Gregore9d95f12015-07-07 03:57:35 +00001375 SourceLocation lAngleLoc,
1376 ArrayRef<IdentifierInfo *> identifiers,
1377 ArrayRef<SourceLocation> identifierLocs,
1378 SourceLocation rAngleLoc,
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001379 SourceLocation &typeArgsLAngleLoc,
1380 SmallVectorImpl<ParsedType> &typeArgs,
1381 SourceLocation &typeArgsRAngleLoc,
1382 SourceLocation &protocolLAngleLoc,
1383 SmallVectorImpl<Decl *> &protocols,
1384 SourceLocation &protocolRAngleLoc,
Douglas Gregore9d95f12015-07-07 03:57:35 +00001385 bool warnOnIncompleteProtocols) {
1386 // Local function that updates the declaration specifiers with
1387 // protocol information.
Douglas Gregore9d95f12015-07-07 03:57:35 +00001388 unsigned numProtocolsResolved = 0;
1389 auto resolvedAsProtocols = [&] {
1390 assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols");
1391
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001392 // Determine whether the base type is a parameterized class, in
1393 // which case we want to warn about typos such as
1394 // "NSArray<NSObject>" (that should be NSArray<NSObject *>).
1395 ObjCInterfaceDecl *baseClass = nullptr;
1396 QualType base = GetTypeFromParser(baseType, nullptr);
1397 bool allAreTypeNames = false;
1398 SourceLocation firstClassNameLoc;
1399 if (!base.isNull()) {
1400 if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) {
1401 baseClass = objcObjectType->getInterface();
1402 if (baseClass) {
1403 if (auto typeParams = baseClass->getTypeParamList()) {
1404 if (typeParams->size() == numProtocolsResolved) {
1405 // Note that we should be looking for type names, too.
1406 allAreTypeNames = true;
1407 }
1408 }
1409 }
1410 }
1411 }
1412
Douglas Gregore9d95f12015-07-07 03:57:35 +00001413 for (unsigned i = 0, n = protocols.size(); i != n; ++i) {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001414 ObjCProtocolDecl *&proto
1415 = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001416 // For an objc container, delay protocol reference checking until after we
1417 // can set the objc decl as the availability context, otherwise check now.
1418 if (!warnOnIncompleteProtocols) {
1419 (void)DiagnoseUseOfDecl(proto, identifierLocs[i]);
1420 }
1421
1422 // If this is a forward protocol declaration, get its definition.
1423 if (!proto->isThisDeclarationADefinition() && proto->getDefinition())
1424 proto = proto->getDefinition();
1425
1426 // If this is a forward declaration and we are supposed to warn in this
1427 // case, do it.
1428 // FIXME: Recover nicely in the hidden case.
1429 ObjCProtocolDecl *forwardDecl = nullptr;
1430 if (warnOnIncompleteProtocols &&
1431 NestedProtocolHasNoDefinition(proto, forwardDecl)) {
1432 Diag(identifierLocs[i], diag::warn_undef_protocolref)
1433 << proto->getDeclName();
1434 Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined)
1435 << forwardDecl;
1436 }
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001437
1438 // If everything this far has been a type name (and we care
1439 // about such things), check whether this name refers to a type
1440 // as well.
1441 if (allAreTypeNames) {
1442 if (auto *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1443 LookupOrdinaryName)) {
1444 if (isa<ObjCInterfaceDecl>(decl)) {
1445 if (firstClassNameLoc.isInvalid())
1446 firstClassNameLoc = identifierLocs[i];
1447 } else if (!isa<TypeDecl>(decl)) {
1448 // Not a type.
1449 allAreTypeNames = false;
1450 }
1451 } else {
1452 allAreTypeNames = false;
1453 }
1454 }
1455 }
1456
1457 // All of the protocols listed also have type names, and at least
1458 // one is an Objective-C class name. Check whether all of the
1459 // protocol conformances are declared by the base class itself, in
1460 // which case we warn.
1461 if (allAreTypeNames && firstClassNameLoc.isValid()) {
1462 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> knownProtocols;
1463 Context.CollectInheritedProtocols(baseClass, knownProtocols);
1464 bool allProtocolsDeclared = true;
1465 for (auto proto : protocols) {
1466 if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) {
1467 allProtocolsDeclared = false;
1468 break;
1469 }
1470 }
1471
1472 if (allProtocolsDeclared) {
1473 Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type)
1474 << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc)
Craig Topper07fa1762015-11-15 02:31:46 +00001475 << FixItHint::CreateInsertion(getLocForEndOfToken(firstClassNameLoc),
1476 " *");
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001477 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00001478 }
1479
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001480 protocolLAngleLoc = lAngleLoc;
1481 protocolRAngleLoc = rAngleLoc;
1482 assert(protocols.size() == identifierLocs.size());
Douglas Gregore9d95f12015-07-07 03:57:35 +00001483 };
1484
1485 // Attempt to resolve all of the identifiers as protocols.
1486 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1487 ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]);
1488 protocols.push_back(proto);
1489 if (proto)
1490 ++numProtocolsResolved;
1491 }
1492
1493 // If all of the names were protocols, these were protocol qualifiers.
1494 if (numProtocolsResolved == identifiers.size())
1495 return resolvedAsProtocols();
1496
1497 // Attempt to resolve all of the identifiers as type names or
1498 // Objective-C class names. The latter is technically ill-formed,
1499 // but is probably something like \c NSArray<NSView *> missing the
1500 // \c*.
1501 typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl;
1502 SmallVector<TypeOrClassDecl, 4> typeDecls;
1503 unsigned numTypeDeclsResolved = 0;
1504 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1505 NamedDecl *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1506 LookupOrdinaryName);
1507 if (!decl) {
1508 typeDecls.push_back(TypeOrClassDecl());
1509 continue;
1510 }
1511
1512 if (auto typeDecl = dyn_cast<TypeDecl>(decl)) {
1513 typeDecls.push_back(typeDecl);
1514 ++numTypeDeclsResolved;
1515 continue;
1516 }
1517
1518 if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) {
1519 typeDecls.push_back(objcClass);
1520 ++numTypeDeclsResolved;
1521 continue;
1522 }
1523
1524 typeDecls.push_back(TypeOrClassDecl());
1525 }
1526
1527 AttributeFactory attrFactory;
1528
1529 // Local function that forms a reference to the given type or
1530 // Objective-C class declaration.
1531 auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc)
1532 -> TypeResult {
1533 // Form declaration specifiers. They simply refer to the type.
1534 DeclSpec DS(attrFactory);
1535 const char* prevSpec; // unused
1536 unsigned diagID; // unused
1537 QualType type;
1538 if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>())
1539 type = Context.getTypeDeclType(actualTypeDecl);
1540 else
1541 type = Context.getObjCInterfaceType(typeDecl.get<ObjCInterfaceDecl *>());
1542 TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc);
1543 ParsedType parsedType = CreateParsedType(type, parsedTSInfo);
1544 DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID,
1545 parsedType, Context.getPrintingPolicy());
1546 // Use the identifier location for the type source range.
1547 DS.SetRangeStart(loc);
1548 DS.SetRangeEnd(loc);
1549
1550 // Form the declarator.
Faisal Vali421b2d12017-12-29 05:41:00 +00001551 Declarator D(DS, DeclaratorContext::TypeNameContext);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001552
1553 // If we have a typedef of an Objective-C class type that is missing a '*',
1554 // add the '*'.
1555 if (type->getAs<ObjCInterfaceType>()) {
Craig Topper07fa1762015-11-15 02:31:46 +00001556 SourceLocation starLoc = getLocForEndOfToken(loc);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001557 ParsedAttributes parsedAttrs(attrFactory);
1558 D.AddTypeInfo(DeclaratorChunk::getPointer(/*typeQuals=*/0, starLoc,
1559 SourceLocation(),
1560 SourceLocation(),
1561 SourceLocation(),
Andrey Bokhanko45d41322016-05-11 18:38:21 +00001562 SourceLocation(),
Douglas Gregore9d95f12015-07-07 03:57:35 +00001563 SourceLocation()),
Hans Wennborgdcfba332015-10-06 23:40:43 +00001564 parsedAttrs,
1565 starLoc);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001566
1567 // Diagnose the missing '*'.
1568 Diag(loc, diag::err_objc_type_arg_missing_star)
1569 << type
1570 << FixItHint::CreateInsertion(starLoc, " *");
1571 }
1572
1573 // Convert this to a type.
1574 return ActOnTypeName(S, D);
1575 };
1576
1577 // Local function that updates the declaration specifiers with
1578 // type argument information.
1579 auto resolvedAsTypeDecls = [&] {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001580 // We did not resolve these as protocols.
1581 protocols.clear();
1582
Douglas Gregore9d95f12015-07-07 03:57:35 +00001583 assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl");
1584 // Map type declarations to type arguments.
Douglas Gregore9d95f12015-07-07 03:57:35 +00001585 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1586 // Map type reference to a type.
1587 TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]);
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001588 if (!type.isUsable()) {
1589 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001590 return;
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001591 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00001592
1593 typeArgs.push_back(type.get());
1594 }
1595
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001596 typeArgsLAngleLoc = lAngleLoc;
1597 typeArgsRAngleLoc = rAngleLoc;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001598 };
1599
1600 // If all of the identifiers can be resolved as type names or
1601 // Objective-C class names, we have type arguments.
1602 if (numTypeDeclsResolved == identifiers.size())
1603 return resolvedAsTypeDecls();
1604
1605 // Error recovery: some names weren't found, or we have a mix of
1606 // type and protocol names. Go resolve all of the unresolved names
1607 // and complain if we can't find a consistent answer.
1608 LookupNameKind lookupKind = LookupAnyName;
1609 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1610 // If we already have a protocol or type. Check whether it is the
1611 // right thing.
1612 if (protocols[i] || typeDecls[i]) {
1613 // If we haven't figured out whether we want types or protocols
1614 // yet, try to figure it out from this name.
1615 if (lookupKind == LookupAnyName) {
1616 // If this name refers to both a protocol and a type (e.g., \c
1617 // NSObject), don't conclude anything yet.
1618 if (protocols[i] && typeDecls[i])
1619 continue;
1620
1621 // Otherwise, let this name decide whether we'll be correcting
1622 // toward types or protocols.
1623 lookupKind = protocols[i] ? LookupObjCProtocolName
1624 : LookupOrdinaryName;
1625 continue;
1626 }
1627
1628 // If we want protocols and we have a protocol, there's nothing
1629 // more to do.
1630 if (lookupKind == LookupObjCProtocolName && protocols[i])
1631 continue;
1632
1633 // If we want types and we have a type declaration, there's
1634 // nothing more to do.
1635 if (lookupKind == LookupOrdinaryName && typeDecls[i])
1636 continue;
1637
1638 // We have a conflict: some names refer to protocols and others
1639 // refer to types.
Bruno Cardoso Lopesc54768f2016-04-13 20:59:07 +00001640 DiagnoseTypeArgsAndProtocols(identifiers[0], identifierLocs[0],
1641 identifiers[i], identifierLocs[i],
1642 protocols[i] != nullptr);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001643
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001644 protocols.clear();
1645 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001646 return;
1647 }
1648
1649 // Perform typo correction on the name.
1650 TypoCorrection corrected = CorrectTypo(
1651 DeclarationNameInfo(identifiers[i], identifierLocs[i]), lookupKind, S,
1652 nullptr,
1653 llvm::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(Context,
1654 lookupKind),
1655 CTK_ErrorRecovery);
1656 if (corrected) {
1657 // Did we find a protocol?
1658 if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) {
1659 diagnoseTypo(corrected,
1660 PDiag(diag::err_undeclared_protocol_suggest)
1661 << identifiers[i]);
1662 lookupKind = LookupObjCProtocolName;
1663 protocols[i] = proto;
1664 ++numProtocolsResolved;
1665 continue;
1666 }
1667
1668 // Did we find a type?
1669 if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) {
1670 diagnoseTypo(corrected,
1671 PDiag(diag::err_unknown_typename_suggest)
1672 << identifiers[i]);
1673 lookupKind = LookupOrdinaryName;
1674 typeDecls[i] = typeDecl;
1675 ++numTypeDeclsResolved;
1676 continue;
1677 }
1678
1679 // Did we find an Objective-C class?
1680 if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1681 diagnoseTypo(corrected,
1682 PDiag(diag::err_unknown_type_or_class_name_suggest)
1683 << identifiers[i] << true);
1684 lookupKind = LookupOrdinaryName;
1685 typeDecls[i] = objcClass;
1686 ++numTypeDeclsResolved;
1687 continue;
1688 }
1689 }
1690
1691 // We couldn't find anything.
1692 Diag(identifierLocs[i],
1693 (lookupKind == LookupAnyName ? diag::err_objc_type_arg_missing
1694 : lookupKind == LookupObjCProtocolName ? diag::err_undeclared_protocol
1695 : diag::err_unknown_typename))
1696 << identifiers[i];
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001697 protocols.clear();
1698 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001699 return;
1700 }
1701
1702 // If all of the names were (corrected to) protocols, these were
1703 // protocol qualifiers.
1704 if (numProtocolsResolved == identifiers.size())
1705 return resolvedAsProtocols();
1706
1707 // Otherwise, all of the names were (corrected to) types.
1708 assert(numTypeDeclsResolved == identifiers.size() && "Not all types?");
1709 return resolvedAsTypeDecls();
1710}
1711
Fariborz Jahanianabf63e7b2009-03-02 19:06:08 +00001712/// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001713/// a class method in its extension.
1714///
Mike Stump11289f42009-09-09 15:08:12 +00001715void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001716 ObjCInterfaceDecl *ID) {
1717 if (!ID)
1718 return; // Possibly due to previous error
1719
1720 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
Aaron Ballmanaff18c02014-03-13 19:03:34 +00001721 for (auto *MD : ID->methods())
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001722 MethodMap[MD->getSelector()] = MD;
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001723
1724 if (MethodMap.empty())
1725 return;
Aaron Ballmanaff18c02014-03-13 19:03:34 +00001726 for (const auto *Method : CAT->methods()) {
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001727 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
Fariborz Jahanian83d674e2014-03-17 17:46:10 +00001728 if (PrevMethod &&
1729 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
1730 !MatchTwoMethodDeclarations(Method, PrevMethod)) {
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001731 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1732 << Method->getDeclName();
1733 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1734 }
1735 }
1736}
1737
James Dennett634962f2012-06-14 21:40:34 +00001738/// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
Douglas Gregorf6102672012-01-01 21:23:57 +00001739Sema::DeclGroupPtrTy
Chris Lattnerda463fe2007-12-12 07:09:47 +00001740Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
Craig Topper0f723bb2015-10-22 05:00:01 +00001741 ArrayRef<IdentifierLocPair> IdentList,
Fariborz Jahanian1470e932008-12-17 01:07:27 +00001742 AttributeList *attrList) {
Douglas Gregorf6102672012-01-01 21:23:57 +00001743 SmallVector<Decl *, 8> DeclsInGroup;
Craig Topper0f723bb2015-10-22 05:00:01 +00001744 for (const IdentifierLocPair &IdentPair : IdentList) {
1745 IdentifierInfo *Ident = IdentPair.first;
1746 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentPair.second,
Richard Smithbecb92d2017-10-10 22:33:17 +00001747 forRedeclarationInCurContext());
Douglas Gregor32c17572012-01-01 20:30:41 +00001748 ObjCProtocolDecl *PDecl
1749 = ObjCProtocolDecl::Create(Context, CurContext, Ident,
Craig Topper0f723bb2015-10-22 05:00:01 +00001750 IdentPair.second, AtProtocolLoc,
Douglas Gregor05a1f4d2012-01-01 22:06:18 +00001751 PrevDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +00001752
1753 PushOnScopeChains(PDecl, TUScope);
Douglas Gregorf6102672012-01-01 21:23:57 +00001754 CheckObjCDeclScope(PDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +00001755
Douglas Gregor42ff1bb2012-01-01 20:33:24 +00001756 if (attrList)
Douglas Gregor758a8692009-06-17 21:51:59 +00001757 ProcessDeclAttributeList(TUScope, PDecl, attrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001758 AddPragmaAttributes(TUScope, PDecl);
1759
Douglas Gregor32c17572012-01-01 20:30:41 +00001760 if (PrevDecl)
1761 mergeDeclAttributes(PDecl, PrevDecl);
1762
Douglas Gregorf6102672012-01-01 21:23:57 +00001763 DeclsInGroup.push_back(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001764 }
Mike Stump11289f42009-09-09 15:08:12 +00001765
Richard Smith3beb7c62017-01-12 02:27:38 +00001766 return BuildDeclaratorGroup(DeclsInGroup);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001767}
1768
John McCall48871652010-08-21 09:40:31 +00001769Decl *Sema::
Chris Lattnerd7352d62008-07-21 22:17:28 +00001770ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
1771 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001772 ObjCTypeParamList *typeParamList,
Chris Lattnerd7352d62008-07-21 22:17:28 +00001773 IdentifierInfo *CategoryName,
1774 SourceLocation CategoryLoc,
John McCall48871652010-08-21 09:40:31 +00001775 Decl * const *ProtoRefs,
Chris Lattnerd7352d62008-07-21 22:17:28 +00001776 unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001777 const SourceLocation *ProtoLocs,
Alex Lorenzf9371392017-03-23 11:44:25 +00001778 SourceLocation EndProtoLoc,
1779 AttributeList *AttrList) {
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001780 ObjCCategoryDecl *CDecl;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001781 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
Ted Kremenek514ff702010-02-23 19:39:46 +00001782
1783 /// Check that class of this category is already completely declared.
Douglas Gregor4123a862011-11-14 22:10:01 +00001784
1785 if (!IDecl
1786 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001787 diag::err_category_forward_interface,
Craig Topperc3ec1492014-05-26 06:22:03 +00001788 CategoryName == nullptr)) {
Ted Kremenek514ff702010-02-23 19:39:46 +00001789 // Create an invalid ObjCCategoryDecl to serve as context for
1790 // the enclosing method declarations. We mark the decl invalid
1791 // to make it clear that this isn't a valid AST.
1792 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001793 ClassLoc, CategoryLoc, CategoryName,
1794 IDecl, typeParamList);
Ted Kremenek514ff702010-02-23 19:39:46 +00001795 CDecl->setInvalidDecl();
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00001796 CurContext->addDecl(CDecl);
Douglas Gregor4123a862011-11-14 22:10:01 +00001797
1798 if (!IDecl)
1799 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001800 return ActOnObjCContainerStartDefinition(CDecl);
Ted Kremenek514ff702010-02-23 19:39:46 +00001801 }
1802
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001803 if (!CategoryName && IDecl->getImplementation()) {
1804 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
1805 Diag(IDecl->getImplementation()->getLocation(),
1806 diag::note_implementation_declared);
Ted Kremenek514ff702010-02-23 19:39:46 +00001807 }
1808
Fariborz Jahanian30a42922010-02-15 21:55:26 +00001809 if (CategoryName) {
1810 /// Check for duplicate interface declaration for this category
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001811 if (ObjCCategoryDecl *Previous
1812 = IDecl->FindCategoryDeclaration(CategoryName)) {
1813 // Class extensions can be declared multiple times, categories cannot.
1814 Diag(CategoryLoc, diag::warn_dup_category_def)
1815 << ClassName << CategoryName;
1816 Diag(Previous->getLocation(), diag::note_previous_definition);
Chris Lattner9018ca82009-02-16 21:26:43 +00001817 }
1818 }
Chris Lattner9018ca82009-02-16 21:26:43 +00001819
Douglas Gregor85f3f952015-07-07 03:57:15 +00001820 // If we have a type parameter list, check it.
1821 if (typeParamList) {
1822 if (auto prevTypeParamList = IDecl->getTypeParamList()) {
1823 if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList,
1824 CategoryName
1825 ? TypeParamListContext::Category
1826 : TypeParamListContext::Extension))
1827 typeParamList = nullptr;
1828 } else {
1829 Diag(typeParamList->getLAngleLoc(),
1830 diag::err_objc_parameterized_category_nonclass)
1831 << (CategoryName != nullptr)
1832 << ClassName
1833 << typeParamList->getSourceRange();
1834
1835 typeParamList = nullptr;
1836 }
1837 }
1838
Argyrios Kyrtzidis3a5094b2011-08-30 19:43:26 +00001839 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001840 ClassLoc, CategoryLoc, CategoryName, IDecl,
1841 typeParamList);
Argyrios Kyrtzidis3a5094b2011-08-30 19:43:26 +00001842 // FIXME: PushOnScopeChains?
1843 CurContext->addDecl(CDecl);
1844
Alex Lorenza9c966d2018-02-23 23:49:43 +00001845 // Process the attributes before looking at protocols to ensure that the
1846 // availability attribute is attached to the category to provide availability
1847 // checking for protocol uses.
1848 if (AttrList)
1849 ProcessDeclAttributeList(TUScope, CDecl, AttrList);
1850 AddPragmaAttributes(TUScope, CDecl);
1851
Chris Lattnerda463fe2007-12-12 07:09:47 +00001852 if (NumProtoRefs) {
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001853 diagnoseUseOfProtocols(*this, CDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1854 NumProtoRefs, ProtoLocs);
1855 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001856 ProtoLocs, Context);
Fariborz Jahanian092cd6e2009-10-05 20:41:32 +00001857 // Protocols in the class extension belong to the class.
Fariborz Jahanian30a42922010-02-15 21:55:26 +00001858 if (CDecl->IsClassExtension())
Roman Divackye6377112012-09-06 15:59:27 +00001859 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001860 NumProtoRefs, Context);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001861 }
Mike Stump11289f42009-09-09 15:08:12 +00001862
Anders Carlssona6b508a2008-11-04 16:57:32 +00001863 CheckObjCDeclScope(CDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001864 return ActOnObjCContainerStartDefinition(CDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001865}
1866
1867/// ActOnStartCategoryImplementation - Perform semantic checks on the
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001868/// category implementation declaration and build an ObjCCategoryImplDecl
Chris Lattnerda463fe2007-12-12 07:09:47 +00001869/// object.
John McCall48871652010-08-21 09:40:31 +00001870Decl *Sema::ActOnStartCategoryImplementation(
Chris Lattnerda463fe2007-12-12 07:09:47 +00001871 SourceLocation AtCatImplLoc,
1872 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1873 IdentifierInfo *CatName, SourceLocation CatLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001874 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
Craig Topperc3ec1492014-05-26 06:22:03 +00001875 ObjCCategoryDecl *CatIDecl = nullptr;
Argyrios Kyrtzidis4af2cb32012-03-02 19:14:29 +00001876 if (IDecl && IDecl->hasDefinition()) {
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001877 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
1878 if (!CatIDecl) {
1879 // Category @implementation with no corresponding @interface.
1880 // Create and install one.
Argyrios Kyrtzidis41fc05c2011-11-23 20:27:26 +00001881 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
1882 ClassLoc, CatLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001883 CatName, IDecl,
1884 /*typeParamList=*/nullptr);
Argyrios Kyrtzidis41fc05c2011-11-23 20:27:26 +00001885 CatIDecl->setImplicit();
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001886 }
1887 }
1888
Mike Stump11289f42009-09-09 15:08:12 +00001889 ObjCCategoryImplDecl *CDecl =
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001890 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
Argyrios Kyrtzidis4996f5f2011-12-09 00:31:40 +00001891 ClassLoc, AtCatImplLoc, CatLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001892 /// Check that class of this category is already completely declared.
Douglas Gregor4123a862011-11-14 22:10:01 +00001893 if (!IDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001894 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
John McCalld2930c22011-07-22 02:45:48 +00001895 CDecl->setInvalidDecl();
Douglas Gregor4123a862011-11-14 22:10:01 +00001896 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1897 diag::err_undef_interface)) {
1898 CDecl->setInvalidDecl();
John McCalld2930c22011-07-22 02:45:48 +00001899 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001900
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001901 // FIXME: PushOnScopeChains?
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001902 CurContext->addDecl(CDecl);
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001903
Douglas Gregor24ae22c2016-04-01 23:23:52 +00001904 // If the interface has the objc_runtime_visible attribute, we
1905 // cannot implement a category for it.
1906 if (IDecl && IDecl->hasAttr<ObjCRuntimeVisibleAttr>()) {
1907 Diag(ClassLoc, diag::err_objc_runtime_visible_category)
1908 << IDecl->getDeclName();
1909 }
1910
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001911 /// Check that CatName, category name, is not used in another implementation.
1912 if (CatIDecl) {
1913 if (CatIDecl->getImplementation()) {
1914 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
1915 << CatName;
1916 Diag(CatIDecl->getImplementation()->getLocation(),
1917 diag::note_previous_definition);
Argyrios Kyrtzidis0f6d5ca2013-05-30 18:53:21 +00001918 CDecl->setInvalidDecl();
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001919 } else {
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001920 CatIDecl->setImplementation(CDecl);
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001921 // Warn on implementating category of deprecated class under
1922 // -Wdeprecated-implementations flag.
Alex Lorenzf81d97e2017-07-13 16:35:59 +00001923 DiagnoseObjCImplementedDeprecations(*this, CatIDecl,
1924 CDecl->getLocation());
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001925 }
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001926 }
Mike Stump11289f42009-09-09 15:08:12 +00001927
Anders Carlssona6b508a2008-11-04 16:57:32 +00001928 CheckObjCDeclScope(CDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001929 return ActOnObjCContainerStartDefinition(CDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001930}
1931
John McCall48871652010-08-21 09:40:31 +00001932Decl *Sema::ActOnStartClassImplementation(
Chris Lattnerda463fe2007-12-12 07:09:47 +00001933 SourceLocation AtClassImplLoc,
1934 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001935 IdentifierInfo *SuperClassname,
Chris Lattnerda463fe2007-12-12 07:09:47 +00001936 SourceLocation SuperClassLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001937 ObjCInterfaceDecl *IDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001938 // Check for another declaration kind with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00001939 NamedDecl *PrevDecl
Douglas Gregorb8eaf292010-04-15 23:40:53 +00001940 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00001941 forRedeclarationInCurContext());
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001942 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001943 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Chris Lattner0369c572008-11-23 23:12:31 +00001944 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor1c283312010-08-11 12:19:30 +00001945 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
Richard Smithdb0ac552015-12-18 22:40:25 +00001946 // FIXME: This will produce an error if the definition of the interface has
1947 // been imported from a module but is not visible.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00001948 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1949 diag::warn_undef_interface);
Douglas Gregor40f7a002010-01-04 17:27:12 +00001950 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001951 // We did not find anything with the name ClassName; try to correct for
Douglas Gregor40f7a002010-01-04 17:27:12 +00001952 // typos in the class name.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001953 TypoCorrection Corrected = CorrectTypo(
1954 DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope,
1955 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(), CTK_NonError);
Richard Smithf9b15102013-08-17 00:46:16 +00001956 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1957 // Suggest the (potentially) correct interface name. Don't provide a
1958 // code-modification hint or use the typo name for recovery, because
1959 // this is just a warning. The program may actually be correct.
1960 diagnoseTypo(Corrected,
1961 PDiag(diag::warn_undef_interface_suggest) << ClassName,
1962 /*ErrorRecovery*/false);
Douglas Gregor40f7a002010-01-04 17:27:12 +00001963 } else {
1964 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
1965 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001966 }
Mike Stump11289f42009-09-09 15:08:12 +00001967
Chris Lattnerda463fe2007-12-12 07:09:47 +00001968 // Check that super class name is valid class name
Craig Topperc3ec1492014-05-26 06:22:03 +00001969 ObjCInterfaceDecl *SDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001970 if (SuperClassname) {
1971 // Check if a different kind of symbol declared in this scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001972 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
1973 LookupOrdinaryName);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001974 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001975 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
1976 << SuperClassname;
Chris Lattner0369c572008-11-23 23:12:31 +00001977 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001978 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001979 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidis3b60cff2012-03-13 01:09:36 +00001980 if (SDecl && !SDecl->hasDefinition())
Craig Topperc3ec1492014-05-26 06:22:03 +00001981 SDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001982 if (!SDecl)
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001983 Diag(SuperClassLoc, diag::err_undef_superclass)
1984 << SuperClassname << ClassName;
Douglas Gregor0b144e12011-12-15 00:29:59 +00001985 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00001986 // This implementation and its interface do not have the same
1987 // super class.
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001988 Diag(SuperClassLoc, diag::err_conflicting_super_class)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001989 << SDecl->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001990 Diag(SDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001991 }
1992 }
1993 }
Mike Stump11289f42009-09-09 15:08:12 +00001994
Chris Lattnerda463fe2007-12-12 07:09:47 +00001995 if (!IDecl) {
1996 // Legacy case of @implementation with no corresponding @interface.
1997 // Build, chain & install the interface decl into the identifier.
Daniel Dunbar73a73f52008-08-20 18:02:42 +00001998
Mike Stump87c57ac2009-05-16 07:39:55 +00001999 // FIXME: Do we support attributes on the @implementation? If so we should
2000 // copy them over.
Mike Stump11289f42009-09-09 15:08:12 +00002001 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00002002 ClassName, /*typeParamList=*/nullptr,
2003 /*PrevDecl=*/nullptr, ClassLoc,
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002004 true);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002005 AddPragmaAttributes(TUScope, IDecl);
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002006 IDecl->startDefinition();
Douglas Gregor16408322011-12-15 22:34:59 +00002007 if (SDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00002008 IDecl->setSuperClass(Context.getTrivialTypeSourceInfo(
2009 Context.getObjCInterfaceType(SDecl),
2010 SuperClassLoc));
Douglas Gregor16408322011-12-15 22:34:59 +00002011 IDecl->setEndOfDefinitionLoc(SuperClassLoc);
2012 } else {
2013 IDecl->setEndOfDefinitionLoc(ClassLoc);
2014 }
2015
Douglas Gregorac345a32009-04-24 00:16:12 +00002016 PushOnScopeChains(IDecl, TUScope);
Douglas Gregor1c283312010-08-11 12:19:30 +00002017 } else {
2018 // Mark the interface as being completed, even if it was just as
2019 // @class ....;
2020 // declaration; the user cannot reopen it.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002021 if (!IDecl->hasDefinition())
2022 IDecl->startDefinition();
Chris Lattnerda463fe2007-12-12 07:09:47 +00002023 }
Mike Stump11289f42009-09-09 15:08:12 +00002024
2025 ObjCImplementationDecl* IMPDecl =
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00002026 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
Argyrios Kyrtzidisfac31622013-05-03 18:05:44 +00002027 ClassLoc, AtClassImplLoc, SuperClassLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002028
Anders Carlssona6b508a2008-11-04 16:57:32 +00002029 if (CheckObjCDeclScope(IMPDecl))
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00002030 return ActOnObjCContainerStartDefinition(IMPDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002031
Chris Lattnerda463fe2007-12-12 07:09:47 +00002032 // Check that there is no duplicate implementation of this class.
Douglas Gregor1c283312010-08-11 12:19:30 +00002033 if (IDecl->getImplementation()) {
2034 // FIXME: Don't leak everything!
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002035 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
Argyrios Kyrtzidis43cee9352009-07-21 00:06:04 +00002036 Diag(IDecl->getImplementation()->getLocation(),
2037 diag::note_previous_definition);
Argyrios Kyrtzidis0f6d5ca2013-05-30 18:53:21 +00002038 IMPDecl->setInvalidDecl();
Douglas Gregor1c283312010-08-11 12:19:30 +00002039 } else { // add it to the list.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002040 IDecl->setImplementation(IMPDecl);
Douglas Gregor79947a22009-04-24 00:11:27 +00002041 PushOnScopeChains(IMPDecl, TUScope);
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00002042 // Warn on implementating deprecated class under
2043 // -Wdeprecated-implementations flag.
Alex Lorenzf81d97e2017-07-13 16:35:59 +00002044 DiagnoseObjCImplementedDeprecations(*this, IDecl, IMPDecl->getLocation());
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002045 }
Douglas Gregor24ae22c2016-04-01 23:23:52 +00002046
2047 // If the superclass has the objc_runtime_visible attribute, we
2048 // cannot implement a subclass of it.
2049 if (IDecl->getSuperClass() &&
2050 IDecl->getSuperClass()->hasAttr<ObjCRuntimeVisibleAttr>()) {
2051 Diag(ClassLoc, diag::err_objc_runtime_visible_subclass)
2052 << IDecl->getDeclName()
2053 << IDecl->getSuperClass()->getDeclName();
2054 }
2055
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00002056 return ActOnObjCContainerStartDefinition(IMPDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002057}
2058
Argyrios Kyrtzidis2e85c5f2012-02-23 21:11:20 +00002059Sema::DeclGroupPtrTy
2060Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
2061 SmallVector<Decl *, 64> DeclsInGroup;
2062 DeclsInGroup.reserve(Decls.size() + 1);
2063
2064 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
2065 Decl *Dcl = Decls[i];
2066 if (!Dcl)
2067 continue;
2068 if (Dcl->getDeclContext()->isFileContext())
2069 Dcl->setTopLevelDeclInObjCContainer();
2070 DeclsInGroup.push_back(Dcl);
2071 }
2072
2073 DeclsInGroup.push_back(ObjCImpDecl);
2074
Richard Smith3beb7c62017-01-12 02:27:38 +00002075 return BuildDeclaratorGroup(DeclsInGroup);
Argyrios Kyrtzidis2e85c5f2012-02-23 21:11:20 +00002076}
2077
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002078void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
2079 ObjCIvarDecl **ivars, unsigned numIvars,
Chris Lattnerda463fe2007-12-12 07:09:47 +00002080 SourceLocation RBrace) {
2081 assert(ImpDecl && "missing implementation decl");
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002082 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
Chris Lattnerda463fe2007-12-12 07:09:47 +00002083 if (!IDecl)
2084 return;
James Dennett634962f2012-06-14 21:40:34 +00002085 /// Check case of non-existing \@interface decl.
2086 /// (legacy objective-c \@implementation decl without an \@interface decl).
Chris Lattnerda463fe2007-12-12 07:09:47 +00002087 /// Add implementations's ivar to the synthesize class's ivar list.
Steve Naroffaac654a2009-04-20 20:09:33 +00002088 if (IDecl->isImplicitInterfaceDecl()) {
Douglas Gregor16408322011-12-15 22:34:59 +00002089 IDecl->setEndOfDefinitionLoc(RBrace);
Fariborz Jahanian20912d62010-02-17 17:00:07 +00002090 // Add ivar's to class's DeclContext.
2091 for (unsigned i = 0, e = numIvars; i != e; ++i) {
Fariborz Jahanianc0309cd2010-02-17 18:10:54 +00002092 ivars[i]->setLexicalDeclContext(ImpDecl);
Richard Smith05afe5e2012-03-13 03:12:56 +00002093 IDecl->makeDeclVisibleInContext(ivars[i]);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00002094 ImpDecl->addDecl(ivars[i]);
Fariborz Jahanian20912d62010-02-17 17:00:07 +00002095 }
2096
Chris Lattnerda463fe2007-12-12 07:09:47 +00002097 return;
2098 }
2099 // If implementation has empty ivar list, just return.
2100 if (numIvars == 0)
2101 return;
Mike Stump11289f42009-09-09 15:08:12 +00002102
Chris Lattnerda463fe2007-12-12 07:09:47 +00002103 assert(ivars && "missing @implementation ivars");
John McCall5fb5df92012-06-20 06:18:46 +00002104 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002105 if (ImpDecl->getSuperClass())
2106 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
2107 for (unsigned i = 0; i < numIvars; i++) {
2108 ObjCIvarDecl* ImplIvar = ivars[i];
2109 if (const ObjCIvarDecl *ClsIvar =
2110 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2111 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2112 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2113 continue;
2114 }
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00002115 // Check class extensions (unnamed categories) for duplicate ivars.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002116 for (const auto *CDecl : IDecl->visible_extensions()) {
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00002117 if (const ObjCIvarDecl *ClsExtIvar =
2118 CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2119 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2120 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
2121 continue;
2122 }
2123 }
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002124 // Instance ivar to Implementation's DeclContext.
2125 ImplIvar->setLexicalDeclContext(ImpDecl);
Richard Smith05afe5e2012-03-13 03:12:56 +00002126 IDecl->makeDeclVisibleInContext(ImplIvar);
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002127 ImpDecl->addDecl(ImplIvar);
2128 }
2129 return;
2130 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002131 // Check interface's Ivar list against those in the implementation.
2132 // names and types must match.
2133 //
Chris Lattnerda463fe2007-12-12 07:09:47 +00002134 unsigned j = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002135 ObjCInterfaceDecl::ivar_iterator
Chris Lattner061227a2007-12-12 17:58:05 +00002136 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
2137 for (; numIvars > 0 && IVI != IVE; ++IVI) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002138 ObjCIvarDecl* ImplIvar = ivars[j++];
David Blaikie40ed2972012-06-06 20:45:41 +00002139 ObjCIvarDecl* ClsIvar = *IVI;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002140 assert (ImplIvar && "missing implementation ivar");
2141 assert (ClsIvar && "missing class ivar");
Mike Stump11289f42009-09-09 15:08:12 +00002142
Steve Naroff157599f2009-03-03 14:49:36 +00002143 // First, make sure the types match.
Richard Smithcaf33902011-10-10 18:28:20 +00002144 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
Chris Lattner3b054132008-11-19 05:08:23 +00002145 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002146 << ImplIvar->getIdentifier()
2147 << ImplIvar->getType() << ClsIvar->getType();
Chris Lattner0369c572008-11-23 23:12:31 +00002148 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
Richard Smithcaf33902011-10-10 18:28:20 +00002149 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
2150 ImplIvar->getBitWidthValue(Context) !=
2151 ClsIvar->getBitWidthValue(Context)) {
2152 Diag(ImplIvar->getBitWidth()->getLocStart(),
2153 diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier();
2154 Diag(ClsIvar->getBitWidth()->getLocStart(),
2155 diag::note_previous_definition);
Mike Stump11289f42009-09-09 15:08:12 +00002156 }
Steve Naroff157599f2009-03-03 14:49:36 +00002157 // Make sure the names are identical.
2158 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002159 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002160 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
Chris Lattner0369c572008-11-23 23:12:31 +00002161 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002162 }
2163 --numIvars;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002164 }
Mike Stump11289f42009-09-09 15:08:12 +00002165
Chris Lattner0f29d982007-12-12 18:11:49 +00002166 if (numIvars > 0)
Alp Tokerfff06742013-12-02 03:50:21 +00002167 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
Chris Lattner0f29d982007-12-12 18:11:49 +00002168 else if (IVI != IVE)
Alp Tokerfff06742013-12-02 03:50:21 +00002169 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002170}
2171
Ted Kremenekf87decd2013-12-13 05:58:44 +00002172static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
2173 ObjCMethodDecl *method,
2174 bool &IncompleteImpl,
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002175 unsigned DiagID,
Craig Topperc3ec1492014-05-26 06:22:03 +00002176 NamedDecl *NeededFor = nullptr) {
Fariborz Jahanian9fc39c42011-06-24 20:31:37 +00002177 // No point warning no definition of method which is 'unavailable'.
Douglas Gregorc2e3d5c2012-12-11 18:53:07 +00002178 switch (method->getAvailability()) {
2179 case AR_Available:
2180 case AR_Deprecated:
2181 break;
2182
2183 // Don't warn about unavailable or not-yet-introduced methods.
2184 case AR_NotYetIntroduced:
2185 case AR_Unavailable:
Fariborz Jahanian9fc39c42011-06-24 20:31:37 +00002186 return;
Douglas Gregorc2e3d5c2012-12-11 18:53:07 +00002187 }
2188
Ted Kremenek65d63572013-03-27 00:02:21 +00002189 // FIXME: For now ignore 'IncompleteImpl'.
2190 // Previously we grouped all unimplemented methods under a single
2191 // warning, but some users strongly voiced that they would prefer
2192 // separate warnings. We will give that approach a try, as that
2193 // matches what we do with protocols.
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002194 {
2195 const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
2196 B << method;
2197 if (NeededFor)
2198 B << NeededFor;
2199 }
Ted Kremenek65d63572013-03-27 00:02:21 +00002200
2201 // Issue a note to the original declaration.
2202 SourceLocation MethodLoc = method->getLocStart();
2203 if (MethodLoc.isValid())
Ted Kremenekf87decd2013-12-13 05:58:44 +00002204 S.Diag(MethodLoc, diag::note_method_declared_at) << method;
Steve Naroff15833ed2008-02-10 21:38:56 +00002205}
2206
David Chisnallb62d15c2010-10-25 17:23:52 +00002207/// Determines if type B can be substituted for type A. Returns true if we can
2208/// guarantee that anything that the user will do to an object of type A can
2209/// also be done to an object of type B. This is trivially true if the two
2210/// types are the same, or if B is a subclass of A. It becomes more complex
2211/// in cases where protocols are involved.
2212///
2213/// Object types in Objective-C describe the minimum requirements for an
2214/// object, rather than providing a complete description of a type. For
2215/// example, if A is a subclass of B, then B* may refer to an instance of A.
2216/// The principle of substitutability means that we may use an instance of A
2217/// anywhere that we may use an instance of B - it will implement all of the
2218/// ivars of B and all of the methods of B.
2219///
2220/// This substitutability is important when type checking methods, because
2221/// the implementation may have stricter type definitions than the interface.
2222/// The interface specifies minimum requirements, but the implementation may
2223/// have more accurate ones. For example, a method may privately accept
2224/// instances of B, but only publish that it accepts instances of A. Any
2225/// object passed to it will be type checked against B, and so will implicitly
2226/// by a valid A*. Similarly, a method may return a subclass of the class that
2227/// it is declared as returning.
2228///
2229/// This is most important when considering subclassing. A method in a
2230/// subclass must accept any object as an argument that its superclass's
2231/// implementation accepts. It may, however, accept a more general type
2232/// without breaking substitutability (i.e. you can still use the subclass
2233/// anywhere that you can use the superclass, but not vice versa). The
2234/// converse requirement applies to return types: the return type for a
2235/// subclass method must be a valid object of the kind that the superclass
2236/// advertises, but it may be specified more accurately. This avoids the need
2237/// for explicit down-casting by callers.
2238///
2239/// Note: This is a stricter requirement than for assignment.
John McCall071df462010-10-28 02:34:38 +00002240static bool isObjCTypeSubstitutable(ASTContext &Context,
2241 const ObjCObjectPointerType *A,
2242 const ObjCObjectPointerType *B,
2243 bool rejectId) {
2244 // Reject a protocol-unqualified id.
2245 if (rejectId && B->isObjCIdType()) return false;
David Chisnallb62d15c2010-10-25 17:23:52 +00002246
2247 // If B is a qualified id, then A must also be a qualified id and it must
2248 // implement all of the protocols in B. It may not be a qualified class.
2249 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
2250 // stricter definition so it is not substitutable for id<A>.
2251 if (B->isObjCQualifiedIdType()) {
2252 return A->isObjCQualifiedIdType() &&
John McCall071df462010-10-28 02:34:38 +00002253 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
2254 QualType(B,0),
2255 false);
David Chisnallb62d15c2010-10-25 17:23:52 +00002256 }
2257
2258 /*
2259 // id is a special type that bypasses type checking completely. We want a
2260 // warning when it is used in one place but not another.
2261 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
2262
2263
2264 // If B is a qualified id, then A must also be a qualified id (which it isn't
2265 // if we've got this far)
2266 if (B->isObjCQualifiedIdType()) return false;
2267 */
2268
2269 // Now we know that A and B are (potentially-qualified) class types. The
2270 // normal rules for assignment apply.
John McCall071df462010-10-28 02:34:38 +00002271 return Context.canAssignObjCInterfaces(A, B);
David Chisnallb62d15c2010-10-25 17:23:52 +00002272}
2273
John McCall071df462010-10-28 02:34:38 +00002274static SourceRange getTypeRange(TypeSourceInfo *TSI) {
2275 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
2276}
2277
Douglas Gregor813a0662015-06-19 18:14:38 +00002278/// Determine whether two set of Objective-C declaration qualifiers conflict.
2279static bool objcModifiersConflict(Decl::ObjCDeclQualifier x,
2280 Decl::ObjCDeclQualifier y) {
2281 return (x & ~Decl::OBJC_TQ_CSNullability) !=
2282 (y & ~Decl::OBJC_TQ_CSNullability);
2283}
2284
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002285static bool CheckMethodOverrideReturn(Sema &S,
John McCall071df462010-10-28 02:34:38 +00002286 ObjCMethodDecl *MethodImpl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002287 ObjCMethodDecl *MethodDecl,
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002288 bool IsProtocolMethodDecl,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002289 bool IsOverridingMode,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002290 bool Warn) {
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002291 if (IsProtocolMethodDecl &&
Douglas Gregor813a0662015-06-19 18:14:38 +00002292 objcModifiersConflict(MethodDecl->getObjCDeclQualifier(),
2293 MethodImpl->getObjCDeclQualifier())) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002294 if (Warn) {
Alp Toker314cc812014-01-25 16:55:45 +00002295 S.Diag(MethodImpl->getLocation(),
2296 (IsOverridingMode
2297 ? diag::warn_conflicting_overriding_ret_type_modifiers
2298 : diag::warn_conflicting_ret_type_modifiers))
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002299 << MethodImpl->getDeclName()
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002300 << MethodImpl->getReturnTypeSourceRange();
Alp Toker314cc812014-01-25 16:55:45 +00002301 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002302 << MethodDecl->getReturnTypeSourceRange();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002303 }
2304 else
2305 return false;
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002306 }
Douglas Gregor813a0662015-06-19 18:14:38 +00002307 if (Warn && IsOverridingMode &&
2308 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2309 !S.Context.hasSameNullabilityTypeQualifier(MethodImpl->getReturnType(),
2310 MethodDecl->getReturnType(),
2311 false)) {
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002312 auto nullabilityMethodImpl =
2313 *MethodImpl->getReturnType()->getNullability(S.Context);
2314 auto nullabilityMethodDecl =
2315 *MethodDecl->getReturnType()->getNullability(S.Context);
Douglas Gregor813a0662015-06-19 18:14:38 +00002316 S.Diag(MethodImpl->getLocation(),
2317 diag::warn_conflicting_nullability_attr_overriding_ret_types)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002318 << DiagNullabilityKind(
2319 nullabilityMethodImpl,
2320 ((MethodImpl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2321 != 0))
2322 << DiagNullabilityKind(
2323 nullabilityMethodDecl,
2324 ((MethodDecl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2325 != 0));
Douglas Gregor813a0662015-06-19 18:14:38 +00002326 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2327 }
2328
Alp Toker314cc812014-01-25 16:55:45 +00002329 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
2330 MethodDecl->getReturnType()))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002331 return true;
2332 if (!Warn)
2333 return false;
John McCall071df462010-10-28 02:34:38 +00002334
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002335 unsigned DiagID =
2336 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
2337 : diag::warn_conflicting_ret_types;
John McCall071df462010-10-28 02:34:38 +00002338
2339 // Mismatches between ObjC pointers go into a different warning
2340 // category, and sometimes they're even completely whitelisted.
2341 if (const ObjCObjectPointerType *ImplPtrTy =
Alp Toker314cc812014-01-25 16:55:45 +00002342 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
John McCall071df462010-10-28 02:34:38 +00002343 if (const ObjCObjectPointerType *IfacePtrTy =
Alp Toker314cc812014-01-25 16:55:45 +00002344 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
John McCall071df462010-10-28 02:34:38 +00002345 // Allow non-matching return types as long as they don't violate
2346 // the principle of substitutability. Specifically, we permit
2347 // return types that are subclasses of the declared return type,
2348 // or that are more-qualified versions of the declared type.
2349 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002350 return false;
John McCall071df462010-10-28 02:34:38 +00002351
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002352 DiagID =
2353 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002354 : diag::warn_non_covariant_ret_types;
John McCall071df462010-10-28 02:34:38 +00002355 }
2356 }
2357
2358 S.Diag(MethodImpl->getLocation(), DiagID)
Alp Toker314cc812014-01-25 16:55:45 +00002359 << MethodImpl->getDeclName() << MethodDecl->getReturnType()
2360 << MethodImpl->getReturnType()
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002361 << MethodImpl->getReturnTypeSourceRange();
Alp Toker314cc812014-01-25 16:55:45 +00002362 S.Diag(MethodDecl->getLocation(), IsOverridingMode
2363 ? diag::note_previous_declaration
2364 : diag::note_previous_definition)
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002365 << MethodDecl->getReturnTypeSourceRange();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002366 return false;
John McCall071df462010-10-28 02:34:38 +00002367}
2368
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002369static bool CheckMethodOverrideParam(Sema &S,
John McCall071df462010-10-28 02:34:38 +00002370 ObjCMethodDecl *MethodImpl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002371 ObjCMethodDecl *MethodDecl,
John McCall071df462010-10-28 02:34:38 +00002372 ParmVarDecl *ImplVar,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002373 ParmVarDecl *IfaceVar,
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002374 bool IsProtocolMethodDecl,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002375 bool IsOverridingMode,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002376 bool Warn) {
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002377 if (IsProtocolMethodDecl &&
Douglas Gregor813a0662015-06-19 18:14:38 +00002378 objcModifiersConflict(ImplVar->getObjCDeclQualifier(),
2379 IfaceVar->getObjCDeclQualifier())) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002380 if (Warn) {
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002381 if (IsOverridingMode)
2382 S.Diag(ImplVar->getLocation(),
2383 diag::warn_conflicting_overriding_param_modifiers)
2384 << getTypeRange(ImplVar->getTypeSourceInfo())
2385 << MethodImpl->getDeclName();
2386 else S.Diag(ImplVar->getLocation(),
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002387 diag::warn_conflicting_param_modifiers)
2388 << getTypeRange(ImplVar->getTypeSourceInfo())
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002389 << MethodImpl->getDeclName();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002390 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
2391 << getTypeRange(IfaceVar->getTypeSourceInfo());
2392 }
2393 else
2394 return false;
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002395 }
2396
John McCall071df462010-10-28 02:34:38 +00002397 QualType ImplTy = ImplVar->getType();
2398 QualType IfaceTy = IfaceVar->getType();
Douglas Gregor813a0662015-06-19 18:14:38 +00002399 if (Warn && IsOverridingMode &&
2400 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2401 !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) {
Douglas Gregor813a0662015-06-19 18:14:38 +00002402 S.Diag(ImplVar->getLocation(),
2403 diag::warn_conflicting_nullability_attr_overriding_param_types)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002404 << DiagNullabilityKind(
2405 *ImplTy->getNullability(S.Context),
2406 ((ImplVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2407 != 0))
2408 << DiagNullabilityKind(
2409 *IfaceTy->getNullability(S.Context),
2410 ((IfaceVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2411 != 0));
2412 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration);
Douglas Gregor813a0662015-06-19 18:14:38 +00002413 }
John McCall071df462010-10-28 02:34:38 +00002414 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002415 return true;
Manman Renc5705ba2016-09-13 17:41:05 +00002416
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002417 if (!Warn)
2418 return false;
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002419 unsigned DiagID =
2420 IsOverridingMode ? diag::warn_conflicting_overriding_param_types
2421 : diag::warn_conflicting_param_types;
John McCall071df462010-10-28 02:34:38 +00002422
2423 // Mismatches between ObjC pointers go into a different warning
2424 // category, and sometimes they're even completely whitelisted.
2425 if (const ObjCObjectPointerType *ImplPtrTy =
2426 ImplTy->getAs<ObjCObjectPointerType>()) {
2427 if (const ObjCObjectPointerType *IfacePtrTy =
2428 IfaceTy->getAs<ObjCObjectPointerType>()) {
2429 // Allow non-matching argument types as long as they don't
2430 // violate the principle of substitutability. Specifically, the
2431 // implementation must accept any objects that the superclass
2432 // accepts, however it may also accept others.
2433 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002434 return false;
John McCall071df462010-10-28 02:34:38 +00002435
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002436 DiagID =
2437 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002438 : diag::warn_non_contravariant_param_types;
John McCall071df462010-10-28 02:34:38 +00002439 }
2440 }
2441
2442 S.Diag(ImplVar->getLocation(), DiagID)
2443 << getTypeRange(ImplVar->getTypeSourceInfo())
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002444 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
2445 S.Diag(IfaceVar->getLocation(),
2446 (IsOverridingMode ? diag::note_previous_declaration
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002447 : diag::note_previous_definition))
John McCall071df462010-10-28 02:34:38 +00002448 << getTypeRange(IfaceVar->getTypeSourceInfo());
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002449 return false;
John McCall071df462010-10-28 02:34:38 +00002450}
John McCall31168b02011-06-15 23:02:42 +00002451
2452/// In ARC, check whether the conventional meanings of the two methods
2453/// match. If they don't, it's a hard error.
2454static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
2455 ObjCMethodDecl *decl) {
2456 ObjCMethodFamily implFamily = impl->getMethodFamily();
2457 ObjCMethodFamily declFamily = decl->getMethodFamily();
2458 if (implFamily == declFamily) return false;
2459
2460 // Since conventions are sorted by selector, the only possibility is
2461 // that the types differ enough to cause one selector or the other
2462 // to fall out of the family.
2463 assert(implFamily == OMF_None || declFamily == OMF_None);
2464
2465 // No further diagnostics required on invalid declarations.
2466 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
2467
2468 const ObjCMethodDecl *unmatched = impl;
2469 ObjCMethodFamily family = declFamily;
2470 unsigned errorID = diag::err_arc_lost_method_convention;
2471 unsigned noteID = diag::note_arc_lost_method_convention;
2472 if (declFamily == OMF_None) {
2473 unmatched = decl;
2474 family = implFamily;
2475 errorID = diag::err_arc_gained_method_convention;
2476 noteID = diag::note_arc_gained_method_convention;
2477 }
2478
2479 // Indexes into a %select clause in the diagnostic.
2480 enum FamilySelector {
2481 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
2482 };
2483 FamilySelector familySelector = FamilySelector();
2484
2485 switch (family) {
2486 case OMF_None: llvm_unreachable("logic error, no method convention");
2487 case OMF_retain:
2488 case OMF_release:
2489 case OMF_autorelease:
2490 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +00002491 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002492 case OMF_retainCount:
2493 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002494 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002495 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00002496 // Mismatches for these methods don't change ownership
2497 // conventions, so we don't care.
2498 return false;
2499
2500 case OMF_init: familySelector = F_init; break;
2501 case OMF_alloc: familySelector = F_alloc; break;
2502 case OMF_copy: familySelector = F_copy; break;
2503 case OMF_mutableCopy: familySelector = F_mutableCopy; break;
2504 case OMF_new: familySelector = F_new; break;
2505 }
2506
2507 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
2508 ReasonSelector reasonSelector;
2509
2510 // The only reason these methods don't fall within their families is
2511 // due to unusual result types.
Alp Toker314cc812014-01-25 16:55:45 +00002512 if (unmatched->getReturnType()->isObjCObjectPointerType()) {
John McCall31168b02011-06-15 23:02:42 +00002513 reasonSelector = R_UnrelatedReturn;
2514 } else {
2515 reasonSelector = R_NonObjectReturn;
2516 }
2517
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00002518 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
2519 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
John McCall31168b02011-06-15 23:02:42 +00002520
2521 return true;
2522}
John McCall071df462010-10-28 02:34:38 +00002523
Fariborz Jahanian7988d7d2008-12-05 18:18:52 +00002524void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002525 ObjCMethodDecl *MethodDecl,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002526 bool IsProtocolMethodDecl) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002527 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002528 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
2529 return;
2530
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002531 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002532 IsProtocolMethodDecl, false,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002533 true);
Mike Stump11289f42009-09-09 15:08:12 +00002534
Chris Lattner67f35b02009-04-11 19:58:42 +00002535 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002536 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2537 EF = MethodDecl->param_end();
2538 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002539 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002540 IsProtocolMethodDecl, false, true);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002541 }
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002542
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002543 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002544 Diag(ImpMethodDecl->getLocation(),
2545 diag::warn_conflicting_variadic);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002546 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002547 }
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002548}
2549
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002550void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2551 ObjCMethodDecl *Overridden,
2552 bool IsProtocolMethodDecl) {
2553
2554 CheckMethodOverrideReturn(*this, Method, Overridden,
2555 IsProtocolMethodDecl, true,
2556 true);
2557
2558 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002559 IF = Overridden->param_begin(), EM = Method->param_end(),
2560 EF = Overridden->param_end();
2561 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002562 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
2563 IsProtocolMethodDecl, true, true);
2564 }
2565
2566 if (Method->isVariadic() != Overridden->isVariadic()) {
2567 Diag(Method->getLocation(),
2568 diag::warn_conflicting_overriding_variadic);
2569 Diag(Overridden->getLocation(), diag::note_previous_declaration);
2570 }
2571}
2572
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002573/// WarnExactTypedMethods - This routine issues a warning if method
2574/// implementation declaration matches exactly that of its declaration.
2575void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2576 ObjCMethodDecl *MethodDecl,
2577 bool IsProtocolMethodDecl) {
2578 // don't issue warning when protocol method is optional because primary
2579 // class is not required to implement it and it is safe for protocol
2580 // to implement it.
2581 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
2582 return;
2583 // don't issue warning when primary class's method is
2584 // depecated/unavailable.
2585 if (MethodDecl->hasAttr<UnavailableAttr>() ||
2586 MethodDecl->hasAttr<DeprecatedAttr>())
2587 return;
2588
2589 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2590 IsProtocolMethodDecl, false, false);
2591 if (match)
2592 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002593 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2594 EF = MethodDecl->param_end();
2595 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002596 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
2597 *IM, *IF,
2598 IsProtocolMethodDecl, false, false);
2599 if (!match)
2600 break;
2601 }
2602 if (match)
2603 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
David Chisnall92918512011-08-08 17:32:19 +00002604 if (match)
2605 match = !(MethodDecl->isClassMethod() &&
2606 MethodDecl->getSelector() == GetNullarySelector("load", Context));
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002607
2608 if (match) {
2609 Diag(ImpMethodDecl->getLocation(),
2610 diag::warn_category_method_impl_match);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002611 Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
2612 << MethodDecl->getDeclName();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002613 }
2614}
2615
Mike Stump87c57ac2009-05-16 07:39:55 +00002616/// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
2617/// improve the efficiency of selector lookups and type checking by associating
2618/// with each protocol / interface / category the flattened instance tables. If
2619/// we used an immutable set to keep the table then it wouldn't add significant
2620/// memory cost and it would be handy for lookups.
Daniel Dunbar4684f372008-08-27 05:40:03 +00002621
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002622typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
Ahmed Charlesaf94d562014-03-09 11:34:25 +00002623typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002624
2625static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
2626 ProtocolNameSet &PNS) {
2627 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
2628 PNS.insert(PDecl->getIdentifier());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002629 for (const auto *PI : PDecl->protocols())
2630 findProtocolsWithExplicitImpls(PI, PNS);
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002631}
2632
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002633/// Recursively populates a set with all conformed protocols in a class
2634/// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
2635/// attribute.
2636static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
2637 ProtocolNameSet &PNS) {
2638 if (!Super)
2639 return;
2640
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002641 for (const auto *I : Super->all_referenced_protocols())
2642 findProtocolsWithExplicitImpls(I, PNS);
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002643
2644 findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002645}
2646
Steve Naroffa36992242008-02-08 22:06:17 +00002647/// CheckProtocolMethodDefs - This routine checks unimplemented methods
Chris Lattnerda463fe2007-12-12 07:09:47 +00002648/// Declared in protocol, and those referenced by it.
Ted Kremenek285ee852013-12-13 06:26:10 +00002649static void CheckProtocolMethodDefs(Sema &S,
2650 SourceLocation ImpLoc,
2651 ObjCProtocolDecl *PDecl,
2652 bool& IncompleteImpl,
2653 const Sema::SelectorSet &InsMap,
2654 const Sema::SelectorSet &ClsMap,
Ted Kremenek33e430f2013-12-13 06:26:14 +00002655 ObjCContainerDecl *CDecl,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002656 LazyProtocolNameSet &ProtocolsExplictImpl) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002657 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
2658 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
2659 : dyn_cast<ObjCInterfaceDecl>(CDecl);
Fariborz Jahanian2e8074b2010-03-27 21:10:05 +00002660 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
2661
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002662 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
Craig Topperc3ec1492014-05-26 06:22:03 +00002663 ObjCInterfaceDecl *NSIDecl = nullptr;
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002664
2665 // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
2666 // then we should check if any class in the super class hierarchy also
2667 // conforms to this protocol, either directly or via protocol inheritance.
2668 // If so, we can skip checking this protocol completely because we
2669 // know that a parent class already satisfies this protocol.
2670 //
2671 // Note: we could generalize this logic for all protocols, and merely
2672 // add the limit on looking at the super class chain for just
2673 // specially marked protocols. This may be a good optimization. This
2674 // change is restricted to 'objc_protocol_requires_explicit_implementation'
2675 // protocols for now for controlled evaluation.
2676 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
Ahmed Charlesaf94d562014-03-09 11:34:25 +00002677 if (!ProtocolsExplictImpl) {
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002678 ProtocolsExplictImpl.reset(new ProtocolNameSet);
2679 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
2680 }
2681 if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
2682 ProtocolsExplictImpl->end())
2683 return;
2684
2685 // If no super class conforms to the protocol, we should not search
2686 // for methods in the super class to implicitly satisfy the protocol.
Craig Topperc3ec1492014-05-26 06:22:03 +00002687 Super = nullptr;
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002688 }
2689
Ted Kremenek285ee852013-12-13 06:26:10 +00002690 if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
Mike Stump11289f42009-09-09 15:08:12 +00002691 // check to see if class implements forwardInvocation method and objects
2692 // of this class are derived from 'NSProxy' so that to forward requests
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002693 // from one object to another.
Mike Stump11289f42009-09-09 15:08:12 +00002694 // Under such conditions, which means that every method possible is
2695 // implemented in the class, we should not issue "Method definition not
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002696 // found" warnings.
2697 // FIXME: Use a general GetUnarySelector method for this.
Ted Kremenek285ee852013-12-13 06:26:10 +00002698 IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
2699 Selector fISelector = S.Context.Selectors.getSelector(1, &II);
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002700 if (InsMap.count(fISelector))
2701 // Is IDecl derived from 'NSProxy'? If so, no instance methods
2702 // need be implemented in the implementation.
Ted Kremenek285ee852013-12-13 06:26:10 +00002703 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002704 }
Mike Stump11289f42009-09-09 15:08:12 +00002705
Fariborz Jahanianc41cf052013-01-07 19:21:03 +00002706 // If this is a forward protocol declaration, get its definition.
2707 if (!PDecl->isThisDeclarationADefinition() &&
2708 PDecl->getDefinition())
2709 PDecl = PDecl->getDefinition();
2710
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002711 // If a method lookup fails locally we still need to look and see if
2712 // the method was implemented by a base class or an inherited
2713 // protocol. This lookup is slow, but occurs rarely in correct code
2714 // and otherwise would terminate in a warning.
2715
Chris Lattnerda463fe2007-12-12 07:09:47 +00002716 // check unimplemented instance methods.
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002717 if (!NSIDecl)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002718 for (auto *method : PDecl->instance_methods()) {
Mike Stump11289f42009-09-09 15:08:12 +00002719 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
Jordan Rosed01e83a2012-10-10 16:42:25 +00002720 !method->isPropertyAccessor() &&
2721 !InsMap.count(method->getSelector()) &&
Ted Kremenek00781502013-11-23 01:01:29 +00002722 (!Super || !Super->lookupMethod(method->getSelector(),
2723 true /* instance */,
2724 false /* shallowCategory */,
Ted Kremenek28eace62013-11-23 01:01:34 +00002725 true /* followsSuper */,
Craig Topperc3ec1492014-05-26 06:22:03 +00002726 nullptr /* category */))) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002727 // If a method is not implemented in the category implementation but
2728 // has been declared in its primary class, superclass,
2729 // or in one of their protocols, no need to issue the warning.
2730 // This is because method will be implemented in the primary class
2731 // or one of its super class implementation.
2732
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002733 // Ugly, but necessary. Method declared in protocol might have
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002734 // have been synthesized due to a property declared in the class which
2735 // uses the protocol.
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002736 if (ObjCMethodDecl *MethodInClass =
Ted Kremenek00781502013-11-23 01:01:29 +00002737 IDecl->lookupMethod(method->getSelector(),
2738 true /* instance */,
2739 true /* shallowCategoryLookup */,
2740 false /* followSuper */))
Jordan Rosed01e83a2012-10-10 16:42:25 +00002741 if (C || MethodInClass->isPropertyAccessor())
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002742 continue;
2743 unsigned DIAG = diag::warn_unimplemented_protocol_method;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002744 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
Ted Kremenek285ee852013-12-13 06:26:10 +00002745 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002746 PDecl);
Fariborz Jahanian97752f72010-03-27 19:02:17 +00002747 }
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002748 }
2749 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002750 // check unimplemented class methods
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002751 for (auto *method : PDecl->class_methods()) {
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002752 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
2753 !ClsMap.count(method->getSelector()) &&
Ted Kremenek00781502013-11-23 01:01:29 +00002754 (!Super || !Super->lookupMethod(method->getSelector(),
2755 false /* class method */,
2756 false /* shallowCategoryLookup */,
Ted Kremenek28eace62013-11-23 01:01:34 +00002757 true /* followSuper */,
Craig Topperc3ec1492014-05-26 06:22:03 +00002758 nullptr /* category */))) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002759 // See above comment for instance method lookups.
Ted Kremenek00781502013-11-23 01:01:29 +00002760 if (C && IDecl->lookupMethod(method->getSelector(),
2761 false /* class */,
2762 true /* shallowCategoryLookup */,
2763 false /* followSuper */))
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002764 continue;
Ted Kremenek00781502013-11-23 01:01:29 +00002765
Fariborz Jahanianc1fb8622010-03-31 18:23:33 +00002766 unsigned DIAG = diag::warn_unimplemented_protocol_method;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002767 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
Ted Kremenek285ee852013-12-13 06:26:10 +00002768 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
Fariborz Jahanianc1fb8622010-03-31 18:23:33 +00002769 }
Fariborz Jahanian97752f72010-03-27 19:02:17 +00002770 }
Steve Naroff3ce37a62007-12-14 23:37:57 +00002771 }
Chris Lattner390d39a2008-07-21 21:32:27 +00002772 // Check on this protocols's referenced protocols, recursively.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002773 for (auto *PI : PDecl->protocols())
2774 CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002775 CDecl, ProtocolsExplictImpl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002776}
2777
Fariborz Jahanianf9ae68a2011-07-16 00:08:33 +00002778/// MatchAllMethodDeclarations - Check methods declared in interface
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002779/// or protocol against those declared in their implementations.
2780///
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002781void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
2782 const SelectorSet &ClsMap,
2783 SelectorSet &InsMapSeen,
2784 SelectorSet &ClsMapSeen,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002785 ObjCImplDecl* IMPDecl,
2786 ObjCContainerDecl* CDecl,
2787 bool &IncompleteImpl,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002788 bool ImmediateClass,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002789 bool WarnCategoryMethodImpl) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002790 // Check and see if instance methods in class interface have been
2791 // implemented in the implementation class. If so, their types match.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002792 for (auto *I : CDecl->instance_methods()) {
David Blaikie82e95a32014-11-19 07:49:47 +00002793 if (!InsMapSeen.insert(I->getSelector()).second)
Benjamin Kramer9f8e2d72013-10-14 15:16:10 +00002794 continue;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002795 if (!I->isPropertyAccessor() &&
2796 !InsMap.count(I->getSelector())) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002797 if (ImmediateClass)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002798 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
Ted Kremenek65d63572013-03-27 00:02:21 +00002799 diag::warn_undef_method_impl);
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002800 continue;
Mike Stump12b8ce12009-08-04 21:02:39 +00002801 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002802 ObjCMethodDecl *ImpMethodDecl =
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002803 IMPDecl->getInstanceMethod(I->getSelector());
Manman Rena58f92f2016-10-11 21:18:20 +00002804 assert(CDecl->getInstanceMethod(I->getSelector(), true/*AllowHidden*/) &&
Argyrios Kyrtzidis342e08f2011-08-30 19:43:21 +00002805 "Expected to find the method through lookup as well");
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002806 // ImpMethodDecl may be null as in a @dynamic property.
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002807 if (ImpMethodDecl) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002808 if (!WarnCategoryMethodImpl)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002809 WarnConflictingTypedMethods(ImpMethodDecl, I,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002810 isa<ObjCProtocolDecl>(CDecl));
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002811 else if (!I->isPropertyAccessor())
2812 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002813 }
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002814 }
2815 }
Mike Stump11289f42009-09-09 15:08:12 +00002816
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002817 // Check and see if class methods in class interface have been
2818 // implemented in the implementation class. If so, their types match.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002819 for (auto *I : CDecl->class_methods()) {
David Blaikie82e95a32014-11-19 07:49:47 +00002820 if (!ClsMapSeen.insert(I->getSelector()).second)
Benjamin Kramer9f8e2d72013-10-14 15:16:10 +00002821 continue;
Manman Rend36f7d52016-01-27 20:10:32 +00002822 if (!I->isPropertyAccessor() &&
2823 !ClsMap.count(I->getSelector())) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002824 if (ImmediateClass)
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002825 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
Ted Kremenek65d63572013-03-27 00:02:21 +00002826 diag::warn_undef_method_impl);
Mike Stump12b8ce12009-08-04 21:02:39 +00002827 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002828 ObjCMethodDecl *ImpMethodDecl =
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002829 IMPDecl->getClassMethod(I->getSelector());
Manman Rena58f92f2016-10-11 21:18:20 +00002830 assert(CDecl->getClassMethod(I->getSelector(), true/*AllowHidden*/) &&
Argyrios Kyrtzidis342e08f2011-08-30 19:43:21 +00002831 "Expected to find the method through lookup as well");
Manman Rend36f7d52016-01-27 20:10:32 +00002832 // ImpMethodDecl may be null as in a @dynamic property.
2833 if (ImpMethodDecl) {
2834 if (!WarnCategoryMethodImpl)
2835 WarnConflictingTypedMethods(ImpMethodDecl, I,
2836 isa<ObjCProtocolDecl>(CDecl));
2837 else if (!I->isPropertyAccessor())
2838 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2839 }
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002840 }
2841 }
Fariborz Jahanian73853e52010-10-08 22:59:25 +00002842
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002843 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
2844 // Also, check for methods declared in protocols inherited by
2845 // this protocol.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002846 for (auto *PI : PD->protocols())
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002847 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002848 IMPDecl, PI, IncompleteImpl, false,
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002849 WarnCategoryMethodImpl);
2850 }
2851
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002852 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002853 // when checking that methods in implementation match their declaration,
2854 // i.e. when WarnCategoryMethodImpl is false, check declarations in class
2855 // extension; as well as those in categories.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002856 if (!WarnCategoryMethodImpl) {
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002857 for (auto *Cat : I->visible_categories())
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002858 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Argyrios Kyrtzidis3a437542015-10-13 23:27:34 +00002859 IMPDecl, Cat, IncompleteImpl,
2860 ImmediateClass && Cat->IsClassExtension(),
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002861 WarnCategoryMethodImpl);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002862 } else {
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002863 // Also methods in class extensions need be looked at next.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002864 for (auto *Ext : I->visible_extensions())
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002865 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002866 IMPDecl, Ext, IncompleteImpl, false,
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002867 WarnCategoryMethodImpl);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002868 }
2869
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002870 // Check for any implementation of a methods declared in protocol.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002871 for (auto *PI : I->all_referenced_protocols())
Mike Stump11289f42009-09-09 15:08:12 +00002872 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002873 IMPDecl, PI, IncompleteImpl, false,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002874 WarnCategoryMethodImpl);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002875
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002876 // FIXME. For now, we are not checking for extact match of methods
2877 // in category implementation and its primary class's super class.
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002878 if (!WarnCategoryMethodImpl && I->getSuperClass())
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002879 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Mike Stump11289f42009-09-09 15:08:12 +00002880 IMPDecl,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002881 I->getSuperClass(), IncompleteImpl, false);
2882 }
2883}
2884
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002885/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2886/// category matches with those implemented in its primary class and
2887/// warns each time an exact match is found.
2888void Sema::CheckCategoryVsClassMethodMatches(
2889 ObjCCategoryImplDecl *CatIMPDecl) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002890 // Get category's primary class.
2891 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
2892 if (!CatDecl)
2893 return;
2894 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
2895 if (!IDecl)
2896 return;
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002897 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
2898 SelectorSet InsMap, ClsMap;
2899
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002900 for (const auto *I : CatIMPDecl->instance_methods()) {
2901 Selector Sel = I->getSelector();
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002902 // When checking for methods implemented in the category, skip over
2903 // those declared in category class's super class. This is because
2904 // the super class must implement the method.
2905 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
2906 continue;
2907 InsMap.insert(Sel);
2908 }
2909
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002910 for (const auto *I : CatIMPDecl->class_methods()) {
2911 Selector Sel = I->getSelector();
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002912 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
2913 continue;
2914 ClsMap.insert(Sel);
2915 }
2916 if (InsMap.empty() && ClsMap.empty())
2917 return;
2918
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002919 SelectorSet InsMapSeen, ClsMapSeen;
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002920 bool IncompleteImpl = false;
2921 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2922 CatIMPDecl, IDecl,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002923 IncompleteImpl, false,
2924 true /*WarnCategoryMethodImpl*/);
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002925}
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002926
Fariborz Jahanian25491a22010-05-05 21:52:17 +00002927void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002928 ObjCContainerDecl* CDecl,
Chris Lattner9ef10f42009-03-01 00:56:52 +00002929 bool IncompleteImpl) {
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002930 SelectorSet InsMap;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002931 // Check and see if instance methods in class interface have been
2932 // implemented in the implementation class.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002933 for (const auto *I : IMPDecl->instance_methods())
2934 InsMap.insert(I->getSelector());
Mike Stump11289f42009-09-09 15:08:12 +00002935
Douglas Gregoracf4fd32015-11-03 01:15:46 +00002936 // Add the selectors for getters/setters of @dynamic properties.
2937 for (const auto *PImpl : IMPDecl->property_impls()) {
2938 // We only care about @dynamic implementations.
2939 if (PImpl->getPropertyImplementation() != ObjCPropertyImplDecl::Dynamic)
2940 continue;
2941
2942 const auto *P = PImpl->getPropertyDecl();
2943 if (!P) continue;
2944
2945 InsMap.insert(P->getGetterName());
2946 if (!P->getSetterName().isNull())
2947 InsMap.insert(P->getSetterName());
2948 }
2949
Fariborz Jahanian6c6aea92009-04-14 23:15:21 +00002950 // Check and see if properties declared in the interface have either 1)
2951 // an implementation or 2) there is a @synthesize/@dynamic implementation
2952 // of the property in the @implementation.
Ted Kremenek348e88c2014-02-21 19:41:34 +00002953 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2954 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
2955 LangOpts.ObjCRuntime.isNonFragile() &&
2956 !IDecl->isObjCRequiresPropertyDefs();
2957 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
2958 }
2959
Douglas Gregor849ebc22015-06-19 18:14:46 +00002960 // Diagnose null-resettable synthesized setters.
2961 diagnoseNullResettableSynthesizedSetters(IMPDecl);
2962
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002963 SelectorSet ClsMap;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002964 for (const auto *I : IMPDecl->class_methods())
2965 ClsMap.insert(I->getSelector());
Mike Stump11289f42009-09-09 15:08:12 +00002966
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002967 // Check for type conflict of methods declared in a class/protocol and
2968 // its implementation; if any.
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002969 SelectorSet InsMapSeen, ClsMapSeen;
Mike Stump11289f42009-09-09 15:08:12 +00002970 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2971 IMPDecl, CDecl,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002972 IncompleteImpl, true);
Fariborz Jahanian2bda1b62011-08-03 18:21:12 +00002973
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002974 // check all methods implemented in category against those declared
2975 // in its primary class.
2976 if (ObjCCategoryImplDecl *CatDecl =
2977 dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
2978 CheckCategoryVsClassMethodMatches(CatDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002979
Chris Lattnerda463fe2007-12-12 07:09:47 +00002980 // Check the protocol list for unimplemented methods in the @implementation
2981 // class.
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002982 // Check and see if class methods in class interface have been
2983 // implemented in the implementation class.
Mike Stump11289f42009-09-09 15:08:12 +00002984
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002985 LazyProtocolNameSet ExplicitImplProtocols;
2986
Chris Lattner9ef10f42009-03-01 00:56:52 +00002987 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002988 for (auto *PI : I->all_referenced_protocols())
2989 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl,
2990 InsMap, ClsMap, I, ExplicitImplProtocols);
Chris Lattner9ef10f42009-03-01 00:56:52 +00002991 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahanian8764c742009-10-05 21:32:49 +00002992 // For extended class, unimplemented methods in its protocols will
2993 // be reported in the primary class.
Fariborz Jahanian30a42922010-02-15 21:55:26 +00002994 if (!C->IsClassExtension()) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002995 for (auto *P : C->protocols())
2996 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002997 IncompleteImpl, InsMap, ClsMap, CDecl,
2998 ExplicitImplProtocols);
Ted Kremenek348e88c2014-02-21 19:41:34 +00002999 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
Nico Weber2e0c8f72014-12-27 03:58:08 +00003000 /*SynthesizeProperties=*/false);
Fariborz Jahanian4f8a5712010-01-20 19:36:21 +00003001 }
Chris Lattner9ef10f42009-03-01 00:56:52 +00003002 } else
David Blaikie83d382b2011-09-23 05:06:16 +00003003 llvm_unreachable("invalid ObjCContainerDecl type.");
Chris Lattnerda463fe2007-12-12 07:09:47 +00003004}
3005
Fariborz Jahanian3a039e32011-08-27 20:50:59 +00003006Sema::DeclGroupPtrTy
Chris Lattnerda463fe2007-12-12 07:09:47 +00003007Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
Chris Lattner99a83312009-02-16 19:25:52 +00003008 IdentifierInfo **IdentList,
Ted Kremeneka26da852009-11-17 23:12:20 +00003009 SourceLocation *IdentLocs,
Douglas Gregor85f3f952015-07-07 03:57:15 +00003010 ArrayRef<ObjCTypeParamList *> TypeParamLists,
Chris Lattner99a83312009-02-16 19:25:52 +00003011 unsigned NumElts) {
Fariborz Jahanian3a039e32011-08-27 20:50:59 +00003012 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003013 for (unsigned i = 0; i != NumElts; ++i) {
3014 // Check for another declaration kind with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00003015 NamedDecl *PrevDecl
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003016 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
Richard Smithbecb92d2017-10-10 22:33:17 +00003017 LookupOrdinaryName, forRedeclarationInCurContext());
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003018 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Steve Naroff946166f2008-06-05 22:57:10 +00003019 // GCC apparently allows the following idiom:
3020 //
3021 // typedef NSObject < XCElementTogglerP > XCElementToggler;
3022 // @class XCElementToggler;
3023 //
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003024 // Here we have chosen to ignore the forward class declaration
3025 // with a warning. Since this is the implied behavior.
Richard Smithdda56e42011-04-15 14:24:37 +00003026 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
John McCall8b07ec22010-05-15 11:32:37 +00003027 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003028 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
Chris Lattner0369c572008-11-23 23:12:31 +00003029 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall8b07ec22010-05-15 11:32:37 +00003030 } else {
Mike Stump12b8ce12009-08-04 21:02:39 +00003031 // a forward class declaration matching a typedef name of a class refers
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003032 // to the underlying class. Just ignore the forward class with a warning
Nico Weber2e0c8f72014-12-27 03:58:08 +00003033 // as this will force the intended behavior which is to lookup the
3034 // typedef name.
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003035 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003036 Diag(AtClassLoc, diag::warn_forward_class_redefinition)
3037 << IdentList[i];
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003038 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3039 continue;
3040 }
Fariborz Jahanian0d451812009-05-07 21:49:26 +00003041 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003042 }
Douglas Gregordc9166c2011-12-15 20:29:51 +00003043
3044 // Create a declaration to describe this forward declaration.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003045 ObjCInterfaceDecl *PrevIDecl
3046 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidisdd710632013-06-18 21:26:33 +00003047
3048 IdentifierInfo *ClassName = IdentList[i];
3049 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
3050 // A previous decl with a different name is because of
3051 // @compatibility_alias, for example:
3052 // \code
3053 // @class NewImage;
3054 // @compatibility_alias OldImage NewImage;
3055 // \endcode
3056 // A lookup for 'OldImage' will return the 'NewImage' decl.
3057 //
3058 // In such a case use the real declaration name, instead of the alias one,
3059 // otherwise we will break IdentifierResolver and redecls-chain invariants.
3060 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
3061 // has been aliased.
3062 ClassName = PrevIDecl->getIdentifier();
3063 }
3064
Douglas Gregor85f3f952015-07-07 03:57:15 +00003065 // If this forward declaration has type parameters, compare them with the
3066 // type parameters of the previous declaration.
3067 ObjCTypeParamList *TypeParams = TypeParamLists[i];
3068 if (PrevIDecl && TypeParams) {
3069 if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) {
3070 // Check for consistency with the previous declaration.
3071 if (checkTypeParamListConsistency(
3072 *this, PrevTypeParams, TypeParams,
3073 TypeParamListContext::ForwardDeclaration)) {
3074 TypeParams = nullptr;
3075 }
3076 } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
3077 // The @interface does not have type parameters. Complain.
3078 Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class)
3079 << ClassName
3080 << TypeParams->getSourceRange();
3081 Diag(Def->getLocation(), diag::note_defined_here)
3082 << ClassName;
3083
3084 TypeParams = nullptr;
3085 }
3086 }
3087
Douglas Gregordc9166c2011-12-15 20:29:51 +00003088 ObjCInterfaceDecl *IDecl
3089 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00003090 ClassName, TypeParams, PrevIDecl,
3091 IdentLocs[i]);
Douglas Gregordc9166c2011-12-15 20:29:51 +00003092 IDecl->setAtEndRange(IdentLocs[i]);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003093
Douglas Gregordc9166c2011-12-15 20:29:51 +00003094 PushOnScopeChains(IDecl, TUScope);
Douglas Gregordeafd0b2011-12-27 22:43:10 +00003095 CheckObjCDeclScope(IDecl);
3096 DeclsInGroup.push_back(IDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003097 }
Rafael Espindolaab417692013-07-09 12:05:01 +00003098
Richard Smith3beb7c62017-01-12 02:27:38 +00003099 return BuildDeclaratorGroup(DeclsInGroup);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003100}
3101
John McCall54507ab2011-06-16 01:15:19 +00003102static bool tryMatchRecordTypes(ASTContext &Context,
3103 Sema::MethodMatchStrategy strategy,
3104 const Type *left, const Type *right);
3105
John McCall31168b02011-06-15 23:02:42 +00003106static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
3107 QualType leftQT, QualType rightQT) {
3108 const Type *left =
3109 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
3110 const Type *right =
3111 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
3112
3113 if (left == right) return true;
3114
3115 // If we're doing a strict match, the types have to match exactly.
3116 if (strategy == Sema::MMS_strict) return false;
3117
3118 if (left->isIncompleteType() || right->isIncompleteType()) return false;
3119
3120 // Otherwise, use this absurdly complicated algorithm to try to
3121 // validate the basic, low-level compatibility of the two types.
3122
3123 // As a minimum, require the sizes and alignments to match.
David Majnemer34b57492014-07-30 01:30:47 +00003124 TypeInfo LeftTI = Context.getTypeInfo(left);
3125 TypeInfo RightTI = Context.getTypeInfo(right);
3126 if (LeftTI.Width != RightTI.Width)
3127 return false;
3128
3129 if (LeftTI.Align != RightTI.Align)
John McCall31168b02011-06-15 23:02:42 +00003130 return false;
3131
3132 // Consider all the kinds of non-dependent canonical types:
3133 // - functions and arrays aren't possible as return and parameter types
3134
3135 // - vector types of equal size can be arbitrarily mixed
3136 if (isa<VectorType>(left)) return isa<VectorType>(right);
3137 if (isa<VectorType>(right)) return false;
3138
3139 // - references should only match references of identical type
John McCall54507ab2011-06-16 01:15:19 +00003140 // - structs, unions, and Objective-C objects must match more-or-less
3141 // exactly
John McCall31168b02011-06-15 23:02:42 +00003142 // - everything else should be a scalar
3143 if (!left->isScalarType() || !right->isScalarType())
John McCall54507ab2011-06-16 01:15:19 +00003144 return tryMatchRecordTypes(Context, strategy, left, right);
John McCall31168b02011-06-15 23:02:42 +00003145
John McCall9320b872011-09-09 05:25:32 +00003146 // Make scalars agree in kind, except count bools as chars, and group
3147 // all non-member pointers together.
John McCall31168b02011-06-15 23:02:42 +00003148 Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
3149 Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
3150 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
3151 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
John McCall9320b872011-09-09 05:25:32 +00003152 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
3153 leftSK = Type::STK_ObjCObjectPointer;
3154 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
3155 rightSK = Type::STK_ObjCObjectPointer;
John McCall31168b02011-06-15 23:02:42 +00003156
3157 // Note that data member pointers and function member pointers don't
3158 // intermix because of the size differences.
3159
3160 return (leftSK == rightSK);
3161}
Chris Lattnerda463fe2007-12-12 07:09:47 +00003162
John McCall54507ab2011-06-16 01:15:19 +00003163static bool tryMatchRecordTypes(ASTContext &Context,
3164 Sema::MethodMatchStrategy strategy,
3165 const Type *lt, const Type *rt) {
3166 assert(lt && rt && lt != rt);
3167
3168 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
3169 RecordDecl *left = cast<RecordType>(lt)->getDecl();
3170 RecordDecl *right = cast<RecordType>(rt)->getDecl();
3171
3172 // Require union-hood to match.
3173 if (left->isUnion() != right->isUnion()) return false;
3174
3175 // Require an exact match if either is non-POD.
3176 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
3177 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
3178 return false;
3179
3180 // Require size and alignment to match.
David Majnemer34b57492014-07-30 01:30:47 +00003181 TypeInfo LeftTI = Context.getTypeInfo(lt);
3182 TypeInfo RightTI = Context.getTypeInfo(rt);
3183 if (LeftTI.Width != RightTI.Width)
3184 return false;
3185
3186 if (LeftTI.Align != RightTI.Align)
3187 return false;
John McCall54507ab2011-06-16 01:15:19 +00003188
3189 // Require fields to match.
3190 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
3191 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
3192 for (; li != le && ri != re; ++li, ++ri) {
3193 if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
3194 return false;
3195 }
3196 return (li == le && ri == re);
3197}
3198
Chris Lattnerda463fe2007-12-12 07:09:47 +00003199/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
3200/// returns true, or false, accordingly.
3201/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
John McCall31168b02011-06-15 23:02:42 +00003202bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
3203 const ObjCMethodDecl *right,
3204 MethodMatchStrategy strategy) {
Alp Toker314cc812014-01-25 16:55:45 +00003205 if (!matchTypes(Context, strategy, left->getReturnType(),
3206 right->getReturnType()))
John McCall31168b02011-06-15 23:02:42 +00003207 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003208
Douglas Gregor560b7fa2013-02-07 19:13:24 +00003209 // If either is hidden, it is not considered to match.
3210 if (left->isHidden() || right->isHidden())
3211 return false;
3212
David Blaikiebbafb8a2012-03-11 07:00:24 +00003213 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003214 (left->hasAttr<NSReturnsRetainedAttr>()
3215 != right->hasAttr<NSReturnsRetainedAttr>() ||
3216 left->hasAttr<NSConsumesSelfAttr>()
3217 != right->hasAttr<NSConsumesSelfAttr>()))
3218 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003219
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00003220 ObjCMethodDecl::param_const_iterator
Douglas Gregor0bf70f42012-05-17 23:13:29 +00003221 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
3222 re = right->param_end();
Mike Stump11289f42009-09-09 15:08:12 +00003223
Douglas Gregor0bf70f42012-05-17 23:13:29 +00003224 for (; li != le && ri != re; ++li, ++ri) {
John McCall31168b02011-06-15 23:02:42 +00003225 assert(ri != right->param_end() && "Param mismatch");
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00003226 const ParmVarDecl *lparm = *li, *rparm = *ri;
John McCall31168b02011-06-15 23:02:42 +00003227
3228 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
3229 return false;
3230
David Blaikiebbafb8a2012-03-11 07:00:24 +00003231 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003232 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
3233 return false;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003234 }
3235 return true;
3236}
3237
Manman Ren71224532016-04-09 18:59:48 +00003238static bool isMethodContextSameForKindofLookup(ObjCMethodDecl *Method,
3239 ObjCMethodDecl *MethodInList) {
3240 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3241 auto *MethodInListProtocol =
3242 dyn_cast<ObjCProtocolDecl>(MethodInList->getDeclContext());
3243 // If this method belongs to a protocol but the method in list does not, or
3244 // vice versa, we say the context is not the same.
3245 if ((MethodProtocol && !MethodInListProtocol) ||
3246 (!MethodProtocol && MethodInListProtocol))
3247 return false;
3248
3249 if (MethodProtocol && MethodInListProtocol)
3250 return true;
3251
3252 ObjCInterfaceDecl *MethodInterface = Method->getClassInterface();
3253 ObjCInterfaceDecl *MethodInListInterface =
3254 MethodInList->getClassInterface();
3255 return MethodInterface == MethodInListInterface;
3256}
3257
Nico Weber2e0c8f72014-12-27 03:58:08 +00003258void Sema::addMethodToGlobalList(ObjCMethodList *List,
3259 ObjCMethodDecl *Method) {
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003260 // Record at the head of the list whether there were 0, 1, or >= 2 methods
3261 // inside categories.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003262 if (ObjCCategoryDecl *CD =
3263 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
Argyrios Kyrtzidis04703a62013-04-27 00:10:12 +00003264 if (!CD->IsClassExtension() && List->getBits() < 2)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003265 List->setBits(List->getBits() + 1);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003266
Douglas Gregorc454afe2012-01-25 00:19:56 +00003267 // If the list is empty, make it a singleton list.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003268 if (List->getMethod() == nullptr) {
3269 List->setMethod(Method);
Craig Topperc3ec1492014-05-26 06:22:03 +00003270 List->setNext(nullptr);
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003271 return;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003272 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003273
Douglas Gregorc454afe2012-01-25 00:19:56 +00003274 // We've seen a method with this name, see if we have already seen this type
3275 // signature.
3276 ObjCMethodList *Previous = List;
Manman Ren051d0b62016-04-13 23:43:56 +00003277 ObjCMethodList *ListWithSameDeclaration = nullptr;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003278 for (; List; Previous = List, List = List->getNext()) {
Douglas Gregor600a2f52013-06-21 00:20:25 +00003279 // If we are building a module, keep all of the methods.
Richard Smithbbcc9f02016-08-26 00:14:38 +00003280 if (getLangOpts().isCompilingModule())
Douglas Gregor600a2f52013-06-21 00:20:25 +00003281 continue;
3282
Manman Ren051d0b62016-04-13 23:43:56 +00003283 bool SameDeclaration = MatchTwoMethodDeclarations(Method,
3284 List->getMethod());
Manman Ren71224532016-04-09 18:59:48 +00003285 // Looking for method with a type bound requires the correct context exists.
Manman Ren051d0b62016-04-13 23:43:56 +00003286 // We need to insert a method into the list if the context is different.
3287 // If the method's declaration matches the list
3288 // a> the method belongs to a different context: we need to insert it, in
3289 // order to emit the availability message, we need to prioritize over
3290 // availability among the methods with the same declaration.
3291 // b> the method belongs to the same context: there is no need to insert a
3292 // new entry.
3293 // If the method's declaration does not match the list, we insert it to the
3294 // end.
3295 if (!SameDeclaration ||
Manman Ren71224532016-04-09 18:59:48 +00003296 !isMethodContextSameForKindofLookup(Method, List->getMethod())) {
Fariborz Jahaniand436b2a2015-04-07 16:56:27 +00003297 // Even if two method types do not match, we would like to say
3298 // there is more than one declaration so unavailability/deprecated
3299 // warning is not too noisy.
3300 if (!Method->isDefined())
3301 List->setHasMoreThanOneDecl(true);
Manman Ren051d0b62016-04-13 23:43:56 +00003302
3303 // For methods with the same declaration, the one that is deprecated
3304 // should be put in the front for better diagnostics.
3305 if (Method->isDeprecated() && SameDeclaration &&
3306 !ListWithSameDeclaration && !List->getMethod()->isDeprecated())
3307 ListWithSameDeclaration = List;
3308
3309 if (Method->isUnavailable() && SameDeclaration &&
3310 !ListWithSameDeclaration &&
3311 List->getMethod()->getAvailability() < AR_Deprecated)
3312 ListWithSameDeclaration = List;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003313 continue;
Fariborz Jahaniand436b2a2015-04-07 16:56:27 +00003314 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003315
3316 ObjCMethodDecl *PrevObjCMethod = List->getMethod();
Douglas Gregorc454afe2012-01-25 00:19:56 +00003317
3318 // Propagate the 'defined' bit.
3319 if (Method->isDefined())
3320 PrevObjCMethod->setDefined(true);
Nico Webere3b11042014-12-27 07:09:37 +00003321 else {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003322 // Objective-C doesn't allow an @interface for a class after its
3323 // @implementation. So if Method is not defined and there already is
3324 // an entry for this type signature, Method has to be for a different
3325 // class than PrevObjCMethod.
3326 List->setHasMoreThanOneDecl(true);
3327 }
3328
Douglas Gregorc454afe2012-01-25 00:19:56 +00003329 // If a method is deprecated, push it in the global pool.
3330 // This is used for better diagnostics.
3331 if (Method->isDeprecated()) {
3332 if (!PrevObjCMethod->isDeprecated())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003333 List->setMethod(Method);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003334 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003335 // If the new method is unavailable, push it into global pool
Douglas Gregorc454afe2012-01-25 00:19:56 +00003336 // unless previous one is deprecated.
3337 if (Method->isUnavailable()) {
3338 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003339 List->setMethod(Method);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003340 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003341
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003342 return;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003343 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003344
Douglas Gregorc454afe2012-01-25 00:19:56 +00003345 // We have a new signature for an existing method - add it.
3346 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
Douglas Gregore1716012012-01-25 00:49:42 +00003347 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
Manman Ren71224532016-04-09 18:59:48 +00003348
Manman Ren051d0b62016-04-13 23:43:56 +00003349 // We insert it right before ListWithSameDeclaration.
3350 if (ListWithSameDeclaration) {
3351 auto *List = new (Mem) ObjCMethodList(*ListWithSameDeclaration);
3352 // FIXME: should we clear the other bits in ListWithSameDeclaration?
3353 ListWithSameDeclaration->setMethod(Method);
3354 ListWithSameDeclaration->setNext(List);
Manman Ren71224532016-04-09 18:59:48 +00003355 return;
3356 }
3357
Nico Weber2e0c8f72014-12-27 03:58:08 +00003358 Previous->setNext(new (Mem) ObjCMethodList(Method));
Douglas Gregorc454afe2012-01-25 00:19:56 +00003359}
3360
Sebastian Redl75d8a322010-08-02 23:18:59 +00003361/// \brief Read the contents of the method pool for a given selector from
3362/// external storage.
Douglas Gregore1716012012-01-25 00:49:42 +00003363void Sema::ReadMethodPool(Selector Sel) {
Douglas Gregorc78d3462009-04-24 21:10:55 +00003364 assert(ExternalSource && "We need an external AST source");
Douglas Gregore1716012012-01-25 00:49:42 +00003365 ExternalSource->ReadMethodPool(Sel);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003366}
3367
Manman Rena0f31a02016-04-29 19:04:05 +00003368void Sema::updateOutOfDateSelector(Selector Sel) {
3369 if (!ExternalSource)
3370 return;
3371 ExternalSource->updateOutOfDateSelector(Sel);
3372}
3373
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003374void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
Sebastian Redl75d8a322010-08-02 23:18:59 +00003375 bool instance) {
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00003376 // Ignore methods of invalid containers.
3377 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003378 return;
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00003379
Douglas Gregor70f449b2012-01-25 00:59:09 +00003380 if (ExternalSource)
3381 ReadMethodPool(Method->getSelector());
3382
Sebastian Redl75d8a322010-08-02 23:18:59 +00003383 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
Douglas Gregor70f449b2012-01-25 00:59:09 +00003384 if (Pos == MethodPool.end())
3385 Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
3386 GlobalMethods())).first;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003387
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003388 Method->setDefined(impl);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003389
Sebastian Redl75d8a322010-08-02 23:18:59 +00003390 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003391 addMethodToGlobalList(&Entry, Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003392}
3393
John McCall31168b02011-06-15 23:02:42 +00003394/// Determines if this is an "acceptable" loose mismatch in the global
3395/// method pool. This exists mostly as a hack to get around certain
3396/// global mismatches which we can't afford to make warnings / errors.
3397/// Really, what we want is a way to take a method out of the global
3398/// method pool.
3399static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
3400 ObjCMethodDecl *other) {
3401 if (!chosen->isInstanceMethod())
3402 return false;
3403
3404 Selector sel = chosen->getSelector();
3405 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
3406 return false;
3407
3408 // Don't complain about mismatches for -length if the method we
3409 // chose has an integral result type.
Alp Toker314cc812014-01-25 16:55:45 +00003410 return (chosen->getReturnType()->isIntegerType());
John McCall31168b02011-06-15 23:02:42 +00003411}
3412
Manman Ren7ed4f982016-04-07 19:32:24 +00003413/// Return true if the given method is wthin the type bound.
3414static bool FilterMethodsByTypeBound(ObjCMethodDecl *Method,
3415 const ObjCObjectType *TypeBound) {
3416 if (!TypeBound)
3417 return true;
3418
3419 if (TypeBound->isObjCId())
3420 // FIXME: should we handle the case of bounding to id<A, B> differently?
3421 return true;
3422
3423 auto *BoundInterface = TypeBound->getInterface();
3424 assert(BoundInterface && "unexpected object type!");
3425
3426 // Check if the Method belongs to a protocol. We should allow any method
3427 // defined in any protocol, because any subclass could adopt the protocol.
3428 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3429 if (MethodProtocol) {
3430 return true;
3431 }
3432
3433 // If the Method belongs to a class, check if it belongs to the class
3434 // hierarchy of the class bound.
3435 if (ObjCInterfaceDecl *MethodInterface = Method->getClassInterface()) {
3436 // We allow methods declared within classes that are part of the hierarchy
3437 // of the class bound (superclass of, subclass of, or the same as the class
3438 // bound).
3439 return MethodInterface == BoundInterface ||
3440 MethodInterface->isSuperClassOf(BoundInterface) ||
3441 BoundInterface->isSuperClassOf(MethodInterface);
3442 }
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003443 llvm_unreachable("unknown method context");
Manman Ren7ed4f982016-04-07 19:32:24 +00003444}
3445
Manman Rend2a3cd72016-04-07 19:30:20 +00003446/// We first select the type of the method: Instance or Factory, then collect
3447/// all methods with that type.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003448bool Sema::CollectMultipleMethodsInGlobalPool(
Manman Rend2a3cd72016-04-07 19:30:20 +00003449 Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods,
Manman Ren7ed4f982016-04-07 19:32:24 +00003450 bool InstanceFirst, bool CheckTheOther,
3451 const ObjCObjectType *TypeBound) {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003452 if (ExternalSource)
3453 ReadMethodPool(Sel);
3454
3455 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3456 if (Pos == MethodPool.end())
3457 return false;
Manman Rend2a3cd72016-04-07 19:30:20 +00003458
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003459 // Gather the non-hidden methods.
Manman Rend2a3cd72016-04-07 19:30:20 +00003460 ObjCMethodList &MethList = InstanceFirst ? Pos->second.first :
3461 Pos->second.second;
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003462 for (ObjCMethodList *M = &MethList; M; M = M->getNext())
Manman Ren7ed4f982016-04-07 19:32:24 +00003463 if (M->getMethod() && !M->getMethod()->isHidden()) {
3464 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3465 Methods.push_back(M->getMethod());
3466 }
Manman Rend2a3cd72016-04-07 19:30:20 +00003467
3468 // Return if we find any method with the desired kind.
3469 if (!Methods.empty())
3470 return Methods.size() > 1;
3471
3472 if (!CheckTheOther)
3473 return false;
3474
3475 // Gather the other kind.
3476 ObjCMethodList &MethList2 = InstanceFirst ? Pos->second.second :
3477 Pos->second.first;
3478 for (ObjCMethodList *M = &MethList2; M; M = M->getNext())
Manman Ren7ed4f982016-04-07 19:32:24 +00003479 if (M->getMethod() && !M->getMethod()->isHidden()) {
3480 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3481 Methods.push_back(M->getMethod());
3482 }
Manman Rend2a3cd72016-04-07 19:30:20 +00003483
Nico Weber2e0c8f72014-12-27 03:58:08 +00003484 return Methods.size() > 1;
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003485}
3486
Manman Rend2a3cd72016-04-07 19:30:20 +00003487bool Sema::AreMultipleMethodsInGlobalPool(
3488 Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R,
3489 bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl *> &Methods) {
3490 // Diagnose finding more than one method in global pool.
3491 SmallVector<ObjCMethodDecl *, 4> FilteredMethods;
3492 FilteredMethods.push_back(BestMethod);
3493
3494 for (auto *M : Methods)
3495 if (M != BestMethod && !M->hasAttr<UnavailableAttr>())
3496 FilteredMethods.push_back(M);
3497
3498 if (FilteredMethods.size() > 1)
3499 DiagnoseMultipleMethodInGlobalPool(FilteredMethods, Sel, R,
3500 receiverIdOrClass);
3501
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003502 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
Nico Weber2e0c8f72014-12-27 03:58:08 +00003503 // Test for no method in the pool which should not trigger any warning by
3504 // caller.
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003505 if (Pos == MethodPool.end())
3506 return true;
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003507 ObjCMethodList &MethList =
3508 BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003509 return MethList.hasMoreThanOneDecl();
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003510}
3511
Sebastian Redl75d8a322010-08-02 23:18:59 +00003512ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00003513 bool receiverIdOrClass,
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003514 bool instance) {
Douglas Gregor70f449b2012-01-25 00:59:09 +00003515 if (ExternalSource)
3516 ReadMethodPool(Sel);
3517
Sebastian Redl75d8a322010-08-02 23:18:59 +00003518 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
Douglas Gregor70f449b2012-01-25 00:59:09 +00003519 if (Pos == MethodPool.end())
Craig Topperc3ec1492014-05-26 06:22:03 +00003520 return nullptr;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003521
Douglas Gregor77f49a42013-01-16 18:47:38 +00003522 // Gather the non-hidden methods.
Sebastian Redl75d8a322010-08-02 23:18:59 +00003523 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00003524 SmallVector<ObjCMethodDecl *, 4> Methods;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003525 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003526 if (M->getMethod() && !M->getMethod()->isHidden())
3527 return M->getMethod();
Douglas Gregorc78d3462009-04-24 21:10:55 +00003528 }
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003529 return nullptr;
3530}
Douglas Gregor77f49a42013-01-16 18:47:38 +00003531
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003532void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3533 Selector Sel, SourceRange R,
3534 bool receiverIdOrClass) {
Douglas Gregor77f49a42013-01-16 18:47:38 +00003535 // We found multiple methods, so we may have to complain.
3536 bool issueDiagnostic = false, issueError = false;
Jonathan Roelofs74411362015-04-28 18:04:44 +00003537
Douglas Gregor77f49a42013-01-16 18:47:38 +00003538 // We support a warning which complains about *any* difference in
3539 // method signature.
3540 bool strictSelectorMatch =
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003541 receiverIdOrClass &&
3542 !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
Douglas Gregor77f49a42013-01-16 18:47:38 +00003543 if (strictSelectorMatch) {
3544 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3545 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
3546 issueDiagnostic = true;
3547 break;
3548 }
3549 }
3550 }
Jonathan Roelofs74411362015-04-28 18:04:44 +00003551
Douglas Gregor77f49a42013-01-16 18:47:38 +00003552 // If we didn't see any strict differences, we won't see any loose
3553 // differences. In ARC, however, we also need to check for loose
3554 // mismatches, because most of them are errors.
3555 if (!strictSelectorMatch ||
3556 (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
3557 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3558 // This checks if the methods differ in type mismatch.
3559 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
3560 !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
3561 issueDiagnostic = true;
3562 if (getLangOpts().ObjCAutoRefCount)
3563 issueError = true;
3564 break;
3565 }
3566 }
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003567
Douglas Gregor77f49a42013-01-16 18:47:38 +00003568 if (issueDiagnostic) {
3569 if (issueError)
3570 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
3571 else if (strictSelectorMatch)
3572 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
3573 else
3574 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003575
Douglas Gregor77f49a42013-01-16 18:47:38 +00003576 Diag(Methods[0]->getLocStart(),
3577 issueError ? diag::note_possibility : diag::note_using)
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003578 << Methods[0]->getSourceRange();
Douglas Gregor77f49a42013-01-16 18:47:38 +00003579 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3580 Diag(Methods[I]->getLocStart(), diag::note_also_found)
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003581 << Methods[I]->getSourceRange();
3582 }
Douglas Gregor77f49a42013-01-16 18:47:38 +00003583 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003584}
3585
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003586ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
Sebastian Redl75d8a322010-08-02 23:18:59 +00003587 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3588 if (Pos == MethodPool.end())
Craig Topperc3ec1492014-05-26 06:22:03 +00003589 return nullptr;
Sebastian Redl75d8a322010-08-02 23:18:59 +00003590
3591 GlobalMethods &Methods = Pos->second;
Fariborz Jahanianec762bd2014-03-26 20:59:26 +00003592 for (const ObjCMethodList *Method = &Methods.first; Method;
3593 Method = Method->getNext())
Fariborz Jahanian4019c7f2015-02-19 21:52:41 +00003594 if (Method->getMethod() &&
3595 (Method->getMethod()->isDefined() ||
3596 Method->getMethod()->isPropertyAccessor()))
Nico Weber2e0c8f72014-12-27 03:58:08 +00003597 return Method->getMethod();
Fariborz Jahanianec762bd2014-03-26 20:59:26 +00003598
3599 for (const ObjCMethodList *Method = &Methods.second; Method;
3600 Method = Method->getNext())
Fariborz Jahanian4019c7f2015-02-19 21:52:41 +00003601 if (Method->getMethod() &&
3602 (Method->getMethod()->isDefined() ||
3603 Method->getMethod()->isPropertyAccessor()))
Nico Weber2e0c8f72014-12-27 03:58:08 +00003604 return Method->getMethod();
Craig Topperc3ec1492014-05-26 06:22:03 +00003605 return nullptr;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003606}
3607
Fariborz Jahanian42f89382013-05-30 21:48:58 +00003608static void
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003609HelperSelectorsForTypoCorrection(
3610 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
3611 StringRef Typo, const ObjCMethodDecl * Method) {
3612 const unsigned MaxEditDistance = 1;
3613 unsigned BestEditDistance = MaxEditDistance + 1;
Richard Trieuea8d3702013-06-06 02:22:29 +00003614 std::string MethodName = Method->getSelector().getAsString();
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003615
3616 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
3617 if (MinPossibleEditDistance > 0 &&
3618 Typo.size() / MinPossibleEditDistance < 1)
3619 return;
3620 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
3621 if (EditDistance > MaxEditDistance)
3622 return;
3623 if (EditDistance == BestEditDistance)
3624 BestMethod.push_back(Method);
3625 else if (EditDistance < BestEditDistance) {
3626 BestMethod.clear();
3627 BestMethod.push_back(Method);
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003628 }
3629}
3630
Fariborz Jahanian75481672013-06-17 17:10:54 +00003631static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
3632 QualType ObjectType) {
3633 if (ObjectType.isNull())
3634 return true;
3635 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
3636 return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003637 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
3638 nullptr;
Fariborz Jahanian75481672013-06-17 17:10:54 +00003639}
3640
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003641const ObjCMethodDecl *
Fariborz Jahanian75481672013-06-17 17:10:54 +00003642Sema::SelectorsForTypoCorrection(Selector Sel,
3643 QualType ObjectType) {
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003644 unsigned NumArgs = Sel.getNumArgs();
3645 SmallVector<const ObjCMethodDecl *, 8> Methods;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003646 bool ObjectIsId = true, ObjectIsClass = true;
3647 if (ObjectType.isNull())
3648 ObjectIsId = ObjectIsClass = false;
3649 else if (!ObjectType->isObjCObjectPointerType())
Craig Topperc3ec1492014-05-26 06:22:03 +00003650 return nullptr;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003651 else if (const ObjCObjectPointerType *ObjCPtr =
3652 ObjectType->getAsObjCInterfacePointerType()) {
3653 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
3654 ObjectIsId = ObjectIsClass = false;
3655 }
3656 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
3657 ObjectIsClass = false;
3658 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
3659 ObjectIsId = false;
3660 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003661 return nullptr;
3662
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003663 for (GlobalMethodPool::iterator b = MethodPool.begin(),
3664 e = MethodPool.end(); b != e; b++) {
3665 // instance methods
3666 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003667 if (M->getMethod() &&
3668 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3669 (M->getMethod()->getSelector() != Sel)) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003670 if (ObjectIsId)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003671 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003672 else if (!ObjectIsClass &&
Nico Weber2e0c8f72014-12-27 03:58:08 +00003673 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3674 ObjectType))
3675 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003676 }
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003677 // class methods
3678 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003679 if (M->getMethod() &&
3680 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3681 (M->getMethod()->getSelector() != Sel)) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003682 if (ObjectIsClass)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003683 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003684 else if (!ObjectIsId &&
Nico Weber2e0c8f72014-12-27 03:58:08 +00003685 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3686 ObjectType))
3687 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003688 }
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003689 }
3690
3691 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
3692 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
3693 HelperSelectorsForTypoCorrection(SelectedMethods,
3694 Sel.getAsString(), Methods[i]);
3695 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003696 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003697}
3698
Fariborz Jahanian42f89382013-05-30 21:48:58 +00003699/// DiagnoseDuplicateIvars -
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003700/// Check for duplicate ivars in the entire class at the start of
James Dennett634962f2012-06-14 21:40:34 +00003701/// \@implementation. This becomes necesssary because class extension can
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003702/// add ivars to a class in random order which will not be known until
James Dennett634962f2012-06-14 21:40:34 +00003703/// class's \@implementation is seen.
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003704void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
3705 ObjCInterfaceDecl *SID) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00003706 for (auto *Ivar : ID->ivars()) {
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003707 if (Ivar->isInvalidDecl())
3708 continue;
3709 if (IdentifierInfo *II = Ivar->getIdentifier()) {
3710 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
3711 if (prevIvar) {
3712 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3713 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
3714 Ivar->setInvalidDecl();
3715 }
3716 }
3717 }
3718}
3719
John McCallb61e14e2015-10-27 04:54:50 +00003720/// Diagnose attempts to define ARC-__weak ivars when __weak is disabled.
3721static void DiagnoseWeakIvars(Sema &S, ObjCImplementationDecl *ID) {
3722 if (S.getLangOpts().ObjCWeak) return;
3723
3724 for (auto ivar = ID->getClassInterface()->all_declared_ivar_begin();
3725 ivar; ivar = ivar->getNextIvar()) {
3726 if (ivar->isInvalidDecl()) continue;
3727 if (ivar->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
3728 if (S.getLangOpts().ObjCWeakRuntime) {
3729 S.Diag(ivar->getLocation(), diag::err_arc_weak_disabled);
3730 } else {
3731 S.Diag(ivar->getLocation(), diag::err_arc_weak_no_runtime);
3732 }
3733 }
3734 }
3735}
3736
Volodymyr Sapsai30680e92017-10-23 22:01:41 +00003737/// Diagnose attempts to use flexible array member with retainable object type.
3738static void DiagnoseRetainableFlexibleArrayMember(Sema &S,
3739 ObjCInterfaceDecl *ID) {
3740 if (!S.getLangOpts().ObjCAutoRefCount)
3741 return;
3742
3743 for (auto ivar = ID->all_declared_ivar_begin(); ivar;
3744 ivar = ivar->getNextIvar()) {
3745 if (ivar->isInvalidDecl())
3746 continue;
3747 QualType IvarTy = ivar->getType();
3748 if (IvarTy->isIncompleteArrayType() &&
3749 (IvarTy.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) &&
3750 IvarTy->isObjCLifetimeType()) {
3751 S.Diag(ivar->getLocation(), diag::err_flexible_array_arc_retainable);
3752 ivar->setInvalidDecl();
3753 }
3754 }
3755}
3756
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003757Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
3758 switch (CurContext->getDeclKind()) {
3759 case Decl::ObjCInterface:
3760 return Sema::OCK_Interface;
3761 case Decl::ObjCProtocol:
3762 return Sema::OCK_Protocol;
3763 case Decl::ObjCCategory:
Benjamin Kramera008d3a2015-04-10 11:37:55 +00003764 if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003765 return Sema::OCK_ClassExtension;
Benjamin Kramera008d3a2015-04-10 11:37:55 +00003766 return Sema::OCK_Category;
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003767 case Decl::ObjCImplementation:
3768 return Sema::OCK_Implementation;
3769 case Decl::ObjCCategoryImpl:
3770 return Sema::OCK_CategoryImplementation;
3771
3772 default:
3773 return Sema::OCK_None;
3774 }
3775}
3776
Volodymyr Sapsai30680e92017-10-23 22:01:41 +00003777static bool IsVariableSizedType(QualType T) {
3778 if (T->isIncompleteArrayType())
3779 return true;
3780 const auto *RecordTy = T->getAs<RecordType>();
3781 return (RecordTy && RecordTy->getDecl()->hasFlexibleArrayMember());
3782}
3783
3784static void DiagnoseVariableSizedIvars(Sema &S, ObjCContainerDecl *OCD) {
3785 ObjCInterfaceDecl *IntfDecl = nullptr;
3786 ObjCInterfaceDecl::ivar_range Ivars = llvm::make_range(
3787 ObjCInterfaceDecl::ivar_iterator(), ObjCInterfaceDecl::ivar_iterator());
3788 if ((IntfDecl = dyn_cast<ObjCInterfaceDecl>(OCD))) {
3789 Ivars = IntfDecl->ivars();
3790 } else if (auto *ImplDecl = dyn_cast<ObjCImplementationDecl>(OCD)) {
3791 IntfDecl = ImplDecl->getClassInterface();
3792 Ivars = ImplDecl->ivars();
3793 } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(OCD)) {
3794 if (CategoryDecl->IsClassExtension()) {
3795 IntfDecl = CategoryDecl->getClassInterface();
3796 Ivars = CategoryDecl->ivars();
3797 }
3798 }
3799
3800 // Check if variable sized ivar is in interface and visible to subclasses.
3801 if (!isa<ObjCInterfaceDecl>(OCD)) {
3802 for (auto ivar : Ivars) {
3803 if (!ivar->isInvalidDecl() && IsVariableSizedType(ivar->getType())) {
3804 S.Diag(ivar->getLocation(), diag::warn_variable_sized_ivar_visibility)
3805 << ivar->getDeclName() << ivar->getType();
3806 }
3807 }
3808 }
3809
3810 // Subsequent checks require interface decl.
3811 if (!IntfDecl)
3812 return;
3813
3814 // Check if variable sized ivar is followed by another ivar.
3815 for (ObjCIvarDecl *ivar = IntfDecl->all_declared_ivar_begin(); ivar;
3816 ivar = ivar->getNextIvar()) {
3817 if (ivar->isInvalidDecl() || !ivar->getNextIvar())
3818 continue;
3819 QualType IvarTy = ivar->getType();
3820 bool IsInvalidIvar = false;
3821 if (IvarTy->isIncompleteArrayType()) {
3822 S.Diag(ivar->getLocation(), diag::err_flexible_array_not_at_end)
3823 << ivar->getDeclName() << IvarTy
3824 << TTK_Class; // Use "class" for Obj-C.
3825 IsInvalidIvar = true;
3826 } else if (const RecordType *RecordTy = IvarTy->getAs<RecordType>()) {
3827 if (RecordTy->getDecl()->hasFlexibleArrayMember()) {
3828 S.Diag(ivar->getLocation(),
3829 diag::err_objc_variable_sized_type_not_at_end)
3830 << ivar->getDeclName() << IvarTy;
3831 IsInvalidIvar = true;
3832 }
3833 }
3834 if (IsInvalidIvar) {
3835 S.Diag(ivar->getNextIvar()->getLocation(),
3836 diag::note_next_ivar_declaration)
3837 << ivar->getNextIvar()->getSynthesize();
3838 ivar->setInvalidDecl();
3839 }
3840 }
3841
3842 // Check if ObjC container adds ivars after variable sized ivar in superclass.
3843 // Perform the check only if OCD is the first container to declare ivars to
3844 // avoid multiple warnings for the same ivar.
3845 ObjCIvarDecl *FirstIvar =
3846 (Ivars.begin() == Ivars.end()) ? nullptr : *Ivars.begin();
3847 if (FirstIvar && (FirstIvar == IntfDecl->all_declared_ivar_begin())) {
3848 const ObjCInterfaceDecl *SuperClass = IntfDecl->getSuperClass();
3849 while (SuperClass && SuperClass->ivar_empty())
3850 SuperClass = SuperClass->getSuperClass();
3851 if (SuperClass) {
3852 auto IvarIter = SuperClass->ivar_begin();
3853 std::advance(IvarIter, SuperClass->ivar_size() - 1);
3854 const ObjCIvarDecl *LastIvar = *IvarIter;
3855 if (IsVariableSizedType(LastIvar->getType())) {
3856 S.Diag(FirstIvar->getLocation(),
3857 diag::warn_superclass_variable_sized_type_not_at_end)
3858 << FirstIvar->getDeclName() << LastIvar->getDeclName()
3859 << LastIvar->getType() << SuperClass->getDeclName();
3860 S.Diag(LastIvar->getLocation(), diag::note_entity_declared_at)
3861 << LastIvar->getDeclName();
3862 }
3863 }
3864 }
3865}
3866
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003867// Note: For class/category implementations, allMethods is always null.
Robert Wilhelm57c67112013-07-17 21:14:35 +00003868Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
Fariborz Jahaniandfb76872013-07-17 00:05:08 +00003869 ArrayRef<DeclGroupPtrTy> allTUVars) {
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003870 if (getObjCContainerKind() == Sema::OCK_None)
Craig Topperc3ec1492014-05-26 06:22:03 +00003871 return nullptr;
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003872
3873 assert(AtEnd.isValid() && "Invalid location for '@end'");
3874
George Burgess IV00f70bd2018-03-01 05:43:23 +00003875 auto *OCD = cast<ObjCContainerDecl>(CurContext);
3876 Decl *ClassDecl = OCD;
3877
Mike Stump11289f42009-09-09 15:08:12 +00003878 bool isInterfaceDeclKind =
Chris Lattner219b3e92008-03-16 21:17:37 +00003879 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
3880 || isa<ObjCProtocolDecl>(ClassDecl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003881 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
Steve Naroffb3a87982009-01-09 15:36:25 +00003882
Steve Naroff35c62ae2009-01-08 17:28:14 +00003883 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
3884 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
3885 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
3886
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003887 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003888 ObjCMethodDecl *Method =
John McCall48871652010-08-21 09:40:31 +00003889 cast_or_null<ObjCMethodDecl>(allMethods[i]);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003890
3891 if (!Method) continue; // Already issued a diagnostic.
Douglas Gregorffca3a22009-01-09 17:18:27 +00003892 if (Method->isInstanceMethod()) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00003893 /// Check for instance method of the same name with incompatible types
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003894 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
Mike Stump11289f42009-09-09 15:08:12 +00003895 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
Chris Lattnerda463fe2007-12-12 07:09:47 +00003896 : false;
Mike Stump11289f42009-09-09 15:08:12 +00003897 if ((isInterfaceDeclKind && PrevMethod && !match)
Eli Friedman42b1e9e2008-12-16 20:15:50 +00003898 || (checkIdenticalMethods && match)) {
Chris Lattner0369c572008-11-23 23:12:31 +00003899 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00003900 << Method->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003901 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Douglas Gregor87e92752010-12-21 17:34:17 +00003902 Method->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00003903 } else {
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003904 if (PrevMethod) {
Argyrios Kyrtzidisdcaaa212011-10-14 08:02:31 +00003905 Method->setAsRedeclaration(PrevMethod);
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003906 if (!Context.getSourceManager().isInSystemHeader(
3907 Method->getLocation()))
3908 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3909 << Method->getDeclName();
3910 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3911 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003912 InsMap[Method->getSelector()] = Method;
3913 /// The following allows us to typecheck messages to "id".
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003914 AddInstanceMethodToGlobalPool(Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003915 }
Mike Stump12b8ce12009-08-04 21:02:39 +00003916 } else {
Chris Lattnerda463fe2007-12-12 07:09:47 +00003917 /// Check for class method of the same name with incompatible types
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003918 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
Mike Stump11289f42009-09-09 15:08:12 +00003919 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
Chris Lattnerda463fe2007-12-12 07:09:47 +00003920 : false;
Mike Stump11289f42009-09-09 15:08:12 +00003921 if ((isInterfaceDeclKind && PrevMethod && !match)
Eli Friedman42b1e9e2008-12-16 20:15:50 +00003922 || (checkIdenticalMethods && match)) {
Chris Lattner0369c572008-11-23 23:12:31 +00003923 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00003924 << Method->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003925 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Douglas Gregor87e92752010-12-21 17:34:17 +00003926 Method->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00003927 } else {
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003928 if (PrevMethod) {
Argyrios Kyrtzidisdcaaa212011-10-14 08:02:31 +00003929 Method->setAsRedeclaration(PrevMethod);
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003930 if (!Context.getSourceManager().isInSystemHeader(
3931 Method->getLocation()))
3932 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3933 << Method->getDeclName();
3934 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3935 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003936 ClsMap[Method->getSelector()] = Method;
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003937 AddFactoryMethodToGlobalPool(Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003938 }
3939 }
3940 }
Douglas Gregorb8982092013-01-21 19:42:21 +00003941 if (isa<ObjCInterfaceDecl>(ClassDecl)) {
3942 // Nothing to do here.
Steve Naroffb3a87982009-01-09 15:36:25 +00003943 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
Fariborz Jahanian62293f42008-12-06 19:59:02 +00003944 // Categories are used to extend the class by declaring new methods.
Mike Stump11289f42009-09-09 15:08:12 +00003945 // By the same token, they are also used to add new properties. No
Fariborz Jahanian62293f42008-12-06 19:59:02 +00003946 // need to compare the added property to those in the class.
Daniel Dunbar4684f372008-08-27 05:40:03 +00003947
Fariborz Jahanianc21f5432010-12-10 23:36:33 +00003948 if (C->IsClassExtension()) {
3949 ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
3950 DiagnoseClassExtensionDupMethods(C, CCPrimary);
Fariborz Jahanianc21f5432010-12-10 23:36:33 +00003951 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003952 }
Steve Naroffb3a87982009-01-09 15:36:25 +00003953 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
Fariborz Jahanian30a42922010-02-15 21:55:26 +00003954 if (CDecl->getIdentifier())
3955 // ProcessPropertyDecl is responsible for diagnosing conflicts with any
3956 // user-defined setter/getter. It also synthesizes setter/getter methods
3957 // and adds them to the DeclContext and global method pools.
Manman Renefe1bac2016-01-27 20:00:32 +00003958 for (auto *I : CDecl->properties())
Douglas Gregore17765e2015-11-03 17:02:34 +00003959 ProcessPropertyDecl(I);
Ted Kremenekc7c64312010-01-07 01:20:12 +00003960 CDecl->setAtEndRange(AtEnd);
Steve Naroffb3a87982009-01-09 15:36:25 +00003961 }
3962 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
Ted Kremenekc7c64312010-01-07 01:20:12 +00003963 IC->setAtEndRange(AtEnd);
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00003964 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003965 // Any property declared in a class extension might have user
3966 // declared setter or getter in current class extension or one
3967 // of the other class extensions. Mark them as synthesized as
3968 // property will be synthesized when property with same name is
3969 // seen in the @implementation.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00003970 for (const auto *Ext : IDecl->visible_extensions()) {
Manman Rena7a8b1f2016-01-26 18:05:23 +00003971 for (const auto *Property : Ext->instance_properties()) {
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003972 // Skip over properties declared @dynamic
3973 if (const ObjCPropertyImplDecl *PIDecl
Manman Ren5b786402016-01-28 18:49:28 +00003974 = IC->FindPropertyImplDecl(Property->getIdentifier(),
3975 Property->getQueryKind()))
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003976 if (PIDecl->getPropertyImplementation()
3977 == ObjCPropertyImplDecl::Dynamic)
3978 continue;
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003979
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00003980 for (const auto *Ext : IDecl->visible_extensions()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003981 if (ObjCMethodDecl *GetterMethod
3982 = Ext->getInstanceMethod(Property->getGetterName()))
Jordan Rosed01e83a2012-10-10 16:42:25 +00003983 GetterMethod->setPropertyAccessor(true);
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003984 if (!Property->isReadOnly())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003985 if (ObjCMethodDecl *SetterMethod
3986 = Ext->getInstanceMethod(Property->getSetterName()))
Jordan Rosed01e83a2012-10-10 16:42:25 +00003987 SetterMethod->setPropertyAccessor(true);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003988 }
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003989 }
3990 }
Fariborz Jahanian25491a22010-05-05 21:52:17 +00003991 ImplMethodsVsClassMethods(S, IC, IDecl);
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00003992 AtomicPropertySetterGetterRules(IC, IDecl);
John McCall31168b02011-06-15 23:02:42 +00003993 DiagnoseOwningPropertyGetterSynthesis(IC);
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00003994 DiagnoseUnusedBackingIvarInAccessor(S, IC);
Fariborz Jahanian20cfff32015-03-11 16:59:48 +00003995 if (IDecl->hasDesignatedInitializers())
3996 DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
John McCallb61e14e2015-10-27 04:54:50 +00003997 DiagnoseWeakIvars(*this, IC);
Volodymyr Sapsai30680e92017-10-23 22:01:41 +00003998 DiagnoseRetainableFlexibleArrayMember(*this, IDecl);
Argyrios Kyrtzidisdb5ce0f2013-12-03 21:11:54 +00003999
Patrick Beardacfbe9e2012-04-06 18:12:22 +00004000 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
Craig Topperc3ec1492014-05-26 06:22:03 +00004001 if (IDecl->getSuperClass() == nullptr) {
Patrick Beardacfbe9e2012-04-06 18:12:22 +00004002 // This class has no superclass, so check that it has been marked with
4003 // __attribute((objc_root_class)).
4004 if (!HasRootClassAttr) {
4005 SourceLocation DeclLoc(IDecl->getLocation());
Alp Tokerb6cc5922014-05-03 03:45:55 +00004006 SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
Patrick Beardacfbe9e2012-04-06 18:12:22 +00004007 Diag(DeclLoc, diag::warn_objc_root_class_missing)
4008 << IDecl->getIdentifier();
4009 // See if NSObject is in the current scope, and if it is, suggest
4010 // adding " : NSObject " to the class declaration.
4011 NamedDecl *IF = LookupSingleName(TUScope,
4012 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
4013 DeclLoc, LookupOrdinaryName);
4014 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
4015 if (NSObjectDecl && NSObjectDecl->getDefinition()) {
4016 Diag(SuperClassLoc, diag::note_objc_needs_superclass)
4017 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
4018 } else {
4019 Diag(SuperClassLoc, diag::note_objc_needs_superclass);
4020 }
4021 }
4022 } else if (HasRootClassAttr) {
4023 // Complain that only root classes may have this attribute.
4024 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
4025 }
4026
Alex Lorenza8c44ba2016-10-28 10:25:10 +00004027 if (const ObjCInterfaceDecl *Super = IDecl->getSuperClass()) {
4028 // An interface can subclass another interface with a
4029 // objc_subclassing_restricted attribute when it has that attribute as
4030 // well (because of interfaces imported from Swift). Therefore we have
4031 // to check if we can subclass in the implementation as well.
4032 if (IDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
4033 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
4034 Diag(IC->getLocation(), diag::err_restricted_superclass_mismatch);
4035 Diag(Super->getLocation(), diag::note_class_declared);
4036 }
4037 }
4038
John McCall5fb5df92012-06-20 06:18:46 +00004039 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian545643c2010-02-23 23:41:11 +00004040 while (IDecl->getSuperClass()) {
4041 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
4042 IDecl = IDecl->getSuperClass();
4043 }
Patrick Beardacfbe9e2012-04-06 18:12:22 +00004044 }
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00004045 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004046 SetIvarInitializers(IC);
Mike Stump11289f42009-09-09 15:08:12 +00004047 } else if (ObjCCategoryImplDecl* CatImplClass =
Steve Naroffb3a87982009-01-09 15:36:25 +00004048 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
Ted Kremenekc7c64312010-01-07 01:20:12 +00004049 CatImplClass->setAtEndRange(AtEnd);
Mike Stump11289f42009-09-09 15:08:12 +00004050
Chris Lattnerda463fe2007-12-12 07:09:47 +00004051 // Find category interface decl and then check that all methods declared
Daniel Dunbar4684f372008-08-27 05:40:03 +00004052 // in this interface are implemented in the category @implementation.
Chris Lattner41fd42e2009-02-16 18:32:47 +00004053 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00004054 if (ObjCCategoryDecl *Cat
4055 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
4056 ImplMethodsVsClassMethods(S, CatImplClass, Cat);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004057 }
4058 }
Alex Lorenza8c44ba2016-10-28 10:25:10 +00004059 } else if (const auto *IntfDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
4060 if (const ObjCInterfaceDecl *Super = IntfDecl->getSuperClass()) {
4061 if (!IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
4062 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
4063 Diag(IntfDecl->getLocation(), diag::err_restricted_superclass_mismatch);
4064 Diag(Super->getLocation(), diag::note_class_declared);
4065 }
4066 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00004067 }
Volodymyr Sapsai30680e92017-10-23 22:01:41 +00004068 DiagnoseVariableSizedIvars(*this, OCD);
Chris Lattner5bbb3c82009-03-29 16:50:03 +00004069 if (isInterfaceDeclKind) {
4070 // Reject invalid vardecls.
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00004071 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00004072 DeclGroupRef DG = allTUVars[i].get();
Chris Lattner5bbb3c82009-03-29 16:50:03 +00004073 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
4074 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
Daniel Dunbar0ca16602009-04-14 02:25:56 +00004075 if (!VDecl->hasExternalStorage())
Steve Naroff42959b22009-04-13 17:58:46 +00004076 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
Fariborz Jahanian629aed92009-03-21 18:06:45 +00004077 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00004078 }
Fariborz Jahanian3654e652009-03-18 22:33:24 +00004079 }
Fariborz Jahanian4327b322011-08-29 17:33:12 +00004080 ActOnObjCContainerFinishDefinition();
Argyrios Kyrtzidisbd8b1502011-10-17 19:48:13 +00004081
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00004082 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00004083 DeclGroupRef DG = allTUVars[i].get();
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004084 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
4085 (*I)->setTopLevelDeclInObjCContainer();
Argyrios Kyrtzidisbd8b1502011-10-17 19:48:13 +00004086 Consumer.HandleTopLevelDeclInObjCContainer(DG);
4087 }
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00004088
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +00004089 ActOnDocumentableDecl(ClassDecl);
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00004090 return ClassDecl;
Chris Lattnerda463fe2007-12-12 07:09:47 +00004091}
4092
Chris Lattnerda463fe2007-12-12 07:09:47 +00004093/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
4094/// objective-c's type qualifier from the parser version of the same info.
Mike Stump11289f42009-09-09 15:08:12 +00004095static Decl::ObjCDeclQualifier
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004096CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
John McCallca872902011-05-01 03:04:29 +00004097 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
Chris Lattnerda463fe2007-12-12 07:09:47 +00004098}
4099
Douglas Gregor33823722011-06-11 01:09:30 +00004100/// \brief Check whether the declared result type of the given Objective-C
4101/// method declaration is compatible with the method's class.
4102///
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004103static Sema::ResultTypeCompatibilityKind
Douglas Gregor33823722011-06-11 01:09:30 +00004104CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
4105 ObjCInterfaceDecl *CurrentClass) {
Alp Toker314cc812014-01-25 16:55:45 +00004106 QualType ResultType = Method->getReturnType();
4107
Douglas Gregor33823722011-06-11 01:09:30 +00004108 // If an Objective-C method inherits its related result type, then its
4109 // declared result type must be compatible with its own class type. The
4110 // declared result type is compatible if:
4111 if (const ObjCObjectPointerType *ResultObjectType
4112 = ResultType->getAs<ObjCObjectPointerType>()) {
4113 // - it is id or qualified id, or
4114 if (ResultObjectType->isObjCIdType() ||
4115 ResultObjectType->isObjCQualifiedIdType())
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004116 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00004117
4118 if (CurrentClass) {
4119 if (ObjCInterfaceDecl *ResultClass
4120 = ResultObjectType->getInterfaceDecl()) {
4121 // - it is the same as the method's class type, or
Douglas Gregor0b144e12011-12-15 00:29:59 +00004122 if (declaresSameEntity(CurrentClass, ResultClass))
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004123 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00004124
4125 // - it is a superclass of the method's class type
4126 if (ResultClass->isSuperClassOf(CurrentClass))
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004127 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00004128 }
Douglas Gregorbab8a962011-09-08 01:46:34 +00004129 } else {
4130 // Any Objective-C pointer type might be acceptable for a protocol
4131 // method; we just don't know.
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004132 return Sema::RTC_Unknown;
Douglas Gregor33823722011-06-11 01:09:30 +00004133 }
4134 }
4135
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004136 return Sema::RTC_Incompatible;
Douglas Gregor33823722011-06-11 01:09:30 +00004137}
4138
John McCalld2930c22011-07-22 02:45:48 +00004139namespace {
4140/// A helper class for searching for methods which a particular method
4141/// overrides.
4142class OverrideSearch {
Daniel Dunbard6d74c32012-02-29 03:04:05 +00004143public:
John McCalld2930c22011-07-22 02:45:48 +00004144 Sema &S;
4145 ObjCMethodDecl *Method;
Akira Hatanaka4c687f32018-02-06 23:44:40 +00004146 llvm::SmallSetVector<ObjCMethodDecl*, 4> Overridden;
John McCalld2930c22011-07-22 02:45:48 +00004147 bool Recursive;
4148
4149public:
4150 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
4151 Selector selector = method->getSelector();
4152
4153 // Bypass this search if we've never seen an instance/class method
4154 // with this selector before.
4155 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
4156 if (it == S.MethodPool.end()) {
Axel Naumanndd433f02012-10-18 19:05:02 +00004157 if (!S.getExternalSource()) return;
Douglas Gregore1716012012-01-25 00:49:42 +00004158 S.ReadMethodPool(selector);
4159
4160 it = S.MethodPool.find(selector);
4161 if (it == S.MethodPool.end())
4162 return;
John McCalld2930c22011-07-22 02:45:48 +00004163 }
4164 ObjCMethodList &list =
4165 method->isInstanceMethod() ? it->second.first : it->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00004166 if (!list.getMethod()) return;
John McCalld2930c22011-07-22 02:45:48 +00004167
4168 ObjCContainerDecl *container
4169 = cast<ObjCContainerDecl>(method->getDeclContext());
4170
4171 // Prevent the search from reaching this container again. This is
4172 // important with categories, which override methods from the
4173 // interface and each other.
Douglas Gregorcf4ac442012-05-03 21:25:24 +00004174 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) {
4175 searchFromContainer(container);
Douglas Gregorc5928af2012-05-17 22:39:14 +00004176 if (ObjCInterfaceDecl *Interface = Category->getClassInterface())
4177 searchFromContainer(Interface);
Douglas Gregorcf4ac442012-05-03 21:25:24 +00004178 } else {
4179 searchFromContainer(container);
4180 }
Douglas Gregor33823722011-06-11 01:09:30 +00004181 }
John McCalld2930c22011-07-22 02:45:48 +00004182
Akira Hatanaka4c687f32018-02-06 23:44:40 +00004183 typedef decltype(Overridden)::iterator iterator;
John McCalld2930c22011-07-22 02:45:48 +00004184 iterator begin() const { return Overridden.begin(); }
4185 iterator end() const { return Overridden.end(); }
4186
4187private:
4188 void searchFromContainer(ObjCContainerDecl *container) {
4189 if (container->isInvalidDecl()) return;
4190
4191 switch (container->getDeclKind()) {
4192#define OBJCCONTAINER(type, base) \
4193 case Decl::type: \
4194 searchFrom(cast<type##Decl>(container)); \
4195 break;
4196#define ABSTRACT_DECL(expansion)
4197#define DECL(type, base) \
4198 case Decl::type:
4199#include "clang/AST/DeclNodes.inc"
4200 llvm_unreachable("not an ObjC container!");
4201 }
4202 }
4203
4204 void searchFrom(ObjCProtocolDecl *protocol) {
Douglas Gregore6e48b12012-01-01 19:29:29 +00004205 if (!protocol->hasDefinition())
4206 return;
4207
John McCalld2930c22011-07-22 02:45:48 +00004208 // A method in a protocol declaration overrides declarations from
4209 // referenced ("parent") protocols.
4210 search(protocol->getReferencedProtocols());
4211 }
4212
4213 void searchFrom(ObjCCategoryDecl *category) {
4214 // A method in a category declaration overrides declarations from
4215 // the main class and from protocols the category references.
Douglas Gregorcf4ac442012-05-03 21:25:24 +00004216 // The main class is handled in the constructor.
John McCalld2930c22011-07-22 02:45:48 +00004217 search(category->getReferencedProtocols());
4218 }
4219
4220 void searchFrom(ObjCCategoryImplDecl *impl) {
4221 // A method in a category definition that has a category
4222 // declaration overrides declarations from the category
4223 // declaration.
4224 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
4225 search(category);
Douglas Gregorc5928af2012-05-17 22:39:14 +00004226 if (ObjCInterfaceDecl *Interface = category->getClassInterface())
4227 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00004228
4229 // Otherwise it overrides declarations from the class.
Douglas Gregorc5928af2012-05-17 22:39:14 +00004230 } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) {
4231 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00004232 }
4233 }
4234
4235 void searchFrom(ObjCInterfaceDecl *iface) {
4236 // A method in a class declaration overrides declarations from
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00004237 if (!iface->hasDefinition())
4238 return;
4239
John McCalld2930c22011-07-22 02:45:48 +00004240 // - categories,
Aaron Ballman15063e12014-03-13 21:35:02 +00004241 for (auto *Cat : iface->known_categories())
4242 search(Cat);
John McCalld2930c22011-07-22 02:45:48 +00004243
4244 // - the super class, and
4245 if (ObjCInterfaceDecl *super = iface->getSuperClass())
4246 search(super);
4247
4248 // - any referenced protocols.
4249 search(iface->getReferencedProtocols());
4250 }
4251
4252 void searchFrom(ObjCImplementationDecl *impl) {
4253 // A method in a class implementation overrides declarations from
4254 // the class interface.
Douglas Gregorc5928af2012-05-17 22:39:14 +00004255 if (ObjCInterfaceDecl *Interface = impl->getClassInterface())
4256 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00004257 }
4258
John McCalld2930c22011-07-22 02:45:48 +00004259 void search(const ObjCProtocolList &protocols) {
4260 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
4261 i != e; ++i)
4262 search(*i);
4263 }
4264
4265 void search(ObjCContainerDecl *container) {
John McCalld2930c22011-07-22 02:45:48 +00004266 // Check for a method in this container which matches this selector.
4267 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
Argyrios Kyrtzidisbd8cd3e2013-03-29 21:51:48 +00004268 Method->isInstanceMethod(),
4269 /*AllowHidden=*/true);
John McCalld2930c22011-07-22 02:45:48 +00004270
4271 // If we find one, record it and bail out.
4272 if (meth) {
4273 Overridden.insert(meth);
4274 return;
4275 }
4276
4277 // Otherwise, search for methods that a hypothetical method here
4278 // would have overridden.
4279
4280 // Note that we're now in a recursive case.
4281 Recursive = true;
4282
4283 searchFromContainer(container);
4284 }
4285};
Hans Wennborgdcfba332015-10-06 23:40:43 +00004286} // end anonymous namespace
Douglas Gregor33823722011-06-11 01:09:30 +00004287
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004288void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
4289 ObjCInterfaceDecl *CurrentClass,
4290 ResultTypeCompatibilityKind RTC) {
4291 // Search for overridden methods and merge information down from them.
4292 OverrideSearch overrides(*this, ObjCMethod);
4293 // Keep track if the method overrides any method in the class's base classes,
4294 // its protocols, or its categories' protocols; we will keep that info
4295 // in the ObjCMethodDecl.
4296 // For this info, a method in an implementation is not considered as
4297 // overriding the same method in the interface or its categories.
4298 bool hasOverriddenMethodsInBaseOrProtocol = false;
4299 for (OverrideSearch::iterator
4300 i = overrides.begin(), e = overrides.end(); i != e; ++i) {
4301 ObjCMethodDecl *overridden = *i;
4302
Argyrios Kyrtzidisc2091d52013-04-17 00:09:08 +00004303 if (!hasOverriddenMethodsInBaseOrProtocol) {
4304 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
4305 CurrentClass != overridden->getClassInterface() ||
4306 overridden->isOverriding()) {
4307 hasOverriddenMethodsInBaseOrProtocol = true;
4308
4309 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
4310 // OverrideSearch will return as "overridden" the same method in the
4311 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
4312 // check whether a category of a base class introduced a method with the
4313 // same selector, after the interface method declaration.
4314 // To avoid unnecessary lookups in the majority of cases, we use the
4315 // extra info bits in GlobalMethodPool to check whether there were any
4316 // category methods with this selector.
4317 GlobalMethodPool::iterator It =
4318 MethodPool.find(ObjCMethod->getSelector());
4319 if (It != MethodPool.end()) {
4320 ObjCMethodList &List =
4321 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
4322 unsigned CategCount = List.getBits();
4323 if (CategCount > 0) {
4324 // If the method is in a category we'll do lookup if there were at
4325 // least 2 category methods recorded, otherwise only one will do.
4326 if (CategCount > 1 ||
4327 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
4328 OverrideSearch overrides(*this, overridden);
4329 for (OverrideSearch::iterator
4330 OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) {
4331 ObjCMethodDecl *SuperOverridden = *OI;
Argyrios Kyrtzidis04703a62013-04-27 00:10:12 +00004332 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
4333 CurrentClass != SuperOverridden->getClassInterface()) {
Argyrios Kyrtzidisc2091d52013-04-17 00:09:08 +00004334 hasOverriddenMethodsInBaseOrProtocol = true;
4335 overridden->setOverriding(true);
4336 break;
4337 }
4338 }
4339 }
4340 }
4341 }
4342 }
4343 }
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004344
4345 // Propagate down the 'related result type' bit from overridden methods.
4346 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
4347 ObjCMethod->SetRelatedResultType();
4348
4349 // Then merge the declarations.
4350 mergeObjCMethodDecls(ObjCMethod, overridden);
4351
4352 if (ObjCMethod->isImplicit() && overridden->isImplicit())
4353 continue; // Conflicting properties are detected elsewhere.
4354
4355 // Check for overriding methods
4356 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
4357 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
4358 CheckConflictingOverridingMethod(ObjCMethod, overridden,
4359 isa<ObjCProtocolDecl>(overridden->getDeclContext()));
4360
4361 if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
Fariborz Jahanian31a25682012-07-05 22:26:07 +00004362 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
4363 !overridden->isImplicit() /* not meant for properties */) {
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004364 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
4365 E = ObjCMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +00004366 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
4367 PrevE = overridden->param_end();
4368 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004369 assert(PrevI != overridden->param_end() && "Param mismatch");
4370 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
4371 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
4372 // If type of argument of method in this class does not match its
4373 // respective argument type in the super class method, issue warning;
4374 if (!Context.typesAreCompatible(T1, T2)) {
4375 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
4376 << T1 << T2;
4377 Diag(overridden->getLocation(), diag::note_previous_declaration);
4378 break;
4379 }
4380 }
4381 }
4382 }
4383
4384 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
4385}
4386
Douglas Gregor813a0662015-06-19 18:14:38 +00004387/// Merge type nullability from for a redeclaration of the same entity,
4388/// producing the updated type of the redeclared entity.
4389static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc,
4390 QualType type,
4391 bool usesCSKeyword,
4392 SourceLocation prevLoc,
4393 QualType prevType,
4394 bool prevUsesCSKeyword) {
4395 // Determine the nullability of both types.
4396 auto nullability = type->getNullability(S.Context);
4397 auto prevNullability = prevType->getNullability(S.Context);
4398
4399 // Easy case: both have nullability.
4400 if (nullability.hasValue() == prevNullability.hasValue()) {
4401 // Neither has nullability; continue.
4402 if (!nullability)
4403 return type;
4404
4405 // The nullabilities are equivalent; do nothing.
4406 if (*nullability == *prevNullability)
4407 return type;
4408
4409 // Complain about mismatched nullability.
4410 S.Diag(loc, diag::err_nullability_conflicting)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00004411 << DiagNullabilityKind(*nullability, usesCSKeyword)
4412 << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword);
Douglas Gregor813a0662015-06-19 18:14:38 +00004413 return type;
4414 }
4415
4416 // If it's the redeclaration that has nullability, don't change anything.
4417 if (nullability)
4418 return type;
4419
4420 // Otherwise, provide the result with the same nullability.
4421 return S.Context.getAttributedType(
4422 AttributedType::getNullabilityAttrKind(*prevNullability),
4423 type, type);
4424}
4425
NAKAMURA Takumi2df5c3c2015-06-20 03:52:52 +00004426/// Merge information from the declaration of a method in the \@interface
Douglas Gregor813a0662015-06-19 18:14:38 +00004427/// (or a category/extension) into the corresponding method in the
4428/// @implementation (for a class or category).
4429static void mergeInterfaceMethodToImpl(Sema &S,
4430 ObjCMethodDecl *method,
4431 ObjCMethodDecl *prevMethod) {
4432 // Merge the objc_requires_super attribute.
4433 if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() &&
4434 !method->hasAttr<ObjCRequiresSuperAttr>()) {
4435 // merge the attribute into implementation.
4436 method->addAttr(
4437 ObjCRequiresSuperAttr::CreateImplicit(S.Context,
4438 method->getLocation()));
4439 }
4440
4441 // Merge nullability of the result type.
4442 QualType newReturnType
4443 = mergeTypeNullabilityForRedecl(
4444 S, method->getReturnTypeSourceRange().getBegin(),
4445 method->getReturnType(),
4446 method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4447 prevMethod->getReturnTypeSourceRange().getBegin(),
4448 prevMethod->getReturnType(),
4449 prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4450 method->setReturnType(newReturnType);
4451
4452 // Handle each of the parameters.
4453 unsigned numParams = method->param_size();
4454 unsigned numPrevParams = prevMethod->param_size();
4455 for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) {
4456 ParmVarDecl *param = method->param_begin()[i];
4457 ParmVarDecl *prevParam = prevMethod->param_begin()[i];
4458
4459 // Merge nullability.
4460 QualType newParamType
4461 = mergeTypeNullabilityForRedecl(
4462 S, param->getLocation(), param->getType(),
4463 param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4464 prevParam->getLocation(), prevParam->getType(),
4465 prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4466 param->setType(newParamType);
4467 }
4468}
4469
Alex Lorenza8a372d2017-04-27 10:43:48 +00004470/// Verify that the method parameters/return value have types that are supported
4471/// by the x86 target.
4472static void checkObjCMethodX86VectorTypes(Sema &SemaRef,
4473 const ObjCMethodDecl *Method) {
4474 assert(SemaRef.getASTContext().getTargetInfo().getTriple().getArch() ==
4475 llvm::Triple::x86 &&
4476 "x86-specific check invoked for a different target");
4477 SourceLocation Loc;
4478 QualType T;
4479 for (const ParmVarDecl *P : Method->parameters()) {
4480 if (P->getType()->isVectorType()) {
4481 Loc = P->getLocStart();
4482 T = P->getType();
4483 break;
4484 }
4485 }
4486 if (Loc.isInvalid()) {
4487 if (Method->getReturnType()->isVectorType()) {
4488 Loc = Method->getReturnTypeSourceRange().getBegin();
4489 T = Method->getReturnType();
4490 } else
4491 return;
4492 }
4493
4494 // Vector parameters/return values are not supported by objc_msgSend on x86 in
4495 // iOS < 9 and macOS < 10.11.
4496 const auto &Triple = SemaRef.getASTContext().getTargetInfo().getTriple();
4497 VersionTuple AcceptedInVersion;
4498 if (Triple.getOS() == llvm::Triple::IOS)
4499 AcceptedInVersion = VersionTuple(/*Major=*/9);
4500 else if (Triple.isMacOSX())
4501 AcceptedInVersion = VersionTuple(/*Major=*/10, /*Minor=*/11);
4502 else
4503 return;
Alex Lorenza8a372d2017-04-27 10:43:48 +00004504 if (SemaRef.getASTContext().getTargetInfo().getPlatformMinVersion() >=
Alex Lorenz92824832017-05-05 16:15:17 +00004505 AcceptedInVersion)
Alex Lorenza8a372d2017-04-27 10:43:48 +00004506 return;
4507 SemaRef.Diag(Loc, diag::err_objc_method_unsupported_param_ret_type)
4508 << T << (Method->getReturnType()->isVectorType() ? /*return value*/ 1
4509 : /*parameter*/ 0)
4510 << (Triple.isMacOSX() ? "macOS 10.11" : "iOS 9");
4511}
4512
John McCall48871652010-08-21 09:40:31 +00004513Decl *Sema::ActOnMethodDeclaration(
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004514 Scope *S,
Chris Lattnerda463fe2007-12-12 07:09:47 +00004515 SourceLocation MethodLoc, SourceLocation EndLoc,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004516 tok::TokenKind MethodType,
John McCallba7bf592010-08-24 05:47:05 +00004517 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004518 ArrayRef<SourceLocation> SelectorLocs,
Chris Lattnerda463fe2007-12-12 07:09:47 +00004519 Selector Sel,
4520 // optional arguments. The number of types/arguments is obtained
4521 // from the Sel.getNumArgs().
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004522 ObjCArgInfo *ArgInfo,
Fariborz Jahanian60462092010-04-08 00:30:06 +00004523 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
Chris Lattnerda463fe2007-12-12 07:09:47 +00004524 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
Fariborz Jahanianc677f692011-03-12 18:54:30 +00004525 bool isVariadic, bool MethodDefinition) {
Steve Naroff83777fe2008-02-29 21:48:07 +00004526 // Make sure we can establish a context for the method.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004527 if (!CurContext->isObjCContainer()) {
Richard Smithf8812672016-12-02 22:38:31 +00004528 Diag(MethodLoc, diag::err_missing_method_context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004529 return nullptr;
Steve Naroff83777fe2008-02-29 21:48:07 +00004530 }
George Burgess IV00f70bd2018-03-01 05:43:23 +00004531 Decl *ClassDecl = cast<ObjCContainerDecl>(CurContext);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004532 QualType resultDeclType;
Mike Stump11289f42009-09-09 15:08:12 +00004533
Douglas Gregorbab8a962011-09-08 01:46:34 +00004534 bool HasRelatedResultType = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00004535 TypeSourceInfo *ReturnTInfo = nullptr;
Steve Naroff32606412009-02-20 22:59:16 +00004536 if (ReturnType) {
Alp Toker314cc812014-01-25 16:55:45 +00004537 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004538
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004539 if (CheckFunctionReturnType(resultDeclType, MethodLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00004540 return nullptr;
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004541
Douglas Gregor813a0662015-06-19 18:14:38 +00004542 QualType bareResultType = resultDeclType;
4543 (void)AttributedType::stripOuterNullability(bareResultType);
4544 HasRelatedResultType = (bareResultType == Context.getObjCInstanceType());
Fariborz Jahanianb5a52ca2011-07-21 17:00:47 +00004545 } else { // get the type for "id".
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004546 resultDeclType = Context.getObjCIdType();
Fariborz Jahanianb21138f2011-07-21 17:38:14 +00004547 Diag(MethodLoc, diag::warn_missing_method_return_type)
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004548 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
Fariborz Jahanianb5a52ca2011-07-21 17:00:47 +00004549 }
Mike Stump11289f42009-09-09 15:08:12 +00004550
Alp Toker314cc812014-01-25 16:55:45 +00004551 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
4552 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
4553 MethodType == tok::minus, isVariadic,
4554 /*isPropertyAccessor=*/false,
4555 /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
4556 MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
4557 : ObjCMethodDecl::Required,
4558 HasRelatedResultType);
Mike Stump11289f42009-09-09 15:08:12 +00004559
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004560 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump11289f42009-09-09 15:08:12 +00004561
Chris Lattner23b0faf2009-04-11 19:42:43 +00004562 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
John McCall856bbea2009-10-23 21:48:59 +00004563 QualType ArgType;
John McCallbcd03502009-12-07 02:54:59 +00004564 TypeSourceInfo *DI;
Mike Stump11289f42009-09-09 15:08:12 +00004565
David Blaikie7d170102013-05-15 07:37:26 +00004566 if (!ArgInfo[i].Type) {
John McCall856bbea2009-10-23 21:48:59 +00004567 ArgType = Context.getObjCIdType();
Craig Topperc3ec1492014-05-26 06:22:03 +00004568 DI = nullptr;
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004569 } else {
John McCall856bbea2009-10-23 21:48:59 +00004570 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004571 }
Mike Stump11289f42009-09-09 15:08:12 +00004572
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004573 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
Richard Smithbecb92d2017-10-10 22:33:17 +00004574 LookupOrdinaryName, forRedeclarationInCurContext());
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004575 LookupName(R, S);
4576 if (R.isSingleResult()) {
4577 NamedDecl *PrevDecl = R.getFoundDecl();
4578 if (S->isDeclScope(PrevDecl)) {
Fariborz Jahanianc677f692011-03-12 18:54:30 +00004579 Diag(ArgInfo[i].NameLoc,
4580 (MethodDefinition ? diag::warn_method_param_redefinition
4581 : diag::warn_method_param_declaration))
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004582 << ArgInfo[i].Name;
4583 Diag(PrevDecl->getLocation(),
4584 diag::note_previous_declaration);
4585 }
4586 }
4587
Abramo Bagnaradff19302011-03-08 08:55:46 +00004588 SourceLocation StartLoc = DI
4589 ? DI->getTypeLoc().getBeginLoc()
4590 : ArgInfo[i].NameLoc;
4591
John McCalld44f4d72011-04-23 02:46:06 +00004592 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
4593 ArgInfo[i].NameLoc, ArgInfo[i].Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004594 ArgType, DI, SC_None);
Mike Stump11289f42009-09-09 15:08:12 +00004595
John McCall82490832011-05-02 00:30:12 +00004596 Param->setObjCMethodScopeInfo(i);
4597
Chris Lattnerc5ffed42008-04-04 06:12:32 +00004598 Param->setObjCDeclQualifier(
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004599 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
Mike Stump11289f42009-09-09 15:08:12 +00004600
Chris Lattner9713a1c2009-04-11 19:34:56 +00004601 // Apply the attributes to the parameter.
Douglas Gregor758a8692009-06-17 21:51:59 +00004602 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00004603 AddPragmaAttributes(TUScope, Param);
Mike Stump11289f42009-09-09 15:08:12 +00004604
Fariborz Jahanian52d02f62012-01-14 18:44:35 +00004605 if (Param->hasAttr<BlocksAttr>()) {
4606 Diag(Param->getLocation(), diag::err_block_on_nonlocal);
4607 Param->setInvalidDecl();
4608 }
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004609 S->AddDecl(Param);
4610 IdResolver.AddDecl(Param);
4611
Chris Lattnerc5ffed42008-04-04 06:12:32 +00004612 Params.push_back(Param);
4613 }
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004614
Fariborz Jahanian60462092010-04-08 00:30:06 +00004615 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +00004616 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
Fariborz Jahanian60462092010-04-08 00:30:06 +00004617 QualType ArgType = Param->getType();
4618 if (ArgType.isNull())
4619 ArgType = Context.getObjCIdType();
4620 else
4621 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
Douglas Gregor84280642011-07-12 04:42:08 +00004622 ArgType = Context.getAdjustedParameterType(ArgType);
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004623
Fariborz Jahanian60462092010-04-08 00:30:06 +00004624 Param->setDeclContext(ObjCMethod);
Fariborz Jahanian60462092010-04-08 00:30:06 +00004625 Params.push_back(Param);
4626 }
4627
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004628 ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004629 ObjCMethod->setObjCDeclQualifier(
4630 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
Daniel Dunbarc136e0c2008-09-26 04:12:28 +00004631
4632 if (AttrList)
Douglas Gregor758a8692009-06-17 21:51:59 +00004633 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00004634 AddPragmaAttributes(TUScope, ObjCMethod);
Mike Stump11289f42009-09-09 15:08:12 +00004635
Douglas Gregor87e92752010-12-21 17:34:17 +00004636 // Add the method now.
Craig Topperc3ec1492014-05-26 06:22:03 +00004637 const ObjCMethodDecl *PrevMethod = nullptr;
John McCalld2930c22011-07-22 02:45:48 +00004638 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00004639 if (MethodType == tok::minus) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004640 PrevMethod = ImpDecl->getInstanceMethod(Sel);
4641 ImpDecl->addInstanceMethod(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004642 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004643 PrevMethod = ImpDecl->getClassMethod(Sel);
4644 ImpDecl->addClassMethod(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004645 }
Douglas Gregor33823722011-06-11 01:09:30 +00004646
Douglas Gregor813a0662015-06-19 18:14:38 +00004647 // Merge information from the @interface declaration into the
4648 // @implementation.
4649 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) {
4650 if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
4651 ObjCMethod->isInstanceMethod())) {
4652 mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD);
4653
4654 // Warn about defining -dealloc in a category.
4655 if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() &&
4656 ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) {
4657 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
4658 << ObjCMethod->getDeclName();
4659 }
4660 }
Fariborz Jahanian7e350d22013-12-17 22:44:28 +00004661 }
Douglas Gregor87e92752010-12-21 17:34:17 +00004662 } else {
4663 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004664 }
John McCalld2930c22011-07-22 02:45:48 +00004665
Chris Lattnerda463fe2007-12-12 07:09:47 +00004666 if (PrevMethod) {
4667 // You can never have two method definitions with the same name.
Chris Lattner0369c572008-11-23 23:12:31 +00004668 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00004669 << ObjCMethod->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00004670 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian096f7c12013-05-13 17:27:00 +00004671 ObjCMethod->setInvalidDecl();
4672 return ObjCMethod;
Mike Stump11289f42009-09-09 15:08:12 +00004673 }
John McCall28a6aea2009-11-04 02:18:39 +00004674
Douglas Gregor33823722011-06-11 01:09:30 +00004675 // If this Objective-C method does not have a related result type, but we
4676 // are allowed to infer related result types, try to do so based on the
4677 // method family.
4678 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
4679 if (!CurrentClass) {
4680 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
4681 CurrentClass = Cat->getClassInterface();
4682 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
4683 CurrentClass = Impl->getClassInterface();
4684 else if (ObjCCategoryImplDecl *CatImpl
4685 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
4686 CurrentClass = CatImpl->getClassInterface();
4687 }
John McCalld2930c22011-07-22 02:45:48 +00004688
Douglas Gregorbab8a962011-09-08 01:46:34 +00004689 ResultTypeCompatibilityKind RTC
4690 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
John McCalld2930c22011-07-22 02:45:48 +00004691
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004692 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
John McCalld2930c22011-07-22 02:45:48 +00004693
John McCall31168b02011-06-15 23:02:42 +00004694 bool ARCError = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004695 if (getLangOpts().ObjCAutoRefCount)
John McCalle48f3892013-04-04 01:38:37 +00004696 ARCError = CheckARCMethodDecl(ObjCMethod);
John McCall31168b02011-06-15 23:02:42 +00004697
Douglas Gregorbab8a962011-09-08 01:46:34 +00004698 // Infer the related result type when possible.
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004699 if (!ARCError && RTC == Sema::RTC_Compatible &&
Douglas Gregorbab8a962011-09-08 01:46:34 +00004700 !ObjCMethod->hasRelatedResultType() &&
4701 LangOpts.ObjCInferRelatedResultType) {
Douglas Gregor33823722011-06-11 01:09:30 +00004702 bool InferRelatedResultType = false;
4703 switch (ObjCMethod->getMethodFamily()) {
4704 case OMF_None:
4705 case OMF_copy:
4706 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +00004707 case OMF_finalize:
Douglas Gregor33823722011-06-11 01:09:30 +00004708 case OMF_mutableCopy:
4709 case OMF_release:
4710 case OMF_retainCount:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00004711 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00004712 case OMF_performSelector:
Douglas Gregor33823722011-06-11 01:09:30 +00004713 break;
4714
4715 case OMF_alloc:
4716 case OMF_new:
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00004717 InferRelatedResultType = ObjCMethod->isClassMethod();
Douglas Gregor33823722011-06-11 01:09:30 +00004718 break;
4719
4720 case OMF_init:
4721 case OMF_autorelease:
4722 case OMF_retain:
4723 case OMF_self:
4724 InferRelatedResultType = ObjCMethod->isInstanceMethod();
4725 break;
4726 }
4727
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00004728 if (InferRelatedResultType &&
4729 !ObjCMethod->getReturnType()->isObjCIndependentClassType())
Douglas Gregor33823722011-06-11 01:09:30 +00004730 ObjCMethod->SetRelatedResultType();
Douglas Gregor33823722011-06-11 01:09:30 +00004731 }
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00004732
Alex Lorenza8a372d2017-04-27 10:43:48 +00004733 if (MethodDefinition &&
4734 Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
4735 checkObjCMethodX86VectorTypes(*this, ObjCMethod);
4736
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00004737 ActOnDocumentableDecl(ObjCMethod);
4738
John McCall48871652010-08-21 09:40:31 +00004739 return ObjCMethod;
Chris Lattnerda463fe2007-12-12 07:09:47 +00004740}
4741
Chris Lattner438e5012008-12-17 07:13:27 +00004742bool Sema::CheckObjCDeclScope(Decl *D) {
Fariborz Jahanianf36734d2011-08-22 18:34:22 +00004743 // Following is also an error. But it is caused by a missing @end
4744 // and diagnostic is issued elsewhere.
Argyrios Kyrtzidis822c4332012-03-23 23:24:23 +00004745 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004746 return false;
Argyrios Kyrtzidis822c4332012-03-23 23:24:23 +00004747
4748 // If we switched context to translation unit while we are still lexically in
4749 // an objc container, it means the parser missed emitting an error.
4750 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
4751 return false;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004752
Anders Carlssona6b508a2008-11-04 16:57:32 +00004753 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
4754 D->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004755
Anders Carlssona6b508a2008-11-04 16:57:32 +00004756 return true;
4757}
Chris Lattner438e5012008-12-17 07:13:27 +00004758
James Dennett634962f2012-06-14 21:40:34 +00004759/// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
Chris Lattner438e5012008-12-17 07:13:27 +00004760/// instance variables of ClassName into Decls.
John McCall48871652010-08-21 09:40:31 +00004761void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
Chris Lattner438e5012008-12-17 07:13:27 +00004762 IdentifierInfo *ClassName,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004763 SmallVectorImpl<Decl*> &Decls) {
Chris Lattner438e5012008-12-17 07:13:27 +00004764 // Check that ClassName is a valid class
Douglas Gregorb2ccf012010-04-15 22:33:43 +00004765 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
Chris Lattner438e5012008-12-17 07:13:27 +00004766 if (!Class) {
4767 Diag(DeclStart, diag::err_undef_interface) << ClassName;
4768 return;
4769 }
John McCall5fb5df92012-06-20 06:18:46 +00004770 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanianece1b2b2009-04-21 20:28:41 +00004771 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
4772 return;
4773 }
Mike Stump11289f42009-09-09 15:08:12 +00004774
Chris Lattner438e5012008-12-17 07:13:27 +00004775 // Collect the instance variables
Jordy Rosea91768e2011-07-22 02:08:32 +00004776 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004777 Context.DeepCollectObjCIvars(Class, true, Ivars);
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004778 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004779 for (unsigned i = 0; i < Ivars.size(); i++) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00004780 const FieldDecl* ID = Ivars[i];
John McCall48871652010-08-21 09:40:31 +00004781 RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
Abramo Bagnaradff19302011-03-08 08:55:46 +00004782 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
4783 /*FIXME: StartL=*/ID->getLocation(),
4784 ID->getLocation(),
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004785 ID->getIdentifier(), ID->getType(),
4786 ID->getBitWidth());
John McCall48871652010-08-21 09:40:31 +00004787 Decls.push_back(FD);
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004788 }
Mike Stump11289f42009-09-09 15:08:12 +00004789
Chris Lattner438e5012008-12-17 07:13:27 +00004790 // Introduce all of these fields into the appropriate scope.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004791 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
Chris Lattner438e5012008-12-17 07:13:27 +00004792 D != Decls.end(); ++D) {
John McCall48871652010-08-21 09:40:31 +00004793 FieldDecl *FD = cast<FieldDecl>(*D);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004794 if (getLangOpts().CPlusPlus)
George Burgess IV00f70bd2018-03-01 05:43:23 +00004795 PushOnScopeChains(FD, S);
John McCall48871652010-08-21 09:40:31 +00004796 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004797 Record->addDecl(FD);
Chris Lattner438e5012008-12-17 07:13:27 +00004798 }
4799}
4800
Douglas Gregorf3564192010-04-26 17:32:49 +00004801/// \brief Build a type-check a new Objective-C exception variable declaration.
Abramo Bagnaradff19302011-03-08 08:55:46 +00004802VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
4803 SourceLocation StartLoc,
4804 SourceLocation IdLoc,
4805 IdentifierInfo *Id,
Douglas Gregorf3564192010-04-26 17:32:49 +00004806 bool Invalid) {
4807 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
4808 // duration shall not be qualified by an address-space qualifier."
4809 // Since all parameters have automatic store duration, they can not have
4810 // an address space.
Alexander Richardson6d989432017-10-15 18:48:14 +00004811 if (T.getAddressSpace() != LangAS::Default) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004812 Diag(IdLoc, diag::err_arg_with_address_space);
Douglas Gregorf3564192010-04-26 17:32:49 +00004813 Invalid = true;
4814 }
4815
4816 // An @catch parameter must be an unqualified object pointer type;
4817 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
4818 if (Invalid) {
4819 // Don't do any further checking.
Douglas Gregorf4e837f2010-04-26 17:57:08 +00004820 } else if (T->isDependentType()) {
4821 // Okay: we don't know what this type will instantiate to.
Douglas Gregorf3564192010-04-26 17:32:49 +00004822 } else if (!T->isObjCObjectPointerType()) {
4823 Invalid = true;
Abramo Bagnaradff19302011-03-08 08:55:46 +00004824 Diag(IdLoc ,diag::err_catch_param_not_objc_type);
Douglas Gregorf3564192010-04-26 17:32:49 +00004825 } else if (T->isObjCQualifiedIdType()) {
4826 Invalid = true;
Abramo Bagnaradff19302011-03-08 08:55:46 +00004827 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00004828 }
4829
Abramo Bagnaradff19302011-03-08 08:55:46 +00004830 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004831 T, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00004832 New->setExceptionVariable(true);
4833
Douglas Gregor8ca0c642011-12-10 01:22:52 +00004834 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004835 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
Douglas Gregor8ca0c642011-12-10 01:22:52 +00004836 Invalid = true;
4837
Douglas Gregorf3564192010-04-26 17:32:49 +00004838 if (Invalid)
4839 New->setInvalidDecl();
4840 return New;
4841}
4842
John McCall48871652010-08-21 09:40:31 +00004843Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
Douglas Gregorf3564192010-04-26 17:32:49 +00004844 const DeclSpec &DS = D.getDeclSpec();
4845
4846 // We allow the "register" storage class on exception variables because
4847 // GCC did, but we drop it completely. Any other storage class is an error.
4848 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
4849 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
4850 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
Richard Smithb4a9e862013-04-12 22:46:28 +00004851 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
Douglas Gregorf3564192010-04-26 17:32:49 +00004852 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
Richard Smithb4a9e862013-04-12 22:46:28 +00004853 << DeclSpec::getSpecifierName(SCS);
4854 }
Richard Smith62f19e72016-06-25 00:15:56 +00004855 if (DS.isInlineSpecified())
4856 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004857 << getLangOpts().CPlusPlus17;
Richard Smithb4a9e862013-04-12 22:46:28 +00004858 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
4859 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
4860 diag::err_invalid_thread)
4861 << DeclSpec::getSpecifierName(TSCS);
Douglas Gregorf3564192010-04-26 17:32:49 +00004862 D.getMutableDeclSpec().ClearStorageClassSpecs();
4863
Richard Smithb1402ae2013-03-18 22:52:47 +00004864 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregorf3564192010-04-26 17:32:49 +00004865
4866 // Check that there are no default arguments inside the type of this
4867 // exception object (C++ only).
David Blaikiebbafb8a2012-03-11 07:00:24 +00004868 if (getLangOpts().CPlusPlus)
Douglas Gregorf3564192010-04-26 17:32:49 +00004869 CheckExtraCXXDefaultArguments(D);
4870
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00004871 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00004872 QualType ExceptionType = TInfo->getType();
Douglas Gregorf3564192010-04-26 17:32:49 +00004873
Abramo Bagnaradff19302011-03-08 08:55:46 +00004874 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
4875 D.getSourceRange().getBegin(),
4876 D.getIdentifierLoc(),
4877 D.getIdentifier(),
Douglas Gregorf3564192010-04-26 17:32:49 +00004878 D.isInvalidType());
4879
4880 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
4881 if (D.getCXXScopeSpec().isSet()) {
4882 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
4883 << D.getCXXScopeSpec().getRange();
4884 New->setInvalidDecl();
4885 }
4886
4887 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00004888 S->AddDecl(New);
Douglas Gregorf3564192010-04-26 17:32:49 +00004889 if (D.getIdentifier())
4890 IdResolver.AddDecl(New);
4891
4892 ProcessDeclAttributes(S, New, D);
4893
4894 if (New->hasAttr<BlocksAttr>())
4895 Diag(New->getLocation(), diag::err_block_on_nonlocal);
John McCall48871652010-08-21 09:40:31 +00004896 return New;
Douglas Gregore11ee112010-04-23 23:01:43 +00004897}
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004898
4899/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004900/// initialization.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004901void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004902 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004903 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
4904 Iv= Iv->getNextIvar()) {
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004905 QualType QT = Context.getBaseElementType(Iv->getType());
Douglas Gregor527786e2010-05-20 02:24:22 +00004906 if (QT->isRecordType())
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004907 Ivars.push_back(Iv);
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004908 }
4909}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004910
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004911void Sema::DiagnoseUseOfUnimplementedSelectors() {
Douglas Gregor72e357f2011-07-28 14:54:22 +00004912 // Load referenced selectors from the external source.
4913 if (ExternalSource) {
4914 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
4915 ExternalSource->ReadReferencedSelectors(Sels);
4916 for (unsigned I = 0, N = Sels.size(); I != N; ++I)
4917 ReferencedSelectors[Sels[I].first] = Sels[I].second;
4918 }
4919
Fariborz Jahanianc9b7c202011-02-04 23:19:27 +00004920 // Warning will be issued only when selector table is
4921 // generated (which means there is at lease one implementation
4922 // in the TU). This is to match gcc's behavior.
4923 if (ReferencedSelectors.empty() ||
4924 !Context.AnyObjCImplementation())
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004925 return;
Chandler Carruth12c8f652015-03-27 00:55:05 +00004926 for (auto &SelectorAndLocation : ReferencedSelectors) {
4927 Selector Sel = SelectorAndLocation.first;
4928 SourceLocation Loc = SelectorAndLocation.second;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004929 if (!LookupImplementedMethodInGlobalPool(Sel))
Chandler Carruth12c8f652015-03-27 00:55:05 +00004930 Diag(Loc, diag::warn_unimplemented_selector) << Sel;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004931 }
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004932}
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004933
4934ObjCIvarDecl *
4935Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4936 const ObjCPropertyDecl *&PDecl) const {
Fariborz Jahanian1cc7ae12014-01-02 17:24:32 +00004937 if (Method->isClassMethod())
Craig Topperc3ec1492014-05-26 06:22:03 +00004938 return nullptr;
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004939 const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
4940 if (!IDecl)
Craig Topperc3ec1492014-05-26 06:22:03 +00004941 return nullptr;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004942 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
4943 /*shallowCategoryLookup=*/false,
4944 /*followSuper=*/false);
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004945 if (!Method || !Method->isPropertyAccessor())
Craig Topperc3ec1492014-05-26 06:22:03 +00004946 return nullptr;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004947 if ((PDecl = Method->findPropertyDecl()))
Fariborz Jahanian122d94f2014-01-27 22:27:43 +00004948 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
4949 // property backing ivar must belong to property's class
4950 // or be a private ivar in class's implementation.
4951 // FIXME. fix the const-ness issue.
4952 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
4953 IV->getIdentifier());
4954 return IV;
4955 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004956 return nullptr;
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004957}
4958
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004959namespace {
4960 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
4961 /// accessor references the backing ivar.
Argyrios Kyrtzidis98045c12014-01-03 19:53:09 +00004962 class UnusedBackingIvarChecker :
Richard Smith50668452015-11-24 03:55:01 +00004963 public RecursiveASTVisitor<UnusedBackingIvarChecker> {
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004964 public:
4965 Sema &S;
4966 const ObjCMethodDecl *Method;
4967 const ObjCIvarDecl *IvarD;
4968 bool AccessedIvar;
4969 bool InvokedSelfMethod;
4970
4971 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
4972 const ObjCIvarDecl *IvarD)
4973 : S(S), Method(Method), IvarD(IvarD),
4974 AccessedIvar(false), InvokedSelfMethod(false) {
4975 assert(IvarD);
4976 }
4977
4978 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
4979 if (E->getDecl() == IvarD) {
4980 AccessedIvar = true;
4981 return false;
4982 }
4983 return true;
4984 }
4985
4986 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
4987 if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
4988 S.isSelfExpr(E->getInstanceReceiver(), Method)) {
4989 InvokedSelfMethod = true;
4990 }
4991 return true;
4992 }
4993 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00004994} // end anonymous namespace
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004995
4996void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
4997 const ObjCImplementationDecl *ImplD) {
4998 if (S->hasUnrecoverableErrorOccurred())
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004999 return;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005000
Aaron Ballmanf26acce2014-03-13 19:50:17 +00005001 for (const auto *CurMethod : ImplD->instance_methods()) {
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005002 unsigned DIAG = diag::warn_unused_property_backing_ivar;
5003 SourceLocation Loc = CurMethod->getLocation();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005004 if (Diags.isIgnored(DIAG, Loc))
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005005 continue;
5006
5007 const ObjCPropertyDecl *PDecl;
5008 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
5009 if (!IV)
5010 continue;
5011
5012 UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
5013 Checker.TraverseStmt(CurMethod->getBody());
5014 if (Checker.AccessedIvar)
5015 continue;
5016
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00005017 // Do not issue this warning if backing ivar is used somewhere and accessor
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005018 // implementation makes a self call. This is to prevent false positive in
5019 // cases where the ivar is accessed by another method that the accessor
5020 // delegates to.
5021 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
Argyrios Kyrtzidisd8a35322014-01-03 19:39:23 +00005022 Diag(Loc, DIAG) << IV;
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00005023 Diag(PDecl->getLocation(), diag::note_property_declare);
5024 }
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00005025 }
5026}