blob: 6b33f7c64ced8bf0e23c95e87c8505e344e8df1f [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 }
David Blaikiebbafb8a2012-03-11 07:00:24 +0000159 if (getLangOpts().ObjCAutoRefCount) {
Akira Hatanaka7d85b8f2017-09-20 05:39:18 +0000160 Diags.setSeverity(diag::warn_nsreturns_retained_attribute_mismatch,
161 diag::Severity::Error, SourceLocation());
162 Diags.setSeverity(diag::warn_nsconsumed_attribute_mismatch,
163 diag::Severity::Error, SourceLocation());
164 }
165
166 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
167 Overridden->hasAttr<NSReturnsRetainedAttr>())) {
168 Diag(NewMethod->getLocation(),
169 diag::warn_nsreturns_retained_attribute_mismatch) << 1;
170 Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
171 }
172 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
173 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
174 Diag(NewMethod->getLocation(),
175 diag::warn_nsreturns_retained_attribute_mismatch) << 0;
176 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>()) {
188 Diag(newDecl->getLocation(), diag::warn_nsconsumed_attribute_mismatch);
189 Diag(oldDecl->getLocation(), diag::note_previous_decl) << "parameter";
Fariborz Jahanianac8dbf02011-09-27 22:35:36 +0000190 }
Akira Hatanaka98a49332017-09-22 00:41:05 +0000191
192 // A parameter of the overriding method should be annotated with noescape
193 // if the corresponding parameter of the overridden method is annotated.
194 if (oldDecl->hasAttr<NoEscapeAttr>() && !newDecl->hasAttr<NoEscapeAttr>()) {
195 Diag(newDecl->getLocation(),
196 diag::warn_overriding_method_missing_noescape);
197 Diag(oldDecl->getLocation(), diag::note_overridden_marked_noescape);
198 }
Fariborz Jahanianac8dbf02011-09-27 22:35:36 +0000199 }
Douglas Gregor33823722011-06-11 01:09:30 +0000200}
201
John McCall31168b02011-06-15 23:02:42 +0000202/// \brief Check a method declaration for compatibility with the Objective-C
203/// ARC conventions.
John McCalle48f3892013-04-04 01:38:37 +0000204bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
John McCall31168b02011-06-15 23:02:42 +0000205 ObjCMethodFamily family = method->getMethodFamily();
206 switch (family) {
207 case OMF_None:
Nico Weber1fb82662011-08-28 22:35:17 +0000208 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +0000209 case OMF_retain:
210 case OMF_release:
211 case OMF_autorelease:
212 case OMF_retainCount:
213 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +0000214 case OMF_initialize:
John McCalld2930c22011-07-22 02:45:48 +0000215 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +0000216 return false;
217
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000218 case OMF_dealloc:
Alp Toker314cc812014-01-25 16:55:45 +0000219 if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
Aaron Ballman41b10ac2014-08-01 13:20:09 +0000220 SourceRange ResultTypeRange = method->getReturnTypeSourceRange();
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000221 if (ResultTypeRange.isInvalid())
Richard Smithf8812672016-12-02 22:38:31 +0000222 Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
Alp Toker314cc812014-01-25 16:55:45 +0000223 << method->getReturnType()
224 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000225 else
Richard Smithf8812672016-12-02 22:38:31 +0000226 Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
Alp Toker314cc812014-01-25 16:55:45 +0000227 << method->getReturnType()
228 << FixItHint::CreateReplacement(ResultTypeRange, "void");
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000229 return true;
230 }
231 return false;
232
John McCall31168b02011-06-15 23:02:42 +0000233 case OMF_init:
234 // If the method doesn't obey the init rules, don't bother annotating it.
John McCalle48f3892013-04-04 01:38:37 +0000235 if (checkInitMethod(method, QualType()))
John McCall31168b02011-06-15 23:02:42 +0000236 return true;
237
Aaron Ballman36a53502014-01-16 13:03:14 +0000238 method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
John McCall31168b02011-06-15 23:02:42 +0000239
240 // Don't add a second copy of this attribute, but otherwise don't
241 // let it be suppressed.
242 if (method->hasAttr<NSReturnsRetainedAttr>())
243 return false;
244 break;
245
246 case OMF_alloc:
247 case OMF_copy:
248 case OMF_mutableCopy:
249 case OMF_new:
250 if (method->hasAttr<NSReturnsRetainedAttr>() ||
251 method->hasAttr<NSReturnsNotRetainedAttr>() ||
252 method->hasAttr<NSReturnsAutoreleasedAttr>())
253 return false;
254 break;
255 }
256
Aaron Ballman36a53502014-01-16 13:03:14 +0000257 method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
John McCall31168b02011-06-15 23:02:42 +0000258 return false;
259}
260
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000261static void DiagnoseObjCImplementedDeprecations(Sema &S, const NamedDecl *ND,
262 SourceLocation ImplLoc) {
263 if (!ND)
264 return;
265 bool IsCategory = false;
Alex Lorenze1088dc2017-07-13 16:37:11 +0000266 AvailabilityResult Availability = ND->getAvailability();
267 if (Availability != AR_Deprecated) {
Eric Christopher7aba9782017-07-14 01:42:57 +0000268 if (isa<ObjCMethodDecl>(ND)) {
Alex Lorenze1088dc2017-07-13 16:37:11 +0000269 if (Availability != AR_Unavailable)
270 return;
271 // Warn about implementing unavailable methods.
272 S.Diag(ImplLoc, diag::warn_unavailable_def);
273 S.Diag(ND->getLocation(), diag::note_method_declared_at)
274 << ND->getDeclName();
275 return;
276 }
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000277 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND)) {
278 if (!CD->getClassInterface()->isDeprecated())
279 return;
280 ND = CD->getClassInterface();
281 IsCategory = true;
282 } else
283 return;
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000284 }
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000285 S.Diag(ImplLoc, diag::warn_deprecated_def)
286 << (isa<ObjCMethodDecl>(ND)
287 ? /*Method*/ 0
288 : isa<ObjCCategoryDecl>(ND) || IsCategory ? /*Category*/ 2
289 : /*Class*/ 1);
290 if (isa<ObjCMethodDecl>(ND))
291 S.Diag(ND->getLocation(), diag::note_method_declared_at)
292 << ND->getDeclName();
293 else
294 S.Diag(ND->getLocation(), diag::note_previous_decl)
295 << (isa<ObjCCategoryDecl>(ND) ? "category" : "class");
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000296}
297
Fariborz Jahanianbd0642f2011-08-31 17:37:55 +0000298/// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
299/// pool.
300void Sema::AddAnyMethodToGlobalPool(Decl *D) {
301 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
302
303 // If we don't have a valid method decl, simply return.
304 if (!MDecl)
305 return;
306 if (MDecl->isInstanceMethod())
307 AddInstanceMethodToGlobalPool(MDecl, true);
308 else
309 AddFactoryMethodToGlobalPool(MDecl, true);
310}
311
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000312/// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
313/// has explicit ownership attribute; false otherwise.
314static bool
315HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
316 QualType T = Param->getType();
317
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000318 if (const PointerType *PT = T->getAs<PointerType>()) {
319 T = PT->getPointeeType();
320 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
321 T = RT->getPointeeType();
322 } else {
323 return true;
324 }
325
326 // If we have a lifetime qualifier, but it's local, we must have
327 // inferred it. So, it is implicit.
328 return !T.getLocalQualifiers().hasObjCLifetime();
329}
330
Fariborz Jahanian18d0a5d2012-08-08 23:41:08 +0000331/// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
332/// and user declared, in the method definition's AST.
333void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000334 assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
John McCall48871652010-08-21 09:40:31 +0000335 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
Fariborz Jahanian577574a2012-07-02 23:37:09 +0000336
Steve Naroff542cd5d2008-07-25 17:57:26 +0000337 // If we don't have a valid method decl, simply return.
338 if (!MDecl)
339 return;
Steve Naroff1d2538c2007-12-18 01:30:32 +0000340
Chris Lattnerda463fe2007-12-12 07:09:47 +0000341 // Allow all of Sema to see that we are entering a method definition.
Douglas Gregor91f84212008-12-11 16:49:14 +0000342 PushDeclContext(FnBodyScope, MDecl);
Douglas Gregor9a28e842010-03-01 23:15:13 +0000343 PushFunctionScope();
344
Chris Lattnerda463fe2007-12-12 07:09:47 +0000345 // Create Decl objects for each parameter, entrring them in the scope for
346 // binding to their use.
Chris Lattnerda463fe2007-12-12 07:09:47 +0000347
348 // Insert the invisible arguments, self and _cmd!
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000349 MDecl->createImplicitParams(Context, MDecl->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000350
Daniel Dunbar279d1cc2008-08-26 06:07:48 +0000351 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
352 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000353
Reid Kleckner5a115802013-06-24 14:38:26 +0000354 // The ObjC parser requires parameter names so there's no need to check.
David Majnemer59f77922016-06-24 04:05:48 +0000355 CheckParmsForFunctionDef(MDecl->parameters(),
Reid Kleckner5a115802013-06-24 14:38:26 +0000356 /*CheckParameterNames=*/false);
357
Chris Lattner58258242008-04-10 02:22:51 +0000358 // Introduce all of the other parameters into this scope.
David Majnemer59f77922016-06-24 04:05:48 +0000359 for (auto *Param : MDecl->parameters()) {
Fariborz Jahanianb3e87122010-09-17 22:07:07 +0000360 if (!Param->isInvalidDecl() &&
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000361 getLangOpts().ObjCAutoRefCount &&
362 !HasExplicitOwnershipAttr(*this, Param))
363 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
364 Param->getType();
Fariborz Jahaniancd278ff2012-08-30 23:56:02 +0000365
Aaron Ballman43b68be2014-03-07 17:50:17 +0000366 if (Param->getIdentifier())
367 PushOnScopeChains(Param, FnBodyScope);
Fariborz Jahanianb3e87122010-09-17 22:07:07 +0000368 }
John McCall31168b02011-06-15 23:02:42 +0000369
370 // In ARC, disallow definition of retain/release/autorelease/retainCount
David Blaikiebbafb8a2012-03-11 07:00:24 +0000371 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +0000372 switch (MDecl->getMethodFamily()) {
373 case OMF_retain:
374 case OMF_retainCount:
375 case OMF_release:
376 case OMF_autorelease:
377 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
Fariborz Jahanian39d1c422013-05-16 19:08:44 +0000378 << 0 << MDecl->getSelector();
John McCall31168b02011-06-15 23:02:42 +0000379 break;
380
381 case OMF_None:
382 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +0000383 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +0000384 case OMF_alloc:
385 case OMF_init:
386 case OMF_mutableCopy:
387 case OMF_copy:
388 case OMF_new:
389 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +0000390 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +0000391 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +0000392 break;
393 }
394 }
395
Nico Weber715abaf2011-08-22 17:25:57 +0000396 // Warn on deprecated methods under -Wdeprecated-implementations,
397 // and prepare for warning on missing super calls.
398 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
Fariborz Jahanian566fff02012-09-07 23:46:23 +0000399 ObjCMethodDecl *IMD =
400 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
401
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000402 if (IMD) {
403 ObjCImplDecl *ImplDeclOfMethodDef =
404 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
405 ObjCContainerDecl *ContDeclOfMethodDecl =
406 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
Craig Topperc3ec1492014-05-26 06:22:03 +0000407 ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000408 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
409 ImplDeclOfMethodDecl = OID->getImplementation();
Fariborz Jahanianed39e7c2014-03-18 16:25:22 +0000410 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
411 if (CD->IsClassExtension()) {
412 if (ObjCInterfaceDecl *OID = CD->getClassInterface())
413 ImplDeclOfMethodDecl = OID->getImplementation();
414 } else
415 ImplDeclOfMethodDecl = CD->getImplementation();
Fariborz Jahanian19a08bb2014-03-18 00:10:37 +0000416 }
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000417 // No need to issue deprecated warning if deprecated mehod in class/category
418 // is being implemented in its own implementation (no overriding is involved).
Fariborz Jahanianed39e7c2014-03-18 16:25:22 +0000419 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000420 DiagnoseObjCImplementedDeprecations(*this, IMD, MDecl->getLocation());
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000421 }
Nico Weber715abaf2011-08-22 17:25:57 +0000422
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000423 if (MDecl->getMethodFamily() == OMF_init) {
424 if (MDecl->isDesignatedInitializerForTheInterface()) {
425 getCurFunction()->ObjCIsDesignatedInit = true;
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +0000426 getCurFunction()->ObjCWarnForNoDesignatedInitChain =
Craig Topperc3ec1492014-05-26 06:22:03 +0000427 IC->getSuperClass() != nullptr;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000428 } else if (IC->hasDesignatedInitializers()) {
429 getCurFunction()->ObjCIsSecondaryInit = true;
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +0000430 getCurFunction()->ObjCWarnForNoInitDelegation = true;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000431 }
432 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +0000433
Nico Weber1fb82662011-08-28 22:35:17 +0000434 // If this is "dealloc" or "finalize", set some bit here.
Nico Weber715abaf2011-08-22 17:25:57 +0000435 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
436 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
437 // Only do this if the current class actually has a superclass.
Jordan Rosed03d99d2013-03-05 01:27:54 +0000438 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
Jordan Rose2afd6612012-10-19 16:05:26 +0000439 ObjCMethodFamily Family = MDecl->getMethodFamily();
440 if (Family == OMF_dealloc) {
441 if (!(getLangOpts().ObjCAutoRefCount ||
442 getLangOpts().getGC() == LangOptions::GCOnly))
443 getCurFunction()->ObjCShouldCallSuper = true;
444
445 } else if (Family == OMF_finalize) {
446 if (Context.getLangOpts().getGC() != LangOptions::NonGC)
447 getCurFunction()->ObjCShouldCallSuper = true;
448
Fariborz Jahaniance4bbb22013-11-05 00:28:21 +0000449 } else {
Jordan Rose2afd6612012-10-19 16:05:26 +0000450 const ObjCMethodDecl *SuperMethod =
Jordan Rosed03d99d2013-03-05 01:27:54 +0000451 SuperClass->lookupMethod(MDecl->getSelector(),
452 MDecl->isInstanceMethod());
Jordan Rose2afd6612012-10-19 16:05:26 +0000453 getCurFunction()->ObjCShouldCallSuper =
454 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
Fariborz Jahaniand6876b22012-09-10 18:04:25 +0000455 }
Nico Weber1fb82662011-08-28 22:35:17 +0000456 }
Nico Weber715abaf2011-08-22 17:25:57 +0000457 }
Chris Lattnerda463fe2007-12-12 07:09:47 +0000458}
459
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000460namespace {
461
462// Callback to only accept typo corrections that are Objective-C classes.
463// If an ObjCInterfaceDecl* is given to the constructor, then the validation
464// function will reject corrections to that class.
465class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback {
466 public:
Craig Topperc3ec1492014-05-26 06:22:03 +0000467 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000468 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
469 : CurrentIDecl(IDecl) {}
470
Craig Toppere14c0f82014-03-12 04:55:44 +0000471 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000472 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
473 return ID && !declaresSameEntity(ID, CurrentIDecl);
474 }
475
476 private:
477 ObjCInterfaceDecl *CurrentIDecl;
478};
479
Hans Wennborgdcfba332015-10-06 23:40:43 +0000480} // end anonymous namespace
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000481
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +0000482static void diagnoseUseOfProtocols(Sema &TheSema,
483 ObjCContainerDecl *CD,
484 ObjCProtocolDecl *const *ProtoRefs,
485 unsigned NumProtoRefs,
486 const SourceLocation *ProtoLocs) {
487 assert(ProtoRefs);
488 // Diagnose availability in the context of the ObjC container.
489 Sema::ContextRAII SavedContext(TheSema, CD);
490 for (unsigned i = 0; i < NumProtoRefs; ++i) {
Alex Lorenzcdd596f2017-07-07 09:15:29 +0000491 (void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i],
492 /*UnknownObjCClass=*/nullptr,
493 /*ObjCPropertyAccess=*/false,
494 /*AvoidPartialAvailabilityChecks=*/true);
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +0000495 }
496}
497
Douglas Gregore9d95f12015-07-07 03:57:35 +0000498void Sema::
499ActOnSuperClassOfClassInterface(Scope *S,
500 SourceLocation AtInterfaceLoc,
501 ObjCInterfaceDecl *IDecl,
502 IdentifierInfo *ClassName,
503 SourceLocation ClassLoc,
504 IdentifierInfo *SuperName,
505 SourceLocation SuperLoc,
506 ArrayRef<ParsedType> SuperTypeArgs,
507 SourceRange SuperTypeArgsRange) {
508 // Check if a different kind of symbol declared in this scope.
509 NamedDecl *PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
510 LookupOrdinaryName);
511
512 if (!PrevDecl) {
513 // Try to correct for a typo in the superclass name without correcting
514 // to the class we're defining.
515 if (TypoCorrection Corrected = CorrectTypo(
516 DeclarationNameInfo(SuperName, SuperLoc),
517 LookupOrdinaryName, TUScope,
Hans Wennborgdcfba332015-10-06 23:40:43 +0000518 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(IDecl),
Douglas Gregore9d95f12015-07-07 03:57:35 +0000519 CTK_ErrorRecovery)) {
520 diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
521 << SuperName << ClassName);
522 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
523 }
524 }
525
526 if (declaresSameEntity(PrevDecl, IDecl)) {
527 Diag(SuperLoc, diag::err_recursive_superclass)
528 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
529 IDecl->setEndOfDefinitionLoc(ClassLoc);
530 } else {
531 ObjCInterfaceDecl *SuperClassDecl =
532 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
533 QualType SuperClassType;
534
535 // Diagnose classes that inherit from deprecated classes.
536 if (SuperClassDecl) {
537 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
538 SuperClassType = Context.getObjCInterfaceType(SuperClassDecl);
539 }
540
Hans Wennborgdcfba332015-10-06 23:40:43 +0000541 if (PrevDecl && !SuperClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +0000542 // The previous declaration was not a class decl. Check if we have a
543 // typedef. If we do, get the underlying class type.
544 if (const TypedefNameDecl *TDecl =
545 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
546 QualType T = TDecl->getUnderlyingType();
547 if (T->isObjCObjectType()) {
548 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
549 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
550 SuperClassType = Context.getTypeDeclType(TDecl);
551
552 // This handles the following case:
553 // @interface NewI @end
554 // typedef NewI DeprI __attribute__((deprecated("blah")))
555 // @interface SI : DeprI /* warn here */ @end
556 (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
557 }
558 }
559 }
560
561 // This handles the following case:
562 //
563 // typedef int SuperClass;
564 // @interface MyClass : SuperClass {} @end
565 //
566 if (!SuperClassDecl) {
567 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
568 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
569 }
570 }
571
572 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
573 if (!SuperClassDecl)
574 Diag(SuperLoc, diag::err_undef_superclass)
575 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
576 else if (RequireCompleteType(SuperLoc,
577 SuperClassType,
578 diag::err_forward_superclass,
579 SuperClassDecl->getDeclName(),
580 ClassName,
581 SourceRange(AtInterfaceLoc, ClassLoc))) {
Hans Wennborgdcfba332015-10-06 23:40:43 +0000582 SuperClassDecl = nullptr;
Douglas Gregore9d95f12015-07-07 03:57:35 +0000583 SuperClassType = QualType();
584 }
585 }
586
587 if (SuperClassType.isNull()) {
588 assert(!SuperClassDecl && "Failed to set SuperClassType?");
589 return;
590 }
591
592 // Handle type arguments on the superclass.
593 TypeSourceInfo *SuperClassTInfo = nullptr;
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000594 if (!SuperTypeArgs.empty()) {
595 TypeResult fullSuperClassType = actOnObjCTypeArgsAndProtocolQualifiers(
596 S,
597 SuperLoc,
598 CreateParsedType(SuperClassType,
599 nullptr),
600 SuperTypeArgsRange.getBegin(),
601 SuperTypeArgs,
602 SuperTypeArgsRange.getEnd(),
603 SourceLocation(),
604 { },
605 { },
606 SourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +0000607 if (!fullSuperClassType.isUsable())
608 return;
609
610 SuperClassType = GetTypeFromParser(fullSuperClassType.get(),
611 &SuperClassTInfo);
612 }
613
614 if (!SuperClassTInfo) {
615 SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType,
616 SuperLoc);
617 }
618
619 IDecl->setSuperClass(SuperClassTInfo);
620 IDecl->setEndOfDefinitionLoc(SuperClassTInfo->getTypeLoc().getLocEnd());
621 }
622}
623
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000624DeclResult Sema::actOnObjCTypeParam(Scope *S,
625 ObjCTypeParamVariance variance,
626 SourceLocation varianceLoc,
627 unsigned index,
Douglas Gregore83b9562015-07-07 03:57:53 +0000628 IdentifierInfo *paramName,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000629 SourceLocation paramLoc,
630 SourceLocation colonLoc,
631 ParsedType parsedTypeBound) {
632 // If there was an explicitly-provided type bound, check it.
633 TypeSourceInfo *typeBoundInfo = nullptr;
634 if (parsedTypeBound) {
635 // The type bound can be any Objective-C pointer type.
636 QualType typeBound = GetTypeFromParser(parsedTypeBound, &typeBoundInfo);
637 if (typeBound->isObjCObjectPointerType()) {
638 // okay
639 } else if (typeBound->isObjCObjectType()) {
640 // The user forgot the * on an Objective-C pointer type, e.g.,
641 // "T : NSView".
Craig Topper07fa1762015-11-15 02:31:46 +0000642 SourceLocation starLoc = getLocForEndOfToken(
Douglas Gregor85f3f952015-07-07 03:57:15 +0000643 typeBoundInfo->getTypeLoc().getEndLoc());
644 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
645 diag::err_objc_type_param_bound_missing_pointer)
646 << typeBound << paramName
647 << FixItHint::CreateInsertion(starLoc, " *");
648
649 // Create a new type location builder so we can update the type
650 // location information we have.
651 TypeLocBuilder builder;
652 builder.pushFullCopy(typeBoundInfo->getTypeLoc());
653
654 // Create the Objective-C pointer type.
655 typeBound = Context.getObjCObjectPointerType(typeBound);
656 ObjCObjectPointerTypeLoc newT
657 = builder.push<ObjCObjectPointerTypeLoc>(typeBound);
658 newT.setStarLoc(starLoc);
659
660 // Form the new type source information.
661 typeBoundInfo = builder.getTypeSourceInfo(Context, typeBound);
662 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +0000663 // Not a valid type bound.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000664 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
665 diag::err_objc_type_param_bound_nonobject)
666 << typeBound << paramName;
667
668 // Forget the bound; we'll default to id later.
669 typeBoundInfo = nullptr;
670 }
Douglas Gregore83b9562015-07-07 03:57:53 +0000671
John McCall69975252015-09-23 22:14:21 +0000672 // Type bounds cannot have qualifiers (even indirectly) or explicit
673 // nullability.
Douglas Gregore83b9562015-07-07 03:57:53 +0000674 if (typeBoundInfo) {
John McCall69975252015-09-23 22:14:21 +0000675 QualType typeBound = typeBoundInfo->getType();
676 TypeLoc qual = typeBoundInfo->getTypeLoc().findExplicitQualifierLoc();
677 if (qual || typeBound.hasQualifiers()) {
678 bool diagnosed = false;
679 SourceRange rangeToRemove;
680 if (qual) {
681 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
682 rangeToRemove = attr.getLocalSourceRange();
683 if (attr.getTypePtr()->getImmediateNullability()) {
684 Diag(attr.getLocStart(),
685 diag::err_objc_type_param_bound_explicit_nullability)
686 << paramName << typeBound
687 << FixItHint::CreateRemoval(rangeToRemove);
688 diagnosed = true;
689 }
690 }
691 }
692
693 if (!diagnosed) {
694 Diag(qual ? qual.getLocStart()
695 : typeBoundInfo->getTypeLoc().getLocStart(),
696 diag::err_objc_type_param_bound_qualified)
697 << paramName << typeBound << typeBound.getQualifiers().getAsString()
698 << FixItHint::CreateRemoval(rangeToRemove);
699 }
700
701 // If the type bound has qualifiers other than CVR, we need to strip
702 // them or we'll probably assert later when trying to apply new
703 // qualifiers.
704 Qualifiers quals = typeBound.getQualifiers();
705 quals.removeCVRQualifiers();
706 if (!quals.empty()) {
707 typeBoundInfo =
708 Context.getTrivialTypeSourceInfo(typeBound.getUnqualifiedType());
709 }
Douglas Gregore83b9562015-07-07 03:57:53 +0000710 }
711 }
Douglas Gregor85f3f952015-07-07 03:57:15 +0000712 }
713
714 // If there was no explicit type bound (or we removed it due to an error),
715 // use 'id' instead.
716 if (!typeBoundInfo) {
717 colonLoc = SourceLocation();
718 typeBoundInfo = Context.getTrivialTypeSourceInfo(Context.getObjCIdType());
719 }
720
721 // Create the type parameter.
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000722 return ObjCTypeParamDecl::Create(Context, CurContext, variance, varianceLoc,
723 index, paramLoc, paramName, colonLoc,
724 typeBoundInfo);
Douglas Gregor85f3f952015-07-07 03:57:15 +0000725}
726
727ObjCTypeParamList *Sema::actOnObjCTypeParamList(Scope *S,
728 SourceLocation lAngleLoc,
729 ArrayRef<Decl *> typeParamsIn,
730 SourceLocation rAngleLoc) {
731 // We know that the array only contains Objective-C type parameters.
732 ArrayRef<ObjCTypeParamDecl *>
733 typeParams(
734 reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()),
735 typeParamsIn.size());
736
737 // Diagnose redeclarations of type parameters.
738 // We do this now because Objective-C type parameters aren't pushed into
739 // scope until later (after the instance variable block), but we want the
740 // diagnostics to occur right after we parse the type parameter list.
741 llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams;
742 for (auto typeParam : typeParams) {
743 auto known = knownParams.find(typeParam->getIdentifier());
744 if (known != knownParams.end()) {
745 Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl)
746 << typeParam->getIdentifier()
747 << SourceRange(known->second->getLocation());
748
749 typeParam->setInvalidDecl();
750 } else {
751 knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam));
752
753 // Push the type parameter into scope.
754 PushOnScopeChains(typeParam, S, /*AddToContext=*/false);
755 }
756 }
757
758 // Create the parameter list.
759 return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc);
760}
761
762void Sema::popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList) {
763 for (auto typeParam : *typeParamList) {
764 if (!typeParam->isInvalidDecl()) {
765 S->RemoveDecl(typeParam);
766 IdResolver.RemoveDecl(typeParam);
767 }
768 }
769}
770
771namespace {
772 /// The context in which an Objective-C type parameter list occurs, for use
773 /// in diagnostics.
774 enum class TypeParamListContext {
775 ForwardDeclaration,
776 Definition,
777 Category,
778 Extension
779 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000780} // end anonymous namespace
Douglas Gregor85f3f952015-07-07 03:57:15 +0000781
782/// Check consistency between two Objective-C type parameter lists, e.g.,
NAKAMURA Takumi4c3ab452015-07-08 02:35:56 +0000783/// between a category/extension and an \@interface or between an \@class and an
784/// \@interface.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000785static bool checkTypeParamListConsistency(Sema &S,
786 ObjCTypeParamList *prevTypeParams,
787 ObjCTypeParamList *newTypeParams,
788 TypeParamListContext newContext) {
789 // If the sizes don't match, complain about that.
790 if (prevTypeParams->size() != newTypeParams->size()) {
791 SourceLocation diagLoc;
792 if (newTypeParams->size() > prevTypeParams->size()) {
793 diagLoc = newTypeParams->begin()[prevTypeParams->size()]->getLocation();
794 } else {
Craig Topper07fa1762015-11-15 02:31:46 +0000795 diagLoc = S.getLocForEndOfToken(newTypeParams->back()->getLocEnd());
Douglas Gregor85f3f952015-07-07 03:57:15 +0000796 }
797
798 S.Diag(diagLoc, diag::err_objc_type_param_arity_mismatch)
799 << static_cast<unsigned>(newContext)
800 << (newTypeParams->size() > prevTypeParams->size())
801 << prevTypeParams->size()
802 << newTypeParams->size();
803
804 return true;
805 }
806
807 // Match up the type parameters.
808 for (unsigned i = 0, n = prevTypeParams->size(); i != n; ++i) {
809 ObjCTypeParamDecl *prevTypeParam = prevTypeParams->begin()[i];
810 ObjCTypeParamDecl *newTypeParam = newTypeParams->begin()[i];
811
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000812 // Check for consistency of the variance.
813 if (newTypeParam->getVariance() != prevTypeParam->getVariance()) {
814 if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant &&
815 newContext != TypeParamListContext::Definition) {
816 // When the new type parameter is invariant and is not part
817 // of the definition, just propagate the variance.
818 newTypeParam->setVariance(prevTypeParam->getVariance());
819 } else if (prevTypeParam->getVariance()
820 == ObjCTypeParamVariance::Invariant &&
821 !(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) &&
822 cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext())
823 ->getDefinition() == prevTypeParam->getDeclContext())) {
824 // When the old parameter is invariant and was not part of the
825 // definition, just ignore the difference because it doesn't
826 // matter.
827 } else {
828 {
829 // Diagnose the conflict and update the second declaration.
830 SourceLocation diagLoc = newTypeParam->getVarianceLoc();
831 if (diagLoc.isInvalid())
832 diagLoc = newTypeParam->getLocStart();
833
834 auto diag = S.Diag(diagLoc,
835 diag::err_objc_type_param_variance_conflict)
836 << static_cast<unsigned>(newTypeParam->getVariance())
837 << newTypeParam->getDeclName()
838 << static_cast<unsigned>(prevTypeParam->getVariance())
839 << prevTypeParam->getDeclName();
840 switch (prevTypeParam->getVariance()) {
841 case ObjCTypeParamVariance::Invariant:
842 diag << FixItHint::CreateRemoval(newTypeParam->getVarianceLoc());
843 break;
844
845 case ObjCTypeParamVariance::Covariant:
846 case ObjCTypeParamVariance::Contravariant: {
847 StringRef newVarianceStr
848 = prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant
849 ? "__covariant"
850 : "__contravariant";
851 if (newTypeParam->getVariance()
852 == ObjCTypeParamVariance::Invariant) {
853 diag << FixItHint::CreateInsertion(newTypeParam->getLocStart(),
854 (newVarianceStr + " ").str());
855 } else {
856 diag << FixItHint::CreateReplacement(newTypeParam->getVarianceLoc(),
857 newVarianceStr);
858 }
859 }
860 }
861 }
862
863 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
864 << prevTypeParam->getDeclName();
865
866 // Override the variance.
867 newTypeParam->setVariance(prevTypeParam->getVariance());
868 }
869 }
870
Douglas Gregor85f3f952015-07-07 03:57:15 +0000871 // If the bound types match, there's nothing to do.
872 if (S.Context.hasSameType(prevTypeParam->getUnderlyingType(),
873 newTypeParam->getUnderlyingType()))
874 continue;
875
876 // If the new type parameter's bound was explicit, complain about it being
877 // different from the original.
878 if (newTypeParam->hasExplicitBound()) {
879 SourceRange newBoundRange = newTypeParam->getTypeSourceInfo()
880 ->getTypeLoc().getSourceRange();
881 S.Diag(newBoundRange.getBegin(), diag::err_objc_type_param_bound_conflict)
882 << newTypeParam->getUnderlyingType()
883 << newTypeParam->getDeclName()
884 << prevTypeParam->hasExplicitBound()
885 << prevTypeParam->getUnderlyingType()
886 << (newTypeParam->getDeclName() == prevTypeParam->getDeclName())
887 << prevTypeParam->getDeclName()
888 << FixItHint::CreateReplacement(
889 newBoundRange,
890 prevTypeParam->getUnderlyingType().getAsString(
891 S.Context.getPrintingPolicy()));
892
893 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
894 << prevTypeParam->getDeclName();
895
896 // Override the new type parameter's bound type with the previous type,
897 // so that it's consistent.
898 newTypeParam->setTypeSourceInfo(
899 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
900 continue;
901 }
902
903 // The new type parameter got the implicit bound of 'id'. That's okay for
904 // categories and extensions (overwrite it later), but not for forward
905 // declarations and @interfaces, because those must be standalone.
906 if (newContext == TypeParamListContext::ForwardDeclaration ||
907 newContext == TypeParamListContext::Definition) {
908 // Diagnose this problem for forward declarations and definitions.
909 SourceLocation insertionLoc
Craig Topper07fa1762015-11-15 02:31:46 +0000910 = S.getLocForEndOfToken(newTypeParam->getLocation());
Douglas Gregor85f3f952015-07-07 03:57:15 +0000911 std::string newCode
912 = " : " + prevTypeParam->getUnderlyingType().getAsString(
913 S.Context.getPrintingPolicy());
914 S.Diag(newTypeParam->getLocation(),
915 diag::err_objc_type_param_bound_missing)
916 << prevTypeParam->getUnderlyingType()
917 << newTypeParam->getDeclName()
918 << (newContext == TypeParamListContext::ForwardDeclaration)
919 << FixItHint::CreateInsertion(insertionLoc, newCode);
920
921 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
922 << prevTypeParam->getDeclName();
923 }
924
925 // Update the new type parameter's bound to match the previous one.
926 newTypeParam->setTypeSourceInfo(
927 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
928 }
929
930 return false;
931}
932
John McCall48871652010-08-21 09:40:31 +0000933Decl *Sema::
Douglas Gregore9d95f12015-07-07 03:57:35 +0000934ActOnStartClassInterface(Scope *S, SourceLocation AtInterfaceLoc,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000935 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000936 ObjCTypeParamList *typeParamList,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000937 IdentifierInfo *SuperName, SourceLocation SuperLoc,
Douglas Gregore9d95f12015-07-07 03:57:35 +0000938 ArrayRef<ParsedType> SuperTypeArgs,
939 SourceRange SuperTypeArgsRange,
John McCall48871652010-08-21 09:40:31 +0000940 Decl * const *ProtoRefs, unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +0000941 const SourceLocation *ProtoLocs,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000942 SourceLocation EndProtoLoc, AttributeList *AttrList) {
Chris Lattnerda463fe2007-12-12 07:09:47 +0000943 assert(ClassName && "Missing class identifier");
Mike Stump11289f42009-09-09 15:08:12 +0000944
Chris Lattnerda463fe2007-12-12 07:09:47 +0000945 // Check for another declaration kind with the same name.
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000946 NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000947 LookupOrdinaryName, ForRedeclaration);
Douglas Gregor5101c242008-12-05 18:15:24 +0000948
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000949 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +0000950 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Chris Lattner0369c572008-11-23 23:12:31 +0000951 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +0000952 }
Mike Stump11289f42009-09-09 15:08:12 +0000953
Douglas Gregordc9166c2011-12-15 20:29:51 +0000954 // Create a declaration to describe this @interface.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +0000955 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidisdd710632013-06-18 21:26:33 +0000956
957 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
958 // A previous decl with a different name is because of
959 // @compatibility_alias, for example:
960 // \code
961 // @class NewImage;
962 // @compatibility_alias OldImage NewImage;
963 // \endcode
964 // A lookup for 'OldImage' will return the 'NewImage' decl.
965 //
966 // In such a case use the real declaration name, instead of the alias one,
967 // otherwise we will break IdentifierResolver and redecls-chain invariants.
968 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
969 // has been aliased.
970 ClassName = PrevIDecl->getIdentifier();
971 }
972
Douglas Gregor85f3f952015-07-07 03:57:15 +0000973 // If there was a forward declaration with type parameters, check
974 // for consistency.
975 if (PrevIDecl) {
976 if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) {
977 if (typeParamList) {
978 // Both have type parameter lists; check for consistency.
979 if (checkTypeParamListConsistency(*this, prevTypeParamList,
980 typeParamList,
981 TypeParamListContext::Definition)) {
982 typeParamList = nullptr;
983 }
984 } else {
985 Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first)
986 << ClassName;
987 Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl)
988 << ClassName;
989
990 // Clone the type parameter list.
991 SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams;
992 for (auto typeParam : *prevTypeParamList) {
993 clonedTypeParams.push_back(
994 ObjCTypeParamDecl::Create(
995 Context,
996 CurContext,
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000997 typeParam->getVariance(),
998 SourceLocation(),
Douglas Gregore83b9562015-07-07 03:57:53 +0000999 typeParam->getIndex(),
Douglas Gregor85f3f952015-07-07 03:57:15 +00001000 SourceLocation(),
1001 typeParam->getIdentifier(),
1002 SourceLocation(),
1003 Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType())));
1004 }
1005
1006 typeParamList = ObjCTypeParamList::create(Context,
1007 SourceLocation(),
1008 clonedTypeParams,
1009 SourceLocation());
1010 }
1011 }
1012 }
1013
Douglas Gregordc9166c2011-12-15 20:29:51 +00001014 ObjCInterfaceDecl *IDecl
1015 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001016 typeParamList, PrevIDecl, ClassLoc);
Douglas Gregordc9166c2011-12-15 20:29:51 +00001017 if (PrevIDecl) {
1018 // Class already seen. Was it a definition?
1019 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
1020 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
1021 << PrevIDecl->getDeclName();
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001022 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregordc9166c2011-12-15 20:29:51 +00001023 IDecl->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00001024 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001025 }
Douglas Gregordc9166c2011-12-15 20:29:51 +00001026
1027 if (AttrList)
1028 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001029 AddPragmaAttributes(TUScope, IDecl);
Douglas Gregordc9166c2011-12-15 20:29:51 +00001030 PushOnScopeChains(IDecl, TUScope);
Mike Stump11289f42009-09-09 15:08:12 +00001031
Douglas Gregordc9166c2011-12-15 20:29:51 +00001032 // Start the definition of this class. If we're in a redefinition case, there
1033 // may already be a definition, so we'll end up adding to it.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001034 if (!IDecl->hasDefinition())
1035 IDecl->startDefinition();
1036
Chris Lattnerda463fe2007-12-12 07:09:47 +00001037 if (SuperName) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001038 // Diagnose availability in the context of the @interface.
1039 ContextRAII SavedContext(*this, IDecl);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001040
Douglas Gregore9d95f12015-07-07 03:57:35 +00001041 ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl,
1042 ClassName, ClassLoc,
1043 SuperName, SuperLoc, SuperTypeArgs,
1044 SuperTypeArgsRange);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001045 } else { // we have a root class.
Douglas Gregor16408322011-12-15 22:34:59 +00001046 IDecl->setEndOfDefinitionLoc(ClassLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001047 }
Mike Stump11289f42009-09-09 15:08:12 +00001048
Sebastian Redle7c1fe62010-08-13 00:28:03 +00001049 // Check then save referenced protocols.
Chris Lattnerdf59f5a2008-07-26 04:13:19 +00001050 if (NumProtoRefs) {
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001051 diagnoseUseOfProtocols(*this, IDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1052 NumProtoRefs, ProtoLocs);
Roman Divackye6377112012-09-06 15:59:27 +00001053 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001054 ProtoLocs, Context);
Douglas Gregor16408322011-12-15 22:34:59 +00001055 IDecl->setEndOfDefinitionLoc(EndProtoLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001056 }
Mike Stump11289f42009-09-09 15:08:12 +00001057
Anders Carlssona6b508a2008-11-04 16:57:32 +00001058 CheckObjCDeclScope(IDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001059 return ActOnObjCContainerStartDefinition(IDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001060}
1061
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001062/// ActOnTypedefedProtocols - this action finds protocol list as part of the
1063/// typedef'ed use for a qualified super class and adds them to the list
1064/// of the protocols.
1065void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
Argyrios Kyrtzidisf95a0002016-11-09 02:47:07 +00001066 SmallVectorImpl<SourceLocation> &ProtocolLocs,
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001067 IdentifierInfo *SuperName,
1068 SourceLocation SuperLoc) {
1069 if (!SuperName)
1070 return;
1071 NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
1072 LookupOrdinaryName);
1073 if (!IDecl)
1074 return;
1075
1076 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
1077 QualType T = TDecl->getUnderlyingType();
1078 if (T->isObjCObjectType())
Argyrios Kyrtzidisf95a0002016-11-09 02:47:07 +00001079 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>()) {
Benjamin Kramerf9890422015-02-17 16:48:30 +00001080 ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
Argyrios Kyrtzidisf95a0002016-11-09 02:47:07 +00001081 // FIXME: Consider whether this should be an invalid loc since the loc
1082 // is not actually pointing to a protocol name reference but to the
1083 // typedef reference. Note that the base class name loc is also pointing
1084 // at the typedef.
1085 ProtocolLocs.append(OPT->getNumProtocols(), SuperLoc);
1086 }
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001087 }
1088}
1089
Richard Smithac4e36d2012-08-08 23:32:13 +00001090/// ActOnCompatibilityAlias - this action is called after complete parsing of
James Dennett634962f2012-06-14 21:40:34 +00001091/// a \@compatibility_alias declaration. It sets up the alias relationships.
Richard Smithac4e36d2012-08-08 23:32:13 +00001092Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
1093 IdentifierInfo *AliasName,
1094 SourceLocation AliasLocation,
1095 IdentifierInfo *ClassName,
1096 SourceLocation ClassLocation) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00001097 // Look for previous declaration of alias name
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001098 NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
Douglas Gregorb8eaf292010-04-15 23:40:53 +00001099 LookupOrdinaryName, ForRedeclaration);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001100 if (ADecl) {
Eli Friedmanfd6b3f82013-06-21 01:49:53 +00001101 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
Chris Lattnerd0685032008-11-23 23:20:13 +00001102 Diag(ADecl->getLocation(), diag::note_previous_declaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001103 return nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001104 }
1105 // Check for class declaration
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001106 NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
Douglas Gregorb8eaf292010-04-15 23:40:53 +00001107 LookupOrdinaryName, ForRedeclaration);
Richard Smithdda56e42011-04-15 14:24:37 +00001108 if (const TypedefNameDecl *TDecl =
1109 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001110 QualType T = TDecl->getUnderlyingType();
John McCall8b07ec22010-05-15 11:32:37 +00001111 if (T->isObjCObjectType()) {
1112 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001113 ClassName = IDecl->getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001114 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
Douglas Gregorb8eaf292010-04-15 23:40:53 +00001115 LookupOrdinaryName, ForRedeclaration);
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001116 }
1117 }
1118 }
Chris Lattner219b3e92008-03-16 21:17:37 +00001119 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
Craig Topperc3ec1492014-05-26 06:22:03 +00001120 if (!CDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001121 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
Chris Lattner219b3e92008-03-16 21:17:37 +00001122 if (CDeclU)
Chris Lattnerd0685032008-11-23 23:20:13 +00001123 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001124 return nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001125 }
Mike Stump11289f42009-09-09 15:08:12 +00001126
Chris Lattner219b3e92008-03-16 21:17:37 +00001127 // Everything checked out, instantiate a new alias declaration AST.
Mike Stump11289f42009-09-09 15:08:12 +00001128 ObjCCompatibleAliasDecl *AliasDecl =
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001129 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001130
Anders Carlssona6b508a2008-11-04 16:57:32 +00001131 if (!CheckObjCDeclScope(AliasDecl))
Douglas Gregor38feed82009-04-24 02:57:34 +00001132 PushOnScopeChains(AliasDecl, TUScope);
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001133
John McCall48871652010-08-21 09:40:31 +00001134 return AliasDecl;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001135}
1136
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001137bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
Steve Naroff41d09ad2009-03-05 15:22:01 +00001138 IdentifierInfo *PName,
1139 SourceLocation &Ploc, SourceLocation PrevLoc,
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001140 const ObjCList<ObjCProtocolDecl> &PList) {
1141
1142 bool res = false;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001143 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
1144 E = PList.end(); I != E; ++I) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001145 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
1146 Ploc)) {
Steve Naroff41d09ad2009-03-05 15:22:01 +00001147 if (PDecl->getIdentifier() == PName) {
1148 Diag(Ploc, diag::err_protocol_has_circular_dependency);
1149 Diag(PrevLoc, diag::note_previous_definition);
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001150 res = true;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001151 }
Douglas Gregore6e48b12012-01-01 19:29:29 +00001152
1153 if (!PDecl->hasDefinition())
1154 continue;
1155
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001156 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
1157 PDecl->getLocation(), PDecl->getReferencedProtocols()))
1158 res = true;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001159 }
1160 }
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001161 return res;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001162}
1163
John McCall48871652010-08-21 09:40:31 +00001164Decl *
Chris Lattner3bbae002008-07-26 04:03:38 +00001165Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
1166 IdentifierInfo *ProtocolName,
1167 SourceLocation ProtocolLoc,
John McCall48871652010-08-21 09:40:31 +00001168 Decl * const *ProtoRefs,
Chris Lattner3bbae002008-07-26 04:03:38 +00001169 unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001170 const SourceLocation *ProtoLocs,
Daniel Dunbar26e2ab42008-09-26 04:48:09 +00001171 SourceLocation EndProtoLoc,
1172 AttributeList *AttrList) {
Fariborz Jahaniancadf7c52011-05-12 22:04:39 +00001173 bool err = false;
Daniel Dunbar26e2ab42008-09-26 04:48:09 +00001174 // FIXME: Deal with AttrList.
Chris Lattnerda463fe2007-12-12 07:09:47 +00001175 assert(ProtocolName && "Missing protocol identifier");
Douglas Gregor32c17572012-01-01 20:30:41 +00001176 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
1177 ForRedeclaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001178 ObjCProtocolDecl *PDecl = nullptr;
1179 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
Douglas Gregor32c17572012-01-01 20:30:41 +00001180 // If we already have a definition, complain.
1181 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
1182 Diag(Def->getLocation(), diag::note_previous_definition);
Mike Stump11289f42009-09-09 15:08:12 +00001183
Douglas Gregor32c17572012-01-01 20:30:41 +00001184 // Create a new protocol that is completely distinct from previous
1185 // declarations, and do not make this protocol available for name lookup.
1186 // That way, we'll end up completely ignoring the duplicate.
1187 // FIXME: Can we turn this into an error?
1188 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
1189 ProtocolLoc, AtProtoInterfaceLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +00001190 /*PrevDecl=*/nullptr);
Douglas Gregor32c17572012-01-01 20:30:41 +00001191 PDecl->startDefinition();
1192 } else {
1193 if (PrevDecl) {
1194 // Check for circular dependencies among protocol declarations. This can
1195 // only happen if this protocol was forward-declared.
Argyrios Kyrtzidis95dfc122011-11-13 22:08:30 +00001196 ObjCList<ObjCProtocolDecl> PList;
1197 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
1198 err = CheckForwardProtocolDeclarationForCircularDependency(
Douglas Gregor32c17572012-01-01 20:30:41 +00001199 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
Argyrios Kyrtzidis95dfc122011-11-13 22:08:30 +00001200 }
Douglas Gregor32c17572012-01-01 20:30:41 +00001201
1202 // Create the new declaration.
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001203 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
Argyrios Kyrtzidis1f4bee52011-10-17 19:48:06 +00001204 ProtocolLoc, AtProtoInterfaceLoc,
Douglas Gregor05a1f4d2012-01-01 22:06:18 +00001205 /*PrevDecl=*/PrevDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +00001206
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001207 PushOnScopeChains(PDecl, TUScope);
Douglas Gregore6e48b12012-01-01 19:29:29 +00001208 PDecl->startDefinition();
Chris Lattnerf87ca0a2008-03-16 01:23:04 +00001209 }
Douglas Gregore6e48b12012-01-01 19:29:29 +00001210
Fariborz Jahanian1470e932008-12-17 01:07:27 +00001211 if (AttrList)
Douglas Gregor758a8692009-06-17 21:51:59 +00001212 ProcessDeclAttributeList(TUScope, PDecl, AttrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001213 AddPragmaAttributes(TUScope, PDecl);
1214
Douglas Gregor32c17572012-01-01 20:30:41 +00001215 // Merge attributes from previous declarations.
1216 if (PrevDecl)
1217 mergeDeclAttributes(PDecl, PrevDecl);
1218
Fariborz Jahaniancadf7c52011-05-12 22:04:39 +00001219 if (!err && NumProtoRefs ) {
Chris Lattneracc04a92008-03-16 20:19:15 +00001220 /// Check then save referenced protocols.
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001221 diagnoseUseOfProtocols(*this, PDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1222 NumProtoRefs, ProtoLocs);
Roman Divackye6377112012-09-06 15:59:27 +00001223 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001224 ProtoLocs, Context);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001225 }
Mike Stump11289f42009-09-09 15:08:12 +00001226
1227 CheckObjCDeclScope(PDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001228 return ActOnObjCContainerStartDefinition(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001229}
1230
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001231static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
1232 ObjCProtocolDecl *&UndefinedProtocol) {
1233 if (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()) {
1234 UndefinedProtocol = PDecl;
1235 return true;
1236 }
1237
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001238 for (auto *PI : PDecl->protocols())
1239 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
1240 UndefinedProtocol = PI;
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001241 return true;
1242 }
1243 return false;
1244}
1245
Chris Lattnerda463fe2007-12-12 07:09:47 +00001246/// FindProtocolDeclaration - This routine looks up protocols and
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00001247/// issues an error if they are not declared. It returns list of
1248/// protocol declarations in its 'Protocols' argument.
Chris Lattnerda463fe2007-12-12 07:09:47 +00001249void
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001250Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
Craig Toppera9247eb2015-10-22 04:59:56 +00001251 ArrayRef<IdentifierLocPair> ProtocolId,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001252 SmallVectorImpl<Decl *> &Protocols) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001253 for (const IdentifierLocPair &Pair : ProtocolId) {
1254 ObjCProtocolDecl *PDecl = LookupProtocol(Pair.first, Pair.second);
Chris Lattner9c1842b2008-07-26 03:47:43 +00001255 if (!PDecl) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001256 TypoCorrection Corrected = CorrectTypo(
Craig Toppera9247eb2015-10-22 04:59:56 +00001257 DeclarationNameInfo(Pair.first, Pair.second),
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001258 LookupObjCProtocolName, TUScope, nullptr,
1259 llvm::make_unique<DeclFilterCCC<ObjCProtocolDecl>>(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001260 CTK_ErrorRecovery);
Richard Smithf9b15102013-08-17 00:46:16 +00001261 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
1262 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
Craig Toppera9247eb2015-10-22 04:59:56 +00001263 << Pair.first);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001264 }
1265
1266 if (!PDecl) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001267 Diag(Pair.second, diag::err_undeclared_protocol) << Pair.first;
Chris Lattner9c1842b2008-07-26 03:47:43 +00001268 continue;
1269 }
Fariborz Jahanianada44a22013-04-09 17:52:29 +00001270 // If this is a forward protocol declaration, get its definition.
1271 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
1272 PDecl = PDecl->getDefinition();
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001273
1274 // For an objc container, delay protocol reference checking until after we
1275 // can set the objc decl as the availability context, otherwise check now.
1276 if (!ForObjCContainer) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001277 (void)DiagnoseUseOfDecl(PDecl, Pair.second);
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001278 }
Chris Lattner9c1842b2008-07-26 03:47:43 +00001279
1280 // If this is a forward declaration and we are supposed to warn in this
1281 // case, do it.
Douglas Gregoreed49792013-01-17 00:38:46 +00001282 // FIXME: Recover nicely in the hidden case.
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001283 ObjCProtocolDecl *UndefinedProtocol;
1284
Douglas Gregoreed49792013-01-17 00:38:46 +00001285 if (WarnOnDeclarations &&
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001286 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001287 Diag(Pair.second, diag::warn_undef_protocolref) << Pair.first;
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001288 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
1289 << UndefinedProtocol;
1290 }
John McCall48871652010-08-21 09:40:31 +00001291 Protocols.push_back(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001292 }
1293}
1294
Benjamin Kramer8b851d02015-07-13 20:42:13 +00001295namespace {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001296// Callback to only accept typo corrections that are either
1297// Objective-C protocols or valid Objective-C type arguments.
1298class ObjCTypeArgOrProtocolValidatorCCC : public CorrectionCandidateCallback {
1299 ASTContext &Context;
1300 Sema::LookupNameKind LookupKind;
1301 public:
1302 ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context,
1303 Sema::LookupNameKind lookupKind)
1304 : Context(context), LookupKind(lookupKind) { }
1305
1306 bool ValidateCandidate(const TypoCorrection &candidate) override {
1307 // If we're allowed to find protocols and we have a protocol, accept it.
1308 if (LookupKind != Sema::LookupOrdinaryName) {
1309 if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>())
1310 return true;
1311 }
1312
1313 // If we're allowed to find type names and we have one, accept it.
1314 if (LookupKind != Sema::LookupObjCProtocolName) {
1315 // If we have a type declaration, we might accept this result.
1316 if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) {
1317 // If we found a tag declaration outside of C++, skip it. This
1318 // can happy because we look for any name when there is no
1319 // bias to protocol or type names.
1320 if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus)
1321 return false;
1322
1323 // Make sure the type is something we would accept as a type
1324 // argument.
1325 auto type = Context.getTypeDeclType(typeDecl);
1326 if (type->isObjCObjectPointerType() ||
1327 type->isBlockPointerType() ||
1328 type->isDependentType() ||
1329 type->isObjCObjectType())
1330 return true;
1331
1332 return false;
1333 }
1334
1335 // If we have an Objective-C class type, accept it; there will
1336 // be another fix to add the '*'.
1337 if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>())
1338 return true;
1339
1340 return false;
1341 }
1342
1343 return false;
1344 }
1345};
Benjamin Kramer8b851d02015-07-13 20:42:13 +00001346} // end anonymous namespace
Douglas Gregore9d95f12015-07-07 03:57:35 +00001347
Bruno Cardoso Lopesc54768f2016-04-13 20:59:07 +00001348void Sema::DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
1349 SourceLocation ProtocolLoc,
1350 IdentifierInfo *TypeArgId,
1351 SourceLocation TypeArgLoc,
1352 bool SelectProtocolFirst) {
1353 Diag(TypeArgLoc, diag::err_objc_type_args_and_protocols)
1354 << SelectProtocolFirst << TypeArgId << ProtocolId
1355 << SourceRange(ProtocolLoc);
1356}
1357
Douglas Gregore9d95f12015-07-07 03:57:35 +00001358void Sema::actOnObjCTypeArgsOrProtocolQualifiers(
1359 Scope *S,
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001360 ParsedType baseType,
Douglas Gregore9d95f12015-07-07 03:57:35 +00001361 SourceLocation lAngleLoc,
1362 ArrayRef<IdentifierInfo *> identifiers,
1363 ArrayRef<SourceLocation> identifierLocs,
1364 SourceLocation rAngleLoc,
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001365 SourceLocation &typeArgsLAngleLoc,
1366 SmallVectorImpl<ParsedType> &typeArgs,
1367 SourceLocation &typeArgsRAngleLoc,
1368 SourceLocation &protocolLAngleLoc,
1369 SmallVectorImpl<Decl *> &protocols,
1370 SourceLocation &protocolRAngleLoc,
Douglas Gregore9d95f12015-07-07 03:57:35 +00001371 bool warnOnIncompleteProtocols) {
1372 // Local function that updates the declaration specifiers with
1373 // protocol information.
Douglas Gregore9d95f12015-07-07 03:57:35 +00001374 unsigned numProtocolsResolved = 0;
1375 auto resolvedAsProtocols = [&] {
1376 assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols");
1377
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001378 // Determine whether the base type is a parameterized class, in
1379 // which case we want to warn about typos such as
1380 // "NSArray<NSObject>" (that should be NSArray<NSObject *>).
1381 ObjCInterfaceDecl *baseClass = nullptr;
1382 QualType base = GetTypeFromParser(baseType, nullptr);
1383 bool allAreTypeNames = false;
1384 SourceLocation firstClassNameLoc;
1385 if (!base.isNull()) {
1386 if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) {
1387 baseClass = objcObjectType->getInterface();
1388 if (baseClass) {
1389 if (auto typeParams = baseClass->getTypeParamList()) {
1390 if (typeParams->size() == numProtocolsResolved) {
1391 // Note that we should be looking for type names, too.
1392 allAreTypeNames = true;
1393 }
1394 }
1395 }
1396 }
1397 }
1398
Douglas Gregore9d95f12015-07-07 03:57:35 +00001399 for (unsigned i = 0, n = protocols.size(); i != n; ++i) {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001400 ObjCProtocolDecl *&proto
1401 = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001402 // For an objc container, delay protocol reference checking until after we
1403 // can set the objc decl as the availability context, otherwise check now.
1404 if (!warnOnIncompleteProtocols) {
1405 (void)DiagnoseUseOfDecl(proto, identifierLocs[i]);
1406 }
1407
1408 // If this is a forward protocol declaration, get its definition.
1409 if (!proto->isThisDeclarationADefinition() && proto->getDefinition())
1410 proto = proto->getDefinition();
1411
1412 // If this is a forward declaration and we are supposed to warn in this
1413 // case, do it.
1414 // FIXME: Recover nicely in the hidden case.
1415 ObjCProtocolDecl *forwardDecl = nullptr;
1416 if (warnOnIncompleteProtocols &&
1417 NestedProtocolHasNoDefinition(proto, forwardDecl)) {
1418 Diag(identifierLocs[i], diag::warn_undef_protocolref)
1419 << proto->getDeclName();
1420 Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined)
1421 << forwardDecl;
1422 }
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001423
1424 // If everything this far has been a type name (and we care
1425 // about such things), check whether this name refers to a type
1426 // as well.
1427 if (allAreTypeNames) {
1428 if (auto *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1429 LookupOrdinaryName)) {
1430 if (isa<ObjCInterfaceDecl>(decl)) {
1431 if (firstClassNameLoc.isInvalid())
1432 firstClassNameLoc = identifierLocs[i];
1433 } else if (!isa<TypeDecl>(decl)) {
1434 // Not a type.
1435 allAreTypeNames = false;
1436 }
1437 } else {
1438 allAreTypeNames = false;
1439 }
1440 }
1441 }
1442
1443 // All of the protocols listed also have type names, and at least
1444 // one is an Objective-C class name. Check whether all of the
1445 // protocol conformances are declared by the base class itself, in
1446 // which case we warn.
1447 if (allAreTypeNames && firstClassNameLoc.isValid()) {
1448 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> knownProtocols;
1449 Context.CollectInheritedProtocols(baseClass, knownProtocols);
1450 bool allProtocolsDeclared = true;
1451 for (auto proto : protocols) {
1452 if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) {
1453 allProtocolsDeclared = false;
1454 break;
1455 }
1456 }
1457
1458 if (allProtocolsDeclared) {
1459 Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type)
1460 << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc)
Craig Topper07fa1762015-11-15 02:31:46 +00001461 << FixItHint::CreateInsertion(getLocForEndOfToken(firstClassNameLoc),
1462 " *");
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001463 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00001464 }
1465
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001466 protocolLAngleLoc = lAngleLoc;
1467 protocolRAngleLoc = rAngleLoc;
1468 assert(protocols.size() == identifierLocs.size());
Douglas Gregore9d95f12015-07-07 03:57:35 +00001469 };
1470
1471 // Attempt to resolve all of the identifiers as protocols.
1472 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1473 ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]);
1474 protocols.push_back(proto);
1475 if (proto)
1476 ++numProtocolsResolved;
1477 }
1478
1479 // If all of the names were protocols, these were protocol qualifiers.
1480 if (numProtocolsResolved == identifiers.size())
1481 return resolvedAsProtocols();
1482
1483 // Attempt to resolve all of the identifiers as type names or
1484 // Objective-C class names. The latter is technically ill-formed,
1485 // but is probably something like \c NSArray<NSView *> missing the
1486 // \c*.
1487 typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl;
1488 SmallVector<TypeOrClassDecl, 4> typeDecls;
1489 unsigned numTypeDeclsResolved = 0;
1490 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1491 NamedDecl *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1492 LookupOrdinaryName);
1493 if (!decl) {
1494 typeDecls.push_back(TypeOrClassDecl());
1495 continue;
1496 }
1497
1498 if (auto typeDecl = dyn_cast<TypeDecl>(decl)) {
1499 typeDecls.push_back(typeDecl);
1500 ++numTypeDeclsResolved;
1501 continue;
1502 }
1503
1504 if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) {
1505 typeDecls.push_back(objcClass);
1506 ++numTypeDeclsResolved;
1507 continue;
1508 }
1509
1510 typeDecls.push_back(TypeOrClassDecl());
1511 }
1512
1513 AttributeFactory attrFactory;
1514
1515 // Local function that forms a reference to the given type or
1516 // Objective-C class declaration.
1517 auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc)
1518 -> TypeResult {
1519 // Form declaration specifiers. They simply refer to the type.
1520 DeclSpec DS(attrFactory);
1521 const char* prevSpec; // unused
1522 unsigned diagID; // unused
1523 QualType type;
1524 if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>())
1525 type = Context.getTypeDeclType(actualTypeDecl);
1526 else
1527 type = Context.getObjCInterfaceType(typeDecl.get<ObjCInterfaceDecl *>());
1528 TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc);
1529 ParsedType parsedType = CreateParsedType(type, parsedTSInfo);
1530 DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID,
1531 parsedType, Context.getPrintingPolicy());
1532 // Use the identifier location for the type source range.
1533 DS.SetRangeStart(loc);
1534 DS.SetRangeEnd(loc);
1535
1536 // Form the declarator.
1537 Declarator D(DS, Declarator::TypeNameContext);
1538
1539 // If we have a typedef of an Objective-C class type that is missing a '*',
1540 // add the '*'.
1541 if (type->getAs<ObjCInterfaceType>()) {
Craig Topper07fa1762015-11-15 02:31:46 +00001542 SourceLocation starLoc = getLocForEndOfToken(loc);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001543 ParsedAttributes parsedAttrs(attrFactory);
1544 D.AddTypeInfo(DeclaratorChunk::getPointer(/*typeQuals=*/0, starLoc,
1545 SourceLocation(),
1546 SourceLocation(),
1547 SourceLocation(),
Andrey Bokhanko45d41322016-05-11 18:38:21 +00001548 SourceLocation(),
Douglas Gregore9d95f12015-07-07 03:57:35 +00001549 SourceLocation()),
Hans Wennborgdcfba332015-10-06 23:40:43 +00001550 parsedAttrs,
1551 starLoc);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001552
1553 // Diagnose the missing '*'.
1554 Diag(loc, diag::err_objc_type_arg_missing_star)
1555 << type
1556 << FixItHint::CreateInsertion(starLoc, " *");
1557 }
1558
1559 // Convert this to a type.
1560 return ActOnTypeName(S, D);
1561 };
1562
1563 // Local function that updates the declaration specifiers with
1564 // type argument information.
1565 auto resolvedAsTypeDecls = [&] {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001566 // We did not resolve these as protocols.
1567 protocols.clear();
1568
Douglas Gregore9d95f12015-07-07 03:57:35 +00001569 assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl");
1570 // Map type declarations to type arguments.
Douglas Gregore9d95f12015-07-07 03:57:35 +00001571 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1572 // Map type reference to a type.
1573 TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]);
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001574 if (!type.isUsable()) {
1575 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001576 return;
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001577 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00001578
1579 typeArgs.push_back(type.get());
1580 }
1581
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001582 typeArgsLAngleLoc = lAngleLoc;
1583 typeArgsRAngleLoc = rAngleLoc;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001584 };
1585
1586 // If all of the identifiers can be resolved as type names or
1587 // Objective-C class names, we have type arguments.
1588 if (numTypeDeclsResolved == identifiers.size())
1589 return resolvedAsTypeDecls();
1590
1591 // Error recovery: some names weren't found, or we have a mix of
1592 // type and protocol names. Go resolve all of the unresolved names
1593 // and complain if we can't find a consistent answer.
1594 LookupNameKind lookupKind = LookupAnyName;
1595 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1596 // If we already have a protocol or type. Check whether it is the
1597 // right thing.
1598 if (protocols[i] || typeDecls[i]) {
1599 // If we haven't figured out whether we want types or protocols
1600 // yet, try to figure it out from this name.
1601 if (lookupKind == LookupAnyName) {
1602 // If this name refers to both a protocol and a type (e.g., \c
1603 // NSObject), don't conclude anything yet.
1604 if (protocols[i] && typeDecls[i])
1605 continue;
1606
1607 // Otherwise, let this name decide whether we'll be correcting
1608 // toward types or protocols.
1609 lookupKind = protocols[i] ? LookupObjCProtocolName
1610 : LookupOrdinaryName;
1611 continue;
1612 }
1613
1614 // If we want protocols and we have a protocol, there's nothing
1615 // more to do.
1616 if (lookupKind == LookupObjCProtocolName && protocols[i])
1617 continue;
1618
1619 // If we want types and we have a type declaration, there's
1620 // nothing more to do.
1621 if (lookupKind == LookupOrdinaryName && typeDecls[i])
1622 continue;
1623
1624 // We have a conflict: some names refer to protocols and others
1625 // refer to types.
Bruno Cardoso Lopesc54768f2016-04-13 20:59:07 +00001626 DiagnoseTypeArgsAndProtocols(identifiers[0], identifierLocs[0],
1627 identifiers[i], identifierLocs[i],
1628 protocols[i] != nullptr);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001629
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001630 protocols.clear();
1631 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001632 return;
1633 }
1634
1635 // Perform typo correction on the name.
1636 TypoCorrection corrected = CorrectTypo(
1637 DeclarationNameInfo(identifiers[i], identifierLocs[i]), lookupKind, S,
1638 nullptr,
1639 llvm::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(Context,
1640 lookupKind),
1641 CTK_ErrorRecovery);
1642 if (corrected) {
1643 // Did we find a protocol?
1644 if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) {
1645 diagnoseTypo(corrected,
1646 PDiag(diag::err_undeclared_protocol_suggest)
1647 << identifiers[i]);
1648 lookupKind = LookupObjCProtocolName;
1649 protocols[i] = proto;
1650 ++numProtocolsResolved;
1651 continue;
1652 }
1653
1654 // Did we find a type?
1655 if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) {
1656 diagnoseTypo(corrected,
1657 PDiag(diag::err_unknown_typename_suggest)
1658 << identifiers[i]);
1659 lookupKind = LookupOrdinaryName;
1660 typeDecls[i] = typeDecl;
1661 ++numTypeDeclsResolved;
1662 continue;
1663 }
1664
1665 // Did we find an Objective-C class?
1666 if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1667 diagnoseTypo(corrected,
1668 PDiag(diag::err_unknown_type_or_class_name_suggest)
1669 << identifiers[i] << true);
1670 lookupKind = LookupOrdinaryName;
1671 typeDecls[i] = objcClass;
1672 ++numTypeDeclsResolved;
1673 continue;
1674 }
1675 }
1676
1677 // We couldn't find anything.
1678 Diag(identifierLocs[i],
1679 (lookupKind == LookupAnyName ? diag::err_objc_type_arg_missing
1680 : lookupKind == LookupObjCProtocolName ? diag::err_undeclared_protocol
1681 : diag::err_unknown_typename))
1682 << identifiers[i];
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001683 protocols.clear();
1684 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001685 return;
1686 }
1687
1688 // If all of the names were (corrected to) protocols, these were
1689 // protocol qualifiers.
1690 if (numProtocolsResolved == identifiers.size())
1691 return resolvedAsProtocols();
1692
1693 // Otherwise, all of the names were (corrected to) types.
1694 assert(numTypeDeclsResolved == identifiers.size() && "Not all types?");
1695 return resolvedAsTypeDecls();
1696}
1697
Fariborz Jahanianabf63e7b2009-03-02 19:06:08 +00001698/// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001699/// a class method in its extension.
1700///
Mike Stump11289f42009-09-09 15:08:12 +00001701void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001702 ObjCInterfaceDecl *ID) {
1703 if (!ID)
1704 return; // Possibly due to previous error
1705
1706 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
Aaron Ballmanaff18c02014-03-13 19:03:34 +00001707 for (auto *MD : ID->methods())
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001708 MethodMap[MD->getSelector()] = MD;
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001709
1710 if (MethodMap.empty())
1711 return;
Aaron Ballmanaff18c02014-03-13 19:03:34 +00001712 for (const auto *Method : CAT->methods()) {
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001713 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
Fariborz Jahanian83d674e2014-03-17 17:46:10 +00001714 if (PrevMethod &&
1715 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
1716 !MatchTwoMethodDeclarations(Method, PrevMethod)) {
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001717 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1718 << Method->getDeclName();
1719 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1720 }
1721 }
1722}
1723
James Dennett634962f2012-06-14 21:40:34 +00001724/// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
Douglas Gregorf6102672012-01-01 21:23:57 +00001725Sema::DeclGroupPtrTy
Chris Lattnerda463fe2007-12-12 07:09:47 +00001726Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
Craig Topper0f723bb2015-10-22 05:00:01 +00001727 ArrayRef<IdentifierLocPair> IdentList,
Fariborz Jahanian1470e932008-12-17 01:07:27 +00001728 AttributeList *attrList) {
Douglas Gregorf6102672012-01-01 21:23:57 +00001729 SmallVector<Decl *, 8> DeclsInGroup;
Craig Topper0f723bb2015-10-22 05:00:01 +00001730 for (const IdentifierLocPair &IdentPair : IdentList) {
1731 IdentifierInfo *Ident = IdentPair.first;
1732 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentPair.second,
Douglas Gregor32c17572012-01-01 20:30:41 +00001733 ForRedeclaration);
1734 ObjCProtocolDecl *PDecl
1735 = ObjCProtocolDecl::Create(Context, CurContext, Ident,
Craig Topper0f723bb2015-10-22 05:00:01 +00001736 IdentPair.second, AtProtocolLoc,
Douglas Gregor05a1f4d2012-01-01 22:06:18 +00001737 PrevDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +00001738
1739 PushOnScopeChains(PDecl, TUScope);
Douglas Gregorf6102672012-01-01 21:23:57 +00001740 CheckObjCDeclScope(PDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +00001741
Douglas Gregor42ff1bb2012-01-01 20:33:24 +00001742 if (attrList)
Douglas Gregor758a8692009-06-17 21:51:59 +00001743 ProcessDeclAttributeList(TUScope, PDecl, attrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001744 AddPragmaAttributes(TUScope, PDecl);
1745
Douglas Gregor32c17572012-01-01 20:30:41 +00001746 if (PrevDecl)
1747 mergeDeclAttributes(PDecl, PrevDecl);
1748
Douglas Gregorf6102672012-01-01 21:23:57 +00001749 DeclsInGroup.push_back(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001750 }
Mike Stump11289f42009-09-09 15:08:12 +00001751
Richard Smith3beb7c62017-01-12 02:27:38 +00001752 return BuildDeclaratorGroup(DeclsInGroup);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001753}
1754
John McCall48871652010-08-21 09:40:31 +00001755Decl *Sema::
Chris Lattnerd7352d62008-07-21 22:17:28 +00001756ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
1757 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001758 ObjCTypeParamList *typeParamList,
Chris Lattnerd7352d62008-07-21 22:17:28 +00001759 IdentifierInfo *CategoryName,
1760 SourceLocation CategoryLoc,
John McCall48871652010-08-21 09:40:31 +00001761 Decl * const *ProtoRefs,
Chris Lattnerd7352d62008-07-21 22:17:28 +00001762 unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001763 const SourceLocation *ProtoLocs,
Alex Lorenzf9371392017-03-23 11:44:25 +00001764 SourceLocation EndProtoLoc,
1765 AttributeList *AttrList) {
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001766 ObjCCategoryDecl *CDecl;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001767 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
Ted Kremenek514ff702010-02-23 19:39:46 +00001768
1769 /// Check that class of this category is already completely declared.
Douglas Gregor4123a862011-11-14 22:10:01 +00001770
1771 if (!IDecl
1772 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001773 diag::err_category_forward_interface,
Craig Topperc3ec1492014-05-26 06:22:03 +00001774 CategoryName == nullptr)) {
Ted Kremenek514ff702010-02-23 19:39:46 +00001775 // Create an invalid ObjCCategoryDecl to serve as context for
1776 // the enclosing method declarations. We mark the decl invalid
1777 // to make it clear that this isn't a valid AST.
1778 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001779 ClassLoc, CategoryLoc, CategoryName,
1780 IDecl, typeParamList);
Ted Kremenek514ff702010-02-23 19:39:46 +00001781 CDecl->setInvalidDecl();
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00001782 CurContext->addDecl(CDecl);
Douglas Gregor4123a862011-11-14 22:10:01 +00001783
1784 if (!IDecl)
1785 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001786 return ActOnObjCContainerStartDefinition(CDecl);
Ted Kremenek514ff702010-02-23 19:39:46 +00001787 }
1788
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001789 if (!CategoryName && IDecl->getImplementation()) {
1790 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
1791 Diag(IDecl->getImplementation()->getLocation(),
1792 diag::note_implementation_declared);
Ted Kremenek514ff702010-02-23 19:39:46 +00001793 }
1794
Fariborz Jahanian30a42922010-02-15 21:55:26 +00001795 if (CategoryName) {
1796 /// Check for duplicate interface declaration for this category
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001797 if (ObjCCategoryDecl *Previous
1798 = IDecl->FindCategoryDeclaration(CategoryName)) {
1799 // Class extensions can be declared multiple times, categories cannot.
1800 Diag(CategoryLoc, diag::warn_dup_category_def)
1801 << ClassName << CategoryName;
1802 Diag(Previous->getLocation(), diag::note_previous_definition);
Chris Lattner9018ca82009-02-16 21:26:43 +00001803 }
1804 }
Chris Lattner9018ca82009-02-16 21:26:43 +00001805
Douglas Gregor85f3f952015-07-07 03:57:15 +00001806 // If we have a type parameter list, check it.
1807 if (typeParamList) {
1808 if (auto prevTypeParamList = IDecl->getTypeParamList()) {
1809 if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList,
1810 CategoryName
1811 ? TypeParamListContext::Category
1812 : TypeParamListContext::Extension))
1813 typeParamList = nullptr;
1814 } else {
1815 Diag(typeParamList->getLAngleLoc(),
1816 diag::err_objc_parameterized_category_nonclass)
1817 << (CategoryName != nullptr)
1818 << ClassName
1819 << typeParamList->getSourceRange();
1820
1821 typeParamList = nullptr;
1822 }
1823 }
1824
Argyrios Kyrtzidis3a5094b2011-08-30 19:43:26 +00001825 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001826 ClassLoc, CategoryLoc, CategoryName, IDecl,
1827 typeParamList);
Argyrios Kyrtzidis3a5094b2011-08-30 19:43:26 +00001828 // FIXME: PushOnScopeChains?
1829 CurContext->addDecl(CDecl);
1830
Chris Lattnerda463fe2007-12-12 07:09:47 +00001831 if (NumProtoRefs) {
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001832 diagnoseUseOfProtocols(*this, CDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1833 NumProtoRefs, ProtoLocs);
1834 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001835 ProtoLocs, Context);
Fariborz Jahanian092cd6e2009-10-05 20:41:32 +00001836 // Protocols in the class extension belong to the class.
Fariborz Jahanian30a42922010-02-15 21:55:26 +00001837 if (CDecl->IsClassExtension())
Roman Divackye6377112012-09-06 15:59:27 +00001838 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001839 NumProtoRefs, Context);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001840 }
Mike Stump11289f42009-09-09 15:08:12 +00001841
Alex Lorenzf9371392017-03-23 11:44:25 +00001842 if (AttrList)
1843 ProcessDeclAttributeList(TUScope, CDecl, AttrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001844 AddPragmaAttributes(TUScope, CDecl);
Alex Lorenzf9371392017-03-23 11:44:25 +00001845
Anders Carlssona6b508a2008-11-04 16:57:32 +00001846 CheckObjCDeclScope(CDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001847 return ActOnObjCContainerStartDefinition(CDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001848}
1849
1850/// ActOnStartCategoryImplementation - Perform semantic checks on the
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001851/// category implementation declaration and build an ObjCCategoryImplDecl
Chris Lattnerda463fe2007-12-12 07:09:47 +00001852/// object.
John McCall48871652010-08-21 09:40:31 +00001853Decl *Sema::ActOnStartCategoryImplementation(
Chris Lattnerda463fe2007-12-12 07:09:47 +00001854 SourceLocation AtCatImplLoc,
1855 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1856 IdentifierInfo *CatName, SourceLocation CatLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001857 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
Craig Topperc3ec1492014-05-26 06:22:03 +00001858 ObjCCategoryDecl *CatIDecl = nullptr;
Argyrios Kyrtzidis4af2cb32012-03-02 19:14:29 +00001859 if (IDecl && IDecl->hasDefinition()) {
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001860 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
1861 if (!CatIDecl) {
1862 // Category @implementation with no corresponding @interface.
1863 // Create and install one.
Argyrios Kyrtzidis41fc05c2011-11-23 20:27:26 +00001864 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
1865 ClassLoc, CatLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001866 CatName, IDecl,
1867 /*typeParamList=*/nullptr);
Argyrios Kyrtzidis41fc05c2011-11-23 20:27:26 +00001868 CatIDecl->setImplicit();
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001869 }
1870 }
1871
Mike Stump11289f42009-09-09 15:08:12 +00001872 ObjCCategoryImplDecl *CDecl =
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001873 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
Argyrios Kyrtzidis4996f5f2011-12-09 00:31:40 +00001874 ClassLoc, AtCatImplLoc, CatLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001875 /// Check that class of this category is already completely declared.
Douglas Gregor4123a862011-11-14 22:10:01 +00001876 if (!IDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001877 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
John McCalld2930c22011-07-22 02:45:48 +00001878 CDecl->setInvalidDecl();
Douglas Gregor4123a862011-11-14 22:10:01 +00001879 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1880 diag::err_undef_interface)) {
1881 CDecl->setInvalidDecl();
John McCalld2930c22011-07-22 02:45:48 +00001882 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001883
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001884 // FIXME: PushOnScopeChains?
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001885 CurContext->addDecl(CDecl);
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001886
Douglas Gregor24ae22c2016-04-01 23:23:52 +00001887 // If the interface has the objc_runtime_visible attribute, we
1888 // cannot implement a category for it.
1889 if (IDecl && IDecl->hasAttr<ObjCRuntimeVisibleAttr>()) {
1890 Diag(ClassLoc, diag::err_objc_runtime_visible_category)
1891 << IDecl->getDeclName();
1892 }
1893
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001894 /// Check that CatName, category name, is not used in another implementation.
1895 if (CatIDecl) {
1896 if (CatIDecl->getImplementation()) {
1897 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
1898 << CatName;
1899 Diag(CatIDecl->getImplementation()->getLocation(),
1900 diag::note_previous_definition);
Argyrios Kyrtzidis0f6d5ca2013-05-30 18:53:21 +00001901 CDecl->setInvalidDecl();
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001902 } else {
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001903 CatIDecl->setImplementation(CDecl);
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001904 // Warn on implementating category of deprecated class under
1905 // -Wdeprecated-implementations flag.
Alex Lorenzf81d97e2017-07-13 16:35:59 +00001906 DiagnoseObjCImplementedDeprecations(*this, CatIDecl,
1907 CDecl->getLocation());
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001908 }
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001909 }
Mike Stump11289f42009-09-09 15:08:12 +00001910
Anders Carlssona6b508a2008-11-04 16:57:32 +00001911 CheckObjCDeclScope(CDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001912 return ActOnObjCContainerStartDefinition(CDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001913}
1914
John McCall48871652010-08-21 09:40:31 +00001915Decl *Sema::ActOnStartClassImplementation(
Chris Lattnerda463fe2007-12-12 07:09:47 +00001916 SourceLocation AtClassImplLoc,
1917 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001918 IdentifierInfo *SuperClassname,
Chris Lattnerda463fe2007-12-12 07:09:47 +00001919 SourceLocation SuperClassLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001920 ObjCInterfaceDecl *IDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001921 // Check for another declaration kind with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00001922 NamedDecl *PrevDecl
Douglas Gregorb8eaf292010-04-15 23:40:53 +00001923 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
1924 ForRedeclaration);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001925 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001926 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Chris Lattner0369c572008-11-23 23:12:31 +00001927 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor1c283312010-08-11 12:19:30 +00001928 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
Richard Smithdb0ac552015-12-18 22:40:25 +00001929 // FIXME: This will produce an error if the definition of the interface has
1930 // been imported from a module but is not visible.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00001931 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1932 diag::warn_undef_interface);
Douglas Gregor40f7a002010-01-04 17:27:12 +00001933 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001934 // We did not find anything with the name ClassName; try to correct for
Douglas Gregor40f7a002010-01-04 17:27:12 +00001935 // typos in the class name.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001936 TypoCorrection Corrected = CorrectTypo(
1937 DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope,
1938 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(), CTK_NonError);
Richard Smithf9b15102013-08-17 00:46:16 +00001939 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1940 // Suggest the (potentially) correct interface name. Don't provide a
1941 // code-modification hint or use the typo name for recovery, because
1942 // this is just a warning. The program may actually be correct.
1943 diagnoseTypo(Corrected,
1944 PDiag(diag::warn_undef_interface_suggest) << ClassName,
1945 /*ErrorRecovery*/false);
Douglas Gregor40f7a002010-01-04 17:27:12 +00001946 } else {
1947 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
1948 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001949 }
Mike Stump11289f42009-09-09 15:08:12 +00001950
Chris Lattnerda463fe2007-12-12 07:09:47 +00001951 // Check that super class name is valid class name
Craig Topperc3ec1492014-05-26 06:22:03 +00001952 ObjCInterfaceDecl *SDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001953 if (SuperClassname) {
1954 // Check if a different kind of symbol declared in this scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001955 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
1956 LookupOrdinaryName);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001957 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001958 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
1959 << SuperClassname;
Chris Lattner0369c572008-11-23 23:12:31 +00001960 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001961 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001962 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidis3b60cff2012-03-13 01:09:36 +00001963 if (SDecl && !SDecl->hasDefinition())
Craig Topperc3ec1492014-05-26 06:22:03 +00001964 SDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001965 if (!SDecl)
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001966 Diag(SuperClassLoc, diag::err_undef_superclass)
1967 << SuperClassname << ClassName;
Douglas Gregor0b144e12011-12-15 00:29:59 +00001968 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00001969 // This implementation and its interface do not have the same
1970 // super class.
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001971 Diag(SuperClassLoc, diag::err_conflicting_super_class)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001972 << SDecl->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001973 Diag(SDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001974 }
1975 }
1976 }
Mike Stump11289f42009-09-09 15:08:12 +00001977
Chris Lattnerda463fe2007-12-12 07:09:47 +00001978 if (!IDecl) {
1979 // Legacy case of @implementation with no corresponding @interface.
1980 // Build, chain & install the interface decl into the identifier.
Daniel Dunbar73a73f52008-08-20 18:02:42 +00001981
Mike Stump87c57ac2009-05-16 07:39:55 +00001982 // FIXME: Do we support attributes on the @implementation? If so we should
1983 // copy them over.
Mike Stump11289f42009-09-09 15:08:12 +00001984 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001985 ClassName, /*typeParamList=*/nullptr,
1986 /*PrevDecl=*/nullptr, ClassLoc,
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00001987 true);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001988 AddPragmaAttributes(TUScope, IDecl);
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001989 IDecl->startDefinition();
Douglas Gregor16408322011-12-15 22:34:59 +00001990 if (SDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001991 IDecl->setSuperClass(Context.getTrivialTypeSourceInfo(
1992 Context.getObjCInterfaceType(SDecl),
1993 SuperClassLoc));
Douglas Gregor16408322011-12-15 22:34:59 +00001994 IDecl->setEndOfDefinitionLoc(SuperClassLoc);
1995 } else {
1996 IDecl->setEndOfDefinitionLoc(ClassLoc);
1997 }
1998
Douglas Gregorac345a32009-04-24 00:16:12 +00001999 PushOnScopeChains(IDecl, TUScope);
Douglas Gregor1c283312010-08-11 12:19:30 +00002000 } else {
2001 // Mark the interface as being completed, even if it was just as
2002 // @class ....;
2003 // declaration; the user cannot reopen it.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002004 if (!IDecl->hasDefinition())
2005 IDecl->startDefinition();
Chris Lattnerda463fe2007-12-12 07:09:47 +00002006 }
Mike Stump11289f42009-09-09 15:08:12 +00002007
2008 ObjCImplementationDecl* IMPDecl =
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00002009 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
Argyrios Kyrtzidisfac31622013-05-03 18:05:44 +00002010 ClassLoc, AtClassImplLoc, SuperClassLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002011
Anders Carlssona6b508a2008-11-04 16:57:32 +00002012 if (CheckObjCDeclScope(IMPDecl))
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00002013 return ActOnObjCContainerStartDefinition(IMPDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002014
Chris Lattnerda463fe2007-12-12 07:09:47 +00002015 // Check that there is no duplicate implementation of this class.
Douglas Gregor1c283312010-08-11 12:19:30 +00002016 if (IDecl->getImplementation()) {
2017 // FIXME: Don't leak everything!
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002018 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
Argyrios Kyrtzidis43cee9352009-07-21 00:06:04 +00002019 Diag(IDecl->getImplementation()->getLocation(),
2020 diag::note_previous_definition);
Argyrios Kyrtzidis0f6d5ca2013-05-30 18:53:21 +00002021 IMPDecl->setInvalidDecl();
Douglas Gregor1c283312010-08-11 12:19:30 +00002022 } else { // add it to the list.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002023 IDecl->setImplementation(IMPDecl);
Douglas Gregor79947a22009-04-24 00:11:27 +00002024 PushOnScopeChains(IMPDecl, TUScope);
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00002025 // Warn on implementating deprecated class under
2026 // -Wdeprecated-implementations flag.
Alex Lorenzf81d97e2017-07-13 16:35:59 +00002027 DiagnoseObjCImplementedDeprecations(*this, IDecl, IMPDecl->getLocation());
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002028 }
Douglas Gregor24ae22c2016-04-01 23:23:52 +00002029
2030 // If the superclass has the objc_runtime_visible attribute, we
2031 // cannot implement a subclass of it.
2032 if (IDecl->getSuperClass() &&
2033 IDecl->getSuperClass()->hasAttr<ObjCRuntimeVisibleAttr>()) {
2034 Diag(ClassLoc, diag::err_objc_runtime_visible_subclass)
2035 << IDecl->getDeclName()
2036 << IDecl->getSuperClass()->getDeclName();
2037 }
2038
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00002039 return ActOnObjCContainerStartDefinition(IMPDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002040}
2041
Argyrios Kyrtzidis2e85c5f2012-02-23 21:11:20 +00002042Sema::DeclGroupPtrTy
2043Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
2044 SmallVector<Decl *, 64> DeclsInGroup;
2045 DeclsInGroup.reserve(Decls.size() + 1);
2046
2047 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
2048 Decl *Dcl = Decls[i];
2049 if (!Dcl)
2050 continue;
2051 if (Dcl->getDeclContext()->isFileContext())
2052 Dcl->setTopLevelDeclInObjCContainer();
2053 DeclsInGroup.push_back(Dcl);
2054 }
2055
2056 DeclsInGroup.push_back(ObjCImpDecl);
2057
Richard Smith3beb7c62017-01-12 02:27:38 +00002058 return BuildDeclaratorGroup(DeclsInGroup);
Argyrios Kyrtzidis2e85c5f2012-02-23 21:11:20 +00002059}
2060
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002061void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
2062 ObjCIvarDecl **ivars, unsigned numIvars,
Chris Lattnerda463fe2007-12-12 07:09:47 +00002063 SourceLocation RBrace) {
2064 assert(ImpDecl && "missing implementation decl");
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002065 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
Chris Lattnerda463fe2007-12-12 07:09:47 +00002066 if (!IDecl)
2067 return;
James Dennett634962f2012-06-14 21:40:34 +00002068 /// Check case of non-existing \@interface decl.
2069 /// (legacy objective-c \@implementation decl without an \@interface decl).
Chris Lattnerda463fe2007-12-12 07:09:47 +00002070 /// Add implementations's ivar to the synthesize class's ivar list.
Steve Naroffaac654a2009-04-20 20:09:33 +00002071 if (IDecl->isImplicitInterfaceDecl()) {
Douglas Gregor16408322011-12-15 22:34:59 +00002072 IDecl->setEndOfDefinitionLoc(RBrace);
Fariborz Jahanian20912d62010-02-17 17:00:07 +00002073 // Add ivar's to class's DeclContext.
2074 for (unsigned i = 0, e = numIvars; i != e; ++i) {
Fariborz Jahanianc0309cd2010-02-17 18:10:54 +00002075 ivars[i]->setLexicalDeclContext(ImpDecl);
Richard Smith05afe5e2012-03-13 03:12:56 +00002076 IDecl->makeDeclVisibleInContext(ivars[i]);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00002077 ImpDecl->addDecl(ivars[i]);
Fariborz Jahanian20912d62010-02-17 17:00:07 +00002078 }
2079
Chris Lattnerda463fe2007-12-12 07:09:47 +00002080 return;
2081 }
2082 // If implementation has empty ivar list, just return.
2083 if (numIvars == 0)
2084 return;
Mike Stump11289f42009-09-09 15:08:12 +00002085
Chris Lattnerda463fe2007-12-12 07:09:47 +00002086 assert(ivars && "missing @implementation ivars");
John McCall5fb5df92012-06-20 06:18:46 +00002087 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002088 if (ImpDecl->getSuperClass())
2089 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
2090 for (unsigned i = 0; i < numIvars; i++) {
2091 ObjCIvarDecl* ImplIvar = ivars[i];
2092 if (const ObjCIvarDecl *ClsIvar =
2093 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2094 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2095 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2096 continue;
2097 }
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00002098 // Check class extensions (unnamed categories) for duplicate ivars.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002099 for (const auto *CDecl : IDecl->visible_extensions()) {
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00002100 if (const ObjCIvarDecl *ClsExtIvar =
2101 CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2102 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2103 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
2104 continue;
2105 }
2106 }
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002107 // Instance ivar to Implementation's DeclContext.
2108 ImplIvar->setLexicalDeclContext(ImpDecl);
Richard Smith05afe5e2012-03-13 03:12:56 +00002109 IDecl->makeDeclVisibleInContext(ImplIvar);
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002110 ImpDecl->addDecl(ImplIvar);
2111 }
2112 return;
2113 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002114 // Check interface's Ivar list against those in the implementation.
2115 // names and types must match.
2116 //
Chris Lattnerda463fe2007-12-12 07:09:47 +00002117 unsigned j = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002118 ObjCInterfaceDecl::ivar_iterator
Chris Lattner061227a2007-12-12 17:58:05 +00002119 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
2120 for (; numIvars > 0 && IVI != IVE; ++IVI) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002121 ObjCIvarDecl* ImplIvar = ivars[j++];
David Blaikie40ed2972012-06-06 20:45:41 +00002122 ObjCIvarDecl* ClsIvar = *IVI;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002123 assert (ImplIvar && "missing implementation ivar");
2124 assert (ClsIvar && "missing class ivar");
Mike Stump11289f42009-09-09 15:08:12 +00002125
Steve Naroff157599f2009-03-03 14:49:36 +00002126 // First, make sure the types match.
Richard Smithcaf33902011-10-10 18:28:20 +00002127 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
Chris Lattner3b054132008-11-19 05:08:23 +00002128 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002129 << ImplIvar->getIdentifier()
2130 << ImplIvar->getType() << ClsIvar->getType();
Chris Lattner0369c572008-11-23 23:12:31 +00002131 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
Richard Smithcaf33902011-10-10 18:28:20 +00002132 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
2133 ImplIvar->getBitWidthValue(Context) !=
2134 ClsIvar->getBitWidthValue(Context)) {
2135 Diag(ImplIvar->getBitWidth()->getLocStart(),
2136 diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier();
2137 Diag(ClsIvar->getBitWidth()->getLocStart(),
2138 diag::note_previous_definition);
Mike Stump11289f42009-09-09 15:08:12 +00002139 }
Steve Naroff157599f2009-03-03 14:49:36 +00002140 // Make sure the names are identical.
2141 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002142 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002143 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
Chris Lattner0369c572008-11-23 23:12:31 +00002144 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002145 }
2146 --numIvars;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002147 }
Mike Stump11289f42009-09-09 15:08:12 +00002148
Chris Lattner0f29d982007-12-12 18:11:49 +00002149 if (numIvars > 0)
Alp Tokerfff06742013-12-02 03:50:21 +00002150 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
Chris Lattner0f29d982007-12-12 18:11:49 +00002151 else if (IVI != IVE)
Alp Tokerfff06742013-12-02 03:50:21 +00002152 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002153}
2154
Ted Kremenekf87decd2013-12-13 05:58:44 +00002155static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
2156 ObjCMethodDecl *method,
2157 bool &IncompleteImpl,
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002158 unsigned DiagID,
Craig Topperc3ec1492014-05-26 06:22:03 +00002159 NamedDecl *NeededFor = nullptr) {
Fariborz Jahanian9fc39c42011-06-24 20:31:37 +00002160 // No point warning no definition of method which is 'unavailable'.
Douglas Gregorc2e3d5c2012-12-11 18:53:07 +00002161 switch (method->getAvailability()) {
2162 case AR_Available:
2163 case AR_Deprecated:
2164 break;
2165
2166 // Don't warn about unavailable or not-yet-introduced methods.
2167 case AR_NotYetIntroduced:
2168 case AR_Unavailable:
Fariborz Jahanian9fc39c42011-06-24 20:31:37 +00002169 return;
Douglas Gregorc2e3d5c2012-12-11 18:53:07 +00002170 }
2171
Ted Kremenek65d63572013-03-27 00:02:21 +00002172 // FIXME: For now ignore 'IncompleteImpl'.
2173 // Previously we grouped all unimplemented methods under a single
2174 // warning, but some users strongly voiced that they would prefer
2175 // separate warnings. We will give that approach a try, as that
2176 // matches what we do with protocols.
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002177 {
2178 const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
2179 B << method;
2180 if (NeededFor)
2181 B << NeededFor;
2182 }
Ted Kremenek65d63572013-03-27 00:02:21 +00002183
2184 // Issue a note to the original declaration.
2185 SourceLocation MethodLoc = method->getLocStart();
2186 if (MethodLoc.isValid())
Ted Kremenekf87decd2013-12-13 05:58:44 +00002187 S.Diag(MethodLoc, diag::note_method_declared_at) << method;
Steve Naroff15833ed2008-02-10 21:38:56 +00002188}
2189
David Chisnallb62d15c2010-10-25 17:23:52 +00002190/// Determines if type B can be substituted for type A. Returns true if we can
2191/// guarantee that anything that the user will do to an object of type A can
2192/// also be done to an object of type B. This is trivially true if the two
2193/// types are the same, or if B is a subclass of A. It becomes more complex
2194/// in cases where protocols are involved.
2195///
2196/// Object types in Objective-C describe the minimum requirements for an
2197/// object, rather than providing a complete description of a type. For
2198/// example, if A is a subclass of B, then B* may refer to an instance of A.
2199/// The principle of substitutability means that we may use an instance of A
2200/// anywhere that we may use an instance of B - it will implement all of the
2201/// ivars of B and all of the methods of B.
2202///
2203/// This substitutability is important when type checking methods, because
2204/// the implementation may have stricter type definitions than the interface.
2205/// The interface specifies minimum requirements, but the implementation may
2206/// have more accurate ones. For example, a method may privately accept
2207/// instances of B, but only publish that it accepts instances of A. Any
2208/// object passed to it will be type checked against B, and so will implicitly
2209/// by a valid A*. Similarly, a method may return a subclass of the class that
2210/// it is declared as returning.
2211///
2212/// This is most important when considering subclassing. A method in a
2213/// subclass must accept any object as an argument that its superclass's
2214/// implementation accepts. It may, however, accept a more general type
2215/// without breaking substitutability (i.e. you can still use the subclass
2216/// anywhere that you can use the superclass, but not vice versa). The
2217/// converse requirement applies to return types: the return type for a
2218/// subclass method must be a valid object of the kind that the superclass
2219/// advertises, but it may be specified more accurately. This avoids the need
2220/// for explicit down-casting by callers.
2221///
2222/// Note: This is a stricter requirement than for assignment.
John McCall071df462010-10-28 02:34:38 +00002223static bool isObjCTypeSubstitutable(ASTContext &Context,
2224 const ObjCObjectPointerType *A,
2225 const ObjCObjectPointerType *B,
2226 bool rejectId) {
2227 // Reject a protocol-unqualified id.
2228 if (rejectId && B->isObjCIdType()) return false;
David Chisnallb62d15c2010-10-25 17:23:52 +00002229
2230 // If B is a qualified id, then A must also be a qualified id and it must
2231 // implement all of the protocols in B. It may not be a qualified class.
2232 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
2233 // stricter definition so it is not substitutable for id<A>.
2234 if (B->isObjCQualifiedIdType()) {
2235 return A->isObjCQualifiedIdType() &&
John McCall071df462010-10-28 02:34:38 +00002236 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
2237 QualType(B,0),
2238 false);
David Chisnallb62d15c2010-10-25 17:23:52 +00002239 }
2240
2241 /*
2242 // id is a special type that bypasses type checking completely. We want a
2243 // warning when it is used in one place but not another.
2244 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
2245
2246
2247 // If B is a qualified id, then A must also be a qualified id (which it isn't
2248 // if we've got this far)
2249 if (B->isObjCQualifiedIdType()) return false;
2250 */
2251
2252 // Now we know that A and B are (potentially-qualified) class types. The
2253 // normal rules for assignment apply.
John McCall071df462010-10-28 02:34:38 +00002254 return Context.canAssignObjCInterfaces(A, B);
David Chisnallb62d15c2010-10-25 17:23:52 +00002255}
2256
John McCall071df462010-10-28 02:34:38 +00002257static SourceRange getTypeRange(TypeSourceInfo *TSI) {
2258 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
2259}
2260
Douglas Gregor813a0662015-06-19 18:14:38 +00002261/// Determine whether two set of Objective-C declaration qualifiers conflict.
2262static bool objcModifiersConflict(Decl::ObjCDeclQualifier x,
2263 Decl::ObjCDeclQualifier y) {
2264 return (x & ~Decl::OBJC_TQ_CSNullability) !=
2265 (y & ~Decl::OBJC_TQ_CSNullability);
2266}
2267
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002268static bool CheckMethodOverrideReturn(Sema &S,
John McCall071df462010-10-28 02:34:38 +00002269 ObjCMethodDecl *MethodImpl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002270 ObjCMethodDecl *MethodDecl,
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002271 bool IsProtocolMethodDecl,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002272 bool IsOverridingMode,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002273 bool Warn) {
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002274 if (IsProtocolMethodDecl &&
Douglas Gregor813a0662015-06-19 18:14:38 +00002275 objcModifiersConflict(MethodDecl->getObjCDeclQualifier(),
2276 MethodImpl->getObjCDeclQualifier())) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002277 if (Warn) {
Alp Toker314cc812014-01-25 16:55:45 +00002278 S.Diag(MethodImpl->getLocation(),
2279 (IsOverridingMode
2280 ? diag::warn_conflicting_overriding_ret_type_modifiers
2281 : diag::warn_conflicting_ret_type_modifiers))
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002282 << MethodImpl->getDeclName()
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002283 << MethodImpl->getReturnTypeSourceRange();
Alp Toker314cc812014-01-25 16:55:45 +00002284 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002285 << MethodDecl->getReturnTypeSourceRange();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002286 }
2287 else
2288 return false;
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002289 }
Douglas Gregor813a0662015-06-19 18:14:38 +00002290 if (Warn && IsOverridingMode &&
2291 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2292 !S.Context.hasSameNullabilityTypeQualifier(MethodImpl->getReturnType(),
2293 MethodDecl->getReturnType(),
2294 false)) {
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002295 auto nullabilityMethodImpl =
2296 *MethodImpl->getReturnType()->getNullability(S.Context);
2297 auto nullabilityMethodDecl =
2298 *MethodDecl->getReturnType()->getNullability(S.Context);
Douglas Gregor813a0662015-06-19 18:14:38 +00002299 S.Diag(MethodImpl->getLocation(),
2300 diag::warn_conflicting_nullability_attr_overriding_ret_types)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002301 << DiagNullabilityKind(
2302 nullabilityMethodImpl,
2303 ((MethodImpl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2304 != 0))
2305 << DiagNullabilityKind(
2306 nullabilityMethodDecl,
2307 ((MethodDecl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2308 != 0));
Douglas Gregor813a0662015-06-19 18:14:38 +00002309 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2310 }
2311
Alp Toker314cc812014-01-25 16:55:45 +00002312 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
2313 MethodDecl->getReturnType()))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002314 return true;
2315 if (!Warn)
2316 return false;
John McCall071df462010-10-28 02:34:38 +00002317
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002318 unsigned DiagID =
2319 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
2320 : diag::warn_conflicting_ret_types;
John McCall071df462010-10-28 02:34:38 +00002321
2322 // Mismatches between ObjC pointers go into a different warning
2323 // category, and sometimes they're even completely whitelisted.
2324 if (const ObjCObjectPointerType *ImplPtrTy =
Alp Toker314cc812014-01-25 16:55:45 +00002325 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
John McCall071df462010-10-28 02:34:38 +00002326 if (const ObjCObjectPointerType *IfacePtrTy =
Alp Toker314cc812014-01-25 16:55:45 +00002327 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
John McCall071df462010-10-28 02:34:38 +00002328 // Allow non-matching return types as long as they don't violate
2329 // the principle of substitutability. Specifically, we permit
2330 // return types that are subclasses of the declared return type,
2331 // or that are more-qualified versions of the declared type.
2332 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002333 return false;
John McCall071df462010-10-28 02:34:38 +00002334
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002335 DiagID =
2336 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002337 : diag::warn_non_covariant_ret_types;
John McCall071df462010-10-28 02:34:38 +00002338 }
2339 }
2340
2341 S.Diag(MethodImpl->getLocation(), DiagID)
Alp Toker314cc812014-01-25 16:55:45 +00002342 << MethodImpl->getDeclName() << MethodDecl->getReturnType()
2343 << MethodImpl->getReturnType()
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002344 << MethodImpl->getReturnTypeSourceRange();
Alp Toker314cc812014-01-25 16:55:45 +00002345 S.Diag(MethodDecl->getLocation(), IsOverridingMode
2346 ? diag::note_previous_declaration
2347 : diag::note_previous_definition)
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002348 << MethodDecl->getReturnTypeSourceRange();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002349 return false;
John McCall071df462010-10-28 02:34:38 +00002350}
2351
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002352static bool CheckMethodOverrideParam(Sema &S,
John McCall071df462010-10-28 02:34:38 +00002353 ObjCMethodDecl *MethodImpl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002354 ObjCMethodDecl *MethodDecl,
John McCall071df462010-10-28 02:34:38 +00002355 ParmVarDecl *ImplVar,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002356 ParmVarDecl *IfaceVar,
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002357 bool IsProtocolMethodDecl,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002358 bool IsOverridingMode,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002359 bool Warn) {
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002360 if (IsProtocolMethodDecl &&
Douglas Gregor813a0662015-06-19 18:14:38 +00002361 objcModifiersConflict(ImplVar->getObjCDeclQualifier(),
2362 IfaceVar->getObjCDeclQualifier())) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002363 if (Warn) {
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002364 if (IsOverridingMode)
2365 S.Diag(ImplVar->getLocation(),
2366 diag::warn_conflicting_overriding_param_modifiers)
2367 << getTypeRange(ImplVar->getTypeSourceInfo())
2368 << MethodImpl->getDeclName();
2369 else S.Diag(ImplVar->getLocation(),
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002370 diag::warn_conflicting_param_modifiers)
2371 << getTypeRange(ImplVar->getTypeSourceInfo())
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002372 << MethodImpl->getDeclName();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002373 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
2374 << getTypeRange(IfaceVar->getTypeSourceInfo());
2375 }
2376 else
2377 return false;
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002378 }
2379
John McCall071df462010-10-28 02:34:38 +00002380 QualType ImplTy = ImplVar->getType();
2381 QualType IfaceTy = IfaceVar->getType();
Douglas Gregor813a0662015-06-19 18:14:38 +00002382 if (Warn && IsOverridingMode &&
2383 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2384 !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) {
Douglas Gregor813a0662015-06-19 18:14:38 +00002385 S.Diag(ImplVar->getLocation(),
2386 diag::warn_conflicting_nullability_attr_overriding_param_types)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002387 << DiagNullabilityKind(
2388 *ImplTy->getNullability(S.Context),
2389 ((ImplVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2390 != 0))
2391 << DiagNullabilityKind(
2392 *IfaceTy->getNullability(S.Context),
2393 ((IfaceVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2394 != 0));
2395 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration);
Douglas Gregor813a0662015-06-19 18:14:38 +00002396 }
John McCall071df462010-10-28 02:34:38 +00002397 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002398 return true;
Manman Renc5705ba2016-09-13 17:41:05 +00002399
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002400 if (!Warn)
2401 return false;
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002402 unsigned DiagID =
2403 IsOverridingMode ? diag::warn_conflicting_overriding_param_types
2404 : diag::warn_conflicting_param_types;
John McCall071df462010-10-28 02:34:38 +00002405
2406 // Mismatches between ObjC pointers go into a different warning
2407 // category, and sometimes they're even completely whitelisted.
2408 if (const ObjCObjectPointerType *ImplPtrTy =
2409 ImplTy->getAs<ObjCObjectPointerType>()) {
2410 if (const ObjCObjectPointerType *IfacePtrTy =
2411 IfaceTy->getAs<ObjCObjectPointerType>()) {
2412 // Allow non-matching argument types as long as they don't
2413 // violate the principle of substitutability. Specifically, the
2414 // implementation must accept any objects that the superclass
2415 // accepts, however it may also accept others.
2416 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002417 return false;
John McCall071df462010-10-28 02:34:38 +00002418
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002419 DiagID =
2420 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002421 : diag::warn_non_contravariant_param_types;
John McCall071df462010-10-28 02:34:38 +00002422 }
2423 }
2424
2425 S.Diag(ImplVar->getLocation(), DiagID)
2426 << getTypeRange(ImplVar->getTypeSourceInfo())
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002427 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
2428 S.Diag(IfaceVar->getLocation(),
2429 (IsOverridingMode ? diag::note_previous_declaration
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002430 : diag::note_previous_definition))
John McCall071df462010-10-28 02:34:38 +00002431 << getTypeRange(IfaceVar->getTypeSourceInfo());
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002432 return false;
John McCall071df462010-10-28 02:34:38 +00002433}
John McCall31168b02011-06-15 23:02:42 +00002434
2435/// In ARC, check whether the conventional meanings of the two methods
2436/// match. If they don't, it's a hard error.
2437static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
2438 ObjCMethodDecl *decl) {
2439 ObjCMethodFamily implFamily = impl->getMethodFamily();
2440 ObjCMethodFamily declFamily = decl->getMethodFamily();
2441 if (implFamily == declFamily) return false;
2442
2443 // Since conventions are sorted by selector, the only possibility is
2444 // that the types differ enough to cause one selector or the other
2445 // to fall out of the family.
2446 assert(implFamily == OMF_None || declFamily == OMF_None);
2447
2448 // No further diagnostics required on invalid declarations.
2449 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
2450
2451 const ObjCMethodDecl *unmatched = impl;
2452 ObjCMethodFamily family = declFamily;
2453 unsigned errorID = diag::err_arc_lost_method_convention;
2454 unsigned noteID = diag::note_arc_lost_method_convention;
2455 if (declFamily == OMF_None) {
2456 unmatched = decl;
2457 family = implFamily;
2458 errorID = diag::err_arc_gained_method_convention;
2459 noteID = diag::note_arc_gained_method_convention;
2460 }
2461
2462 // Indexes into a %select clause in the diagnostic.
2463 enum FamilySelector {
2464 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
2465 };
2466 FamilySelector familySelector = FamilySelector();
2467
2468 switch (family) {
2469 case OMF_None: llvm_unreachable("logic error, no method convention");
2470 case OMF_retain:
2471 case OMF_release:
2472 case OMF_autorelease:
2473 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +00002474 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002475 case OMF_retainCount:
2476 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002477 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002478 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00002479 // Mismatches for these methods don't change ownership
2480 // conventions, so we don't care.
2481 return false;
2482
2483 case OMF_init: familySelector = F_init; break;
2484 case OMF_alloc: familySelector = F_alloc; break;
2485 case OMF_copy: familySelector = F_copy; break;
2486 case OMF_mutableCopy: familySelector = F_mutableCopy; break;
2487 case OMF_new: familySelector = F_new; break;
2488 }
2489
2490 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
2491 ReasonSelector reasonSelector;
2492
2493 // The only reason these methods don't fall within their families is
2494 // due to unusual result types.
Alp Toker314cc812014-01-25 16:55:45 +00002495 if (unmatched->getReturnType()->isObjCObjectPointerType()) {
John McCall31168b02011-06-15 23:02:42 +00002496 reasonSelector = R_UnrelatedReturn;
2497 } else {
2498 reasonSelector = R_NonObjectReturn;
2499 }
2500
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00002501 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
2502 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
John McCall31168b02011-06-15 23:02:42 +00002503
2504 return true;
2505}
John McCall071df462010-10-28 02:34:38 +00002506
Fariborz Jahanian7988d7d2008-12-05 18:18:52 +00002507void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002508 ObjCMethodDecl *MethodDecl,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002509 bool IsProtocolMethodDecl) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002510 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002511 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
2512 return;
2513
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002514 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002515 IsProtocolMethodDecl, false,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002516 true);
Mike Stump11289f42009-09-09 15:08:12 +00002517
Chris Lattner67f35b02009-04-11 19:58:42 +00002518 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002519 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2520 EF = MethodDecl->param_end();
2521 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002522 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002523 IsProtocolMethodDecl, false, true);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002524 }
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002525
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002526 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002527 Diag(ImpMethodDecl->getLocation(),
2528 diag::warn_conflicting_variadic);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002529 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002530 }
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002531}
2532
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002533void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2534 ObjCMethodDecl *Overridden,
2535 bool IsProtocolMethodDecl) {
2536
2537 CheckMethodOverrideReturn(*this, Method, Overridden,
2538 IsProtocolMethodDecl, true,
2539 true);
2540
2541 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002542 IF = Overridden->param_begin(), EM = Method->param_end(),
2543 EF = Overridden->param_end();
2544 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002545 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
2546 IsProtocolMethodDecl, true, true);
2547 }
2548
2549 if (Method->isVariadic() != Overridden->isVariadic()) {
2550 Diag(Method->getLocation(),
2551 diag::warn_conflicting_overriding_variadic);
2552 Diag(Overridden->getLocation(), diag::note_previous_declaration);
2553 }
2554}
2555
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002556/// WarnExactTypedMethods - This routine issues a warning if method
2557/// implementation declaration matches exactly that of its declaration.
2558void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2559 ObjCMethodDecl *MethodDecl,
2560 bool IsProtocolMethodDecl) {
2561 // don't issue warning when protocol method is optional because primary
2562 // class is not required to implement it and it is safe for protocol
2563 // to implement it.
2564 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
2565 return;
2566 // don't issue warning when primary class's method is
2567 // depecated/unavailable.
2568 if (MethodDecl->hasAttr<UnavailableAttr>() ||
2569 MethodDecl->hasAttr<DeprecatedAttr>())
2570 return;
2571
2572 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2573 IsProtocolMethodDecl, false, false);
2574 if (match)
2575 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002576 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2577 EF = MethodDecl->param_end();
2578 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002579 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
2580 *IM, *IF,
2581 IsProtocolMethodDecl, false, false);
2582 if (!match)
2583 break;
2584 }
2585 if (match)
2586 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
David Chisnall92918512011-08-08 17:32:19 +00002587 if (match)
2588 match = !(MethodDecl->isClassMethod() &&
2589 MethodDecl->getSelector() == GetNullarySelector("load", Context));
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002590
2591 if (match) {
2592 Diag(ImpMethodDecl->getLocation(),
2593 diag::warn_category_method_impl_match);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002594 Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
2595 << MethodDecl->getDeclName();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002596 }
2597}
2598
Mike Stump87c57ac2009-05-16 07:39:55 +00002599/// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
2600/// improve the efficiency of selector lookups and type checking by associating
2601/// with each protocol / interface / category the flattened instance tables. If
2602/// we used an immutable set to keep the table then it wouldn't add significant
2603/// memory cost and it would be handy for lookups.
Daniel Dunbar4684f372008-08-27 05:40:03 +00002604
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002605typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
Ahmed Charlesaf94d562014-03-09 11:34:25 +00002606typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002607
2608static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
2609 ProtocolNameSet &PNS) {
2610 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
2611 PNS.insert(PDecl->getIdentifier());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002612 for (const auto *PI : PDecl->protocols())
2613 findProtocolsWithExplicitImpls(PI, PNS);
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002614}
2615
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002616/// Recursively populates a set with all conformed protocols in a class
2617/// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
2618/// attribute.
2619static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
2620 ProtocolNameSet &PNS) {
2621 if (!Super)
2622 return;
2623
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002624 for (const auto *I : Super->all_referenced_protocols())
2625 findProtocolsWithExplicitImpls(I, PNS);
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002626
2627 findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002628}
2629
Steve Naroffa36992242008-02-08 22:06:17 +00002630/// CheckProtocolMethodDefs - This routine checks unimplemented methods
Chris Lattnerda463fe2007-12-12 07:09:47 +00002631/// Declared in protocol, and those referenced by it.
Ted Kremenek285ee852013-12-13 06:26:10 +00002632static void CheckProtocolMethodDefs(Sema &S,
2633 SourceLocation ImpLoc,
2634 ObjCProtocolDecl *PDecl,
2635 bool& IncompleteImpl,
2636 const Sema::SelectorSet &InsMap,
2637 const Sema::SelectorSet &ClsMap,
Ted Kremenek33e430f2013-12-13 06:26:14 +00002638 ObjCContainerDecl *CDecl,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002639 LazyProtocolNameSet &ProtocolsExplictImpl) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002640 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
2641 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
2642 : dyn_cast<ObjCInterfaceDecl>(CDecl);
Fariborz Jahanian2e8074b2010-03-27 21:10:05 +00002643 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
2644
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002645 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
Craig Topperc3ec1492014-05-26 06:22:03 +00002646 ObjCInterfaceDecl *NSIDecl = nullptr;
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002647
2648 // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
2649 // then we should check if any class in the super class hierarchy also
2650 // conforms to this protocol, either directly or via protocol inheritance.
2651 // If so, we can skip checking this protocol completely because we
2652 // know that a parent class already satisfies this protocol.
2653 //
2654 // Note: we could generalize this logic for all protocols, and merely
2655 // add the limit on looking at the super class chain for just
2656 // specially marked protocols. This may be a good optimization. This
2657 // change is restricted to 'objc_protocol_requires_explicit_implementation'
2658 // protocols for now for controlled evaluation.
2659 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
Ahmed Charlesaf94d562014-03-09 11:34:25 +00002660 if (!ProtocolsExplictImpl) {
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002661 ProtocolsExplictImpl.reset(new ProtocolNameSet);
2662 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
2663 }
2664 if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
2665 ProtocolsExplictImpl->end())
2666 return;
2667
2668 // If no super class conforms to the protocol, we should not search
2669 // for methods in the super class to implicitly satisfy the protocol.
Craig Topperc3ec1492014-05-26 06:22:03 +00002670 Super = nullptr;
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002671 }
2672
Ted Kremenek285ee852013-12-13 06:26:10 +00002673 if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
Mike Stump11289f42009-09-09 15:08:12 +00002674 // check to see if class implements forwardInvocation method and objects
2675 // of this class are derived from 'NSProxy' so that to forward requests
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002676 // from one object to another.
Mike Stump11289f42009-09-09 15:08:12 +00002677 // Under such conditions, which means that every method possible is
2678 // implemented in the class, we should not issue "Method definition not
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002679 // found" warnings.
2680 // FIXME: Use a general GetUnarySelector method for this.
Ted Kremenek285ee852013-12-13 06:26:10 +00002681 IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
2682 Selector fISelector = S.Context.Selectors.getSelector(1, &II);
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002683 if (InsMap.count(fISelector))
2684 // Is IDecl derived from 'NSProxy'? If so, no instance methods
2685 // need be implemented in the implementation.
Ted Kremenek285ee852013-12-13 06:26:10 +00002686 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002687 }
Mike Stump11289f42009-09-09 15:08:12 +00002688
Fariborz Jahanianc41cf052013-01-07 19:21:03 +00002689 // If this is a forward protocol declaration, get its definition.
2690 if (!PDecl->isThisDeclarationADefinition() &&
2691 PDecl->getDefinition())
2692 PDecl = PDecl->getDefinition();
2693
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002694 // If a method lookup fails locally we still need to look and see if
2695 // the method was implemented by a base class or an inherited
2696 // protocol. This lookup is slow, but occurs rarely in correct code
2697 // and otherwise would terminate in a warning.
2698
Chris Lattnerda463fe2007-12-12 07:09:47 +00002699 // check unimplemented instance methods.
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002700 if (!NSIDecl)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002701 for (auto *method : PDecl->instance_methods()) {
Mike Stump11289f42009-09-09 15:08:12 +00002702 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
Jordan Rosed01e83a2012-10-10 16:42:25 +00002703 !method->isPropertyAccessor() &&
2704 !InsMap.count(method->getSelector()) &&
Ted Kremenek00781502013-11-23 01:01:29 +00002705 (!Super || !Super->lookupMethod(method->getSelector(),
2706 true /* instance */,
2707 false /* shallowCategory */,
Ted Kremenek28eace62013-11-23 01:01:34 +00002708 true /* followsSuper */,
Craig Topperc3ec1492014-05-26 06:22:03 +00002709 nullptr /* category */))) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002710 // If a method is not implemented in the category implementation but
2711 // has been declared in its primary class, superclass,
2712 // or in one of their protocols, no need to issue the warning.
2713 // This is because method will be implemented in the primary class
2714 // or one of its super class implementation.
2715
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002716 // Ugly, but necessary. Method declared in protcol might have
2717 // have been synthesized due to a property declared in the class which
2718 // uses the protocol.
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002719 if (ObjCMethodDecl *MethodInClass =
Ted Kremenek00781502013-11-23 01:01:29 +00002720 IDecl->lookupMethod(method->getSelector(),
2721 true /* instance */,
2722 true /* shallowCategoryLookup */,
2723 false /* followSuper */))
Jordan Rosed01e83a2012-10-10 16:42:25 +00002724 if (C || MethodInClass->isPropertyAccessor())
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002725 continue;
2726 unsigned DIAG = diag::warn_unimplemented_protocol_method;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002727 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
Ted Kremenek285ee852013-12-13 06:26:10 +00002728 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002729 PDecl);
Fariborz Jahanian97752f72010-03-27 19:02:17 +00002730 }
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002731 }
2732 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002733 // check unimplemented class methods
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002734 for (auto *method : PDecl->class_methods()) {
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002735 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
2736 !ClsMap.count(method->getSelector()) &&
Ted Kremenek00781502013-11-23 01:01:29 +00002737 (!Super || !Super->lookupMethod(method->getSelector(),
2738 false /* class method */,
2739 false /* shallowCategoryLookup */,
Ted Kremenek28eace62013-11-23 01:01:34 +00002740 true /* followSuper */,
Craig Topperc3ec1492014-05-26 06:22:03 +00002741 nullptr /* category */))) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002742 // See above comment for instance method lookups.
Ted Kremenek00781502013-11-23 01:01:29 +00002743 if (C && IDecl->lookupMethod(method->getSelector(),
2744 false /* class */,
2745 true /* shallowCategoryLookup */,
2746 false /* followSuper */))
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002747 continue;
Ted Kremenek00781502013-11-23 01:01:29 +00002748
Fariborz Jahanianc1fb8622010-03-31 18:23:33 +00002749 unsigned DIAG = diag::warn_unimplemented_protocol_method;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002750 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
Ted Kremenek285ee852013-12-13 06:26:10 +00002751 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
Fariborz Jahanianc1fb8622010-03-31 18:23:33 +00002752 }
Fariborz Jahanian97752f72010-03-27 19:02:17 +00002753 }
Steve Naroff3ce37a62007-12-14 23:37:57 +00002754 }
Chris Lattner390d39a2008-07-21 21:32:27 +00002755 // Check on this protocols's referenced protocols, recursively.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002756 for (auto *PI : PDecl->protocols())
2757 CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002758 CDecl, ProtocolsExplictImpl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002759}
2760
Fariborz Jahanianf9ae68a2011-07-16 00:08:33 +00002761/// MatchAllMethodDeclarations - Check methods declared in interface
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002762/// or protocol against those declared in their implementations.
2763///
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002764void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
2765 const SelectorSet &ClsMap,
2766 SelectorSet &InsMapSeen,
2767 SelectorSet &ClsMapSeen,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002768 ObjCImplDecl* IMPDecl,
2769 ObjCContainerDecl* CDecl,
2770 bool &IncompleteImpl,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002771 bool ImmediateClass,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002772 bool WarnCategoryMethodImpl) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002773 // Check and see if instance methods in class interface have been
2774 // implemented in the implementation class. If so, their types match.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002775 for (auto *I : CDecl->instance_methods()) {
David Blaikie82e95a32014-11-19 07:49:47 +00002776 if (!InsMapSeen.insert(I->getSelector()).second)
Benjamin Kramer9f8e2d72013-10-14 15:16:10 +00002777 continue;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002778 if (!I->isPropertyAccessor() &&
2779 !InsMap.count(I->getSelector())) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002780 if (ImmediateClass)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002781 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
Ted Kremenek65d63572013-03-27 00:02:21 +00002782 diag::warn_undef_method_impl);
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002783 continue;
Mike Stump12b8ce12009-08-04 21:02:39 +00002784 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002785 ObjCMethodDecl *ImpMethodDecl =
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002786 IMPDecl->getInstanceMethod(I->getSelector());
Manman Rena58f92f2016-10-11 21:18:20 +00002787 assert(CDecl->getInstanceMethod(I->getSelector(), true/*AllowHidden*/) &&
Argyrios Kyrtzidis342e08f2011-08-30 19:43:21 +00002788 "Expected to find the method through lookup as well");
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002789 // ImpMethodDecl may be null as in a @dynamic property.
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002790 if (ImpMethodDecl) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002791 if (!WarnCategoryMethodImpl)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002792 WarnConflictingTypedMethods(ImpMethodDecl, I,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002793 isa<ObjCProtocolDecl>(CDecl));
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002794 else if (!I->isPropertyAccessor())
2795 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002796 }
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002797 }
2798 }
Mike Stump11289f42009-09-09 15:08:12 +00002799
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002800 // Check and see if class methods in class interface have been
2801 // implemented in the implementation class. If so, their types match.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002802 for (auto *I : CDecl->class_methods()) {
David Blaikie82e95a32014-11-19 07:49:47 +00002803 if (!ClsMapSeen.insert(I->getSelector()).second)
Benjamin Kramer9f8e2d72013-10-14 15:16:10 +00002804 continue;
Manman Rend36f7d52016-01-27 20:10:32 +00002805 if (!I->isPropertyAccessor() &&
2806 !ClsMap.count(I->getSelector())) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002807 if (ImmediateClass)
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002808 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
Ted Kremenek65d63572013-03-27 00:02:21 +00002809 diag::warn_undef_method_impl);
Mike Stump12b8ce12009-08-04 21:02:39 +00002810 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002811 ObjCMethodDecl *ImpMethodDecl =
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002812 IMPDecl->getClassMethod(I->getSelector());
Manman Rena58f92f2016-10-11 21:18:20 +00002813 assert(CDecl->getClassMethod(I->getSelector(), true/*AllowHidden*/) &&
Argyrios Kyrtzidis342e08f2011-08-30 19:43:21 +00002814 "Expected to find the method through lookup as well");
Manman Rend36f7d52016-01-27 20:10:32 +00002815 // ImpMethodDecl may be null as in a @dynamic property.
2816 if (ImpMethodDecl) {
2817 if (!WarnCategoryMethodImpl)
2818 WarnConflictingTypedMethods(ImpMethodDecl, I,
2819 isa<ObjCProtocolDecl>(CDecl));
2820 else if (!I->isPropertyAccessor())
2821 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2822 }
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002823 }
2824 }
Fariborz Jahanian73853e52010-10-08 22:59:25 +00002825
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002826 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
2827 // Also, check for methods declared in protocols inherited by
2828 // this protocol.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002829 for (auto *PI : PD->protocols())
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002830 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002831 IMPDecl, PI, IncompleteImpl, false,
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002832 WarnCategoryMethodImpl);
2833 }
2834
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002835 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002836 // when checking that methods in implementation match their declaration,
2837 // i.e. when WarnCategoryMethodImpl is false, check declarations in class
2838 // extension; as well as those in categories.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002839 if (!WarnCategoryMethodImpl) {
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002840 for (auto *Cat : I->visible_categories())
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002841 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Argyrios Kyrtzidis3a437542015-10-13 23:27:34 +00002842 IMPDecl, Cat, IncompleteImpl,
2843 ImmediateClass && Cat->IsClassExtension(),
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002844 WarnCategoryMethodImpl);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002845 } else {
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002846 // Also methods in class extensions need be looked at next.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002847 for (auto *Ext : I->visible_extensions())
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002848 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002849 IMPDecl, Ext, IncompleteImpl, false,
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002850 WarnCategoryMethodImpl);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002851 }
2852
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002853 // Check for any implementation of a methods declared in protocol.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002854 for (auto *PI : I->all_referenced_protocols())
Mike Stump11289f42009-09-09 15:08:12 +00002855 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002856 IMPDecl, PI, IncompleteImpl, false,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002857 WarnCategoryMethodImpl);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002858
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002859 // FIXME. For now, we are not checking for extact match of methods
2860 // in category implementation and its primary class's super class.
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002861 if (!WarnCategoryMethodImpl && I->getSuperClass())
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002862 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Mike Stump11289f42009-09-09 15:08:12 +00002863 IMPDecl,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002864 I->getSuperClass(), IncompleteImpl, false);
2865 }
2866}
2867
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002868/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2869/// category matches with those implemented in its primary class and
2870/// warns each time an exact match is found.
2871void Sema::CheckCategoryVsClassMethodMatches(
2872 ObjCCategoryImplDecl *CatIMPDecl) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002873 // Get category's primary class.
2874 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
2875 if (!CatDecl)
2876 return;
2877 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
2878 if (!IDecl)
2879 return;
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002880 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
2881 SelectorSet InsMap, ClsMap;
2882
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002883 for (const auto *I : CatIMPDecl->instance_methods()) {
2884 Selector Sel = I->getSelector();
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002885 // When checking for methods implemented in the category, skip over
2886 // those declared in category class's super class. This is because
2887 // the super class must implement the method.
2888 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
2889 continue;
2890 InsMap.insert(Sel);
2891 }
2892
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002893 for (const auto *I : CatIMPDecl->class_methods()) {
2894 Selector Sel = I->getSelector();
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002895 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
2896 continue;
2897 ClsMap.insert(Sel);
2898 }
2899 if (InsMap.empty() && ClsMap.empty())
2900 return;
2901
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002902 SelectorSet InsMapSeen, ClsMapSeen;
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002903 bool IncompleteImpl = false;
2904 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2905 CatIMPDecl, IDecl,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002906 IncompleteImpl, false,
2907 true /*WarnCategoryMethodImpl*/);
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002908}
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002909
Fariborz Jahanian25491a22010-05-05 21:52:17 +00002910void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002911 ObjCContainerDecl* CDecl,
Chris Lattner9ef10f42009-03-01 00:56:52 +00002912 bool IncompleteImpl) {
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002913 SelectorSet InsMap;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002914 // Check and see if instance methods in class interface have been
2915 // implemented in the implementation class.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002916 for (const auto *I : IMPDecl->instance_methods())
2917 InsMap.insert(I->getSelector());
Mike Stump11289f42009-09-09 15:08:12 +00002918
Douglas Gregoracf4fd32015-11-03 01:15:46 +00002919 // Add the selectors for getters/setters of @dynamic properties.
2920 for (const auto *PImpl : IMPDecl->property_impls()) {
2921 // We only care about @dynamic implementations.
2922 if (PImpl->getPropertyImplementation() != ObjCPropertyImplDecl::Dynamic)
2923 continue;
2924
2925 const auto *P = PImpl->getPropertyDecl();
2926 if (!P) continue;
2927
2928 InsMap.insert(P->getGetterName());
2929 if (!P->getSetterName().isNull())
2930 InsMap.insert(P->getSetterName());
2931 }
2932
Fariborz Jahanian6c6aea92009-04-14 23:15:21 +00002933 // Check and see if properties declared in the interface have either 1)
2934 // an implementation or 2) there is a @synthesize/@dynamic implementation
2935 // of the property in the @implementation.
Ted Kremenek348e88c2014-02-21 19:41:34 +00002936 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2937 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
2938 LangOpts.ObjCRuntime.isNonFragile() &&
2939 !IDecl->isObjCRequiresPropertyDefs();
2940 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
2941 }
2942
Douglas Gregor849ebc22015-06-19 18:14:46 +00002943 // Diagnose null-resettable synthesized setters.
2944 diagnoseNullResettableSynthesizedSetters(IMPDecl);
2945
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002946 SelectorSet ClsMap;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002947 for (const auto *I : IMPDecl->class_methods())
2948 ClsMap.insert(I->getSelector());
Mike Stump11289f42009-09-09 15:08:12 +00002949
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002950 // Check for type conflict of methods declared in a class/protocol and
2951 // its implementation; if any.
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002952 SelectorSet InsMapSeen, ClsMapSeen;
Mike Stump11289f42009-09-09 15:08:12 +00002953 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2954 IMPDecl, CDecl,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002955 IncompleteImpl, true);
Fariborz Jahanian2bda1b62011-08-03 18:21:12 +00002956
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002957 // check all methods implemented in category against those declared
2958 // in its primary class.
2959 if (ObjCCategoryImplDecl *CatDecl =
2960 dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
2961 CheckCategoryVsClassMethodMatches(CatDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002962
Chris Lattnerda463fe2007-12-12 07:09:47 +00002963 // Check the protocol list for unimplemented methods in the @implementation
2964 // class.
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002965 // Check and see if class methods in class interface have been
2966 // implemented in the implementation class.
Mike Stump11289f42009-09-09 15:08:12 +00002967
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002968 LazyProtocolNameSet ExplicitImplProtocols;
2969
Chris Lattner9ef10f42009-03-01 00:56:52 +00002970 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002971 for (auto *PI : I->all_referenced_protocols())
2972 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl,
2973 InsMap, ClsMap, I, ExplicitImplProtocols);
Chris Lattner9ef10f42009-03-01 00:56:52 +00002974 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahanian8764c742009-10-05 21:32:49 +00002975 // For extended class, unimplemented methods in its protocols will
2976 // be reported in the primary class.
Fariborz Jahanian30a42922010-02-15 21:55:26 +00002977 if (!C->IsClassExtension()) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002978 for (auto *P : C->protocols())
2979 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002980 IncompleteImpl, InsMap, ClsMap, CDecl,
2981 ExplicitImplProtocols);
Ted Kremenek348e88c2014-02-21 19:41:34 +00002982 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
Nico Weber2e0c8f72014-12-27 03:58:08 +00002983 /*SynthesizeProperties=*/false);
Fariborz Jahanian4f8a5712010-01-20 19:36:21 +00002984 }
Chris Lattner9ef10f42009-03-01 00:56:52 +00002985 } else
David Blaikie83d382b2011-09-23 05:06:16 +00002986 llvm_unreachable("invalid ObjCContainerDecl type.");
Chris Lattnerda463fe2007-12-12 07:09:47 +00002987}
2988
Fariborz Jahanian3a039e32011-08-27 20:50:59 +00002989Sema::DeclGroupPtrTy
Chris Lattnerda463fe2007-12-12 07:09:47 +00002990Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
Chris Lattner99a83312009-02-16 19:25:52 +00002991 IdentifierInfo **IdentList,
Ted Kremeneka26da852009-11-17 23:12:20 +00002992 SourceLocation *IdentLocs,
Douglas Gregor85f3f952015-07-07 03:57:15 +00002993 ArrayRef<ObjCTypeParamList *> TypeParamLists,
Chris Lattner99a83312009-02-16 19:25:52 +00002994 unsigned NumElts) {
Fariborz Jahanian3a039e32011-08-27 20:50:59 +00002995 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002996 for (unsigned i = 0; i != NumElts; ++i) {
2997 // Check for another declaration kind with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00002998 NamedDecl *PrevDecl
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002999 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
Douglas Gregorb8eaf292010-04-15 23:40:53 +00003000 LookupOrdinaryName, ForRedeclaration);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003001 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Steve Naroff946166f2008-06-05 22:57:10 +00003002 // GCC apparently allows the following idiom:
3003 //
3004 // typedef NSObject < XCElementTogglerP > XCElementToggler;
3005 // @class XCElementToggler;
3006 //
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003007 // Here we have chosen to ignore the forward class declaration
3008 // with a warning. Since this is the implied behavior.
Richard Smithdda56e42011-04-15 14:24:37 +00003009 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
John McCall8b07ec22010-05-15 11:32:37 +00003010 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003011 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
Chris Lattner0369c572008-11-23 23:12:31 +00003012 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall8b07ec22010-05-15 11:32:37 +00003013 } else {
Mike Stump12b8ce12009-08-04 21:02:39 +00003014 // a forward class declaration matching a typedef name of a class refers
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003015 // to the underlying class. Just ignore the forward class with a warning
Nico Weber2e0c8f72014-12-27 03:58:08 +00003016 // as this will force the intended behavior which is to lookup the
3017 // typedef name.
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003018 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003019 Diag(AtClassLoc, diag::warn_forward_class_redefinition)
3020 << IdentList[i];
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003021 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3022 continue;
3023 }
Fariborz Jahanian0d451812009-05-07 21:49:26 +00003024 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003025 }
Douglas Gregordc9166c2011-12-15 20:29:51 +00003026
3027 // Create a declaration to describe this forward declaration.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003028 ObjCInterfaceDecl *PrevIDecl
3029 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidisdd710632013-06-18 21:26:33 +00003030
3031 IdentifierInfo *ClassName = IdentList[i];
3032 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
3033 // A previous decl with a different name is because of
3034 // @compatibility_alias, for example:
3035 // \code
3036 // @class NewImage;
3037 // @compatibility_alias OldImage NewImage;
3038 // \endcode
3039 // A lookup for 'OldImage' will return the 'NewImage' decl.
3040 //
3041 // In such a case use the real declaration name, instead of the alias one,
3042 // otherwise we will break IdentifierResolver and redecls-chain invariants.
3043 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
3044 // has been aliased.
3045 ClassName = PrevIDecl->getIdentifier();
3046 }
3047
Douglas Gregor85f3f952015-07-07 03:57:15 +00003048 // If this forward declaration has type parameters, compare them with the
3049 // type parameters of the previous declaration.
3050 ObjCTypeParamList *TypeParams = TypeParamLists[i];
3051 if (PrevIDecl && TypeParams) {
3052 if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) {
3053 // Check for consistency with the previous declaration.
3054 if (checkTypeParamListConsistency(
3055 *this, PrevTypeParams, TypeParams,
3056 TypeParamListContext::ForwardDeclaration)) {
3057 TypeParams = nullptr;
3058 }
3059 } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
3060 // The @interface does not have type parameters. Complain.
3061 Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class)
3062 << ClassName
3063 << TypeParams->getSourceRange();
3064 Diag(Def->getLocation(), diag::note_defined_here)
3065 << ClassName;
3066
3067 TypeParams = nullptr;
3068 }
3069 }
3070
Douglas Gregordc9166c2011-12-15 20:29:51 +00003071 ObjCInterfaceDecl *IDecl
3072 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00003073 ClassName, TypeParams, PrevIDecl,
3074 IdentLocs[i]);
Douglas Gregordc9166c2011-12-15 20:29:51 +00003075 IDecl->setAtEndRange(IdentLocs[i]);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003076
Douglas Gregordc9166c2011-12-15 20:29:51 +00003077 PushOnScopeChains(IDecl, TUScope);
Douglas Gregordeafd0b2011-12-27 22:43:10 +00003078 CheckObjCDeclScope(IDecl);
3079 DeclsInGroup.push_back(IDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003080 }
Rafael Espindolaab417692013-07-09 12:05:01 +00003081
Richard Smith3beb7c62017-01-12 02:27:38 +00003082 return BuildDeclaratorGroup(DeclsInGroup);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003083}
3084
John McCall54507ab2011-06-16 01:15:19 +00003085static bool tryMatchRecordTypes(ASTContext &Context,
3086 Sema::MethodMatchStrategy strategy,
3087 const Type *left, const Type *right);
3088
John McCall31168b02011-06-15 23:02:42 +00003089static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
3090 QualType leftQT, QualType rightQT) {
3091 const Type *left =
3092 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
3093 const Type *right =
3094 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
3095
3096 if (left == right) return true;
3097
3098 // If we're doing a strict match, the types have to match exactly.
3099 if (strategy == Sema::MMS_strict) return false;
3100
3101 if (left->isIncompleteType() || right->isIncompleteType()) return false;
3102
3103 // Otherwise, use this absurdly complicated algorithm to try to
3104 // validate the basic, low-level compatibility of the two types.
3105
3106 // As a minimum, require the sizes and alignments to match.
David Majnemer34b57492014-07-30 01:30:47 +00003107 TypeInfo LeftTI = Context.getTypeInfo(left);
3108 TypeInfo RightTI = Context.getTypeInfo(right);
3109 if (LeftTI.Width != RightTI.Width)
3110 return false;
3111
3112 if (LeftTI.Align != RightTI.Align)
John McCall31168b02011-06-15 23:02:42 +00003113 return false;
3114
3115 // Consider all the kinds of non-dependent canonical types:
3116 // - functions and arrays aren't possible as return and parameter types
3117
3118 // - vector types of equal size can be arbitrarily mixed
3119 if (isa<VectorType>(left)) return isa<VectorType>(right);
3120 if (isa<VectorType>(right)) return false;
3121
3122 // - references should only match references of identical type
John McCall54507ab2011-06-16 01:15:19 +00003123 // - structs, unions, and Objective-C objects must match more-or-less
3124 // exactly
John McCall31168b02011-06-15 23:02:42 +00003125 // - everything else should be a scalar
3126 if (!left->isScalarType() || !right->isScalarType())
John McCall54507ab2011-06-16 01:15:19 +00003127 return tryMatchRecordTypes(Context, strategy, left, right);
John McCall31168b02011-06-15 23:02:42 +00003128
John McCall9320b872011-09-09 05:25:32 +00003129 // Make scalars agree in kind, except count bools as chars, and group
3130 // all non-member pointers together.
John McCall31168b02011-06-15 23:02:42 +00003131 Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
3132 Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
3133 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
3134 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
John McCall9320b872011-09-09 05:25:32 +00003135 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
3136 leftSK = Type::STK_ObjCObjectPointer;
3137 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
3138 rightSK = Type::STK_ObjCObjectPointer;
John McCall31168b02011-06-15 23:02:42 +00003139
3140 // Note that data member pointers and function member pointers don't
3141 // intermix because of the size differences.
3142
3143 return (leftSK == rightSK);
3144}
Chris Lattnerda463fe2007-12-12 07:09:47 +00003145
John McCall54507ab2011-06-16 01:15:19 +00003146static bool tryMatchRecordTypes(ASTContext &Context,
3147 Sema::MethodMatchStrategy strategy,
3148 const Type *lt, const Type *rt) {
3149 assert(lt && rt && lt != rt);
3150
3151 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
3152 RecordDecl *left = cast<RecordType>(lt)->getDecl();
3153 RecordDecl *right = cast<RecordType>(rt)->getDecl();
3154
3155 // Require union-hood to match.
3156 if (left->isUnion() != right->isUnion()) return false;
3157
3158 // Require an exact match if either is non-POD.
3159 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
3160 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
3161 return false;
3162
3163 // Require size and alignment to match.
David Majnemer34b57492014-07-30 01:30:47 +00003164 TypeInfo LeftTI = Context.getTypeInfo(lt);
3165 TypeInfo RightTI = Context.getTypeInfo(rt);
3166 if (LeftTI.Width != RightTI.Width)
3167 return false;
3168
3169 if (LeftTI.Align != RightTI.Align)
3170 return false;
John McCall54507ab2011-06-16 01:15:19 +00003171
3172 // Require fields to match.
3173 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
3174 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
3175 for (; li != le && ri != re; ++li, ++ri) {
3176 if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
3177 return false;
3178 }
3179 return (li == le && ri == re);
3180}
3181
Chris Lattnerda463fe2007-12-12 07:09:47 +00003182/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
3183/// returns true, or false, accordingly.
3184/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
John McCall31168b02011-06-15 23:02:42 +00003185bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
3186 const ObjCMethodDecl *right,
3187 MethodMatchStrategy strategy) {
Alp Toker314cc812014-01-25 16:55:45 +00003188 if (!matchTypes(Context, strategy, left->getReturnType(),
3189 right->getReturnType()))
John McCall31168b02011-06-15 23:02:42 +00003190 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003191
Douglas Gregor560b7fa2013-02-07 19:13:24 +00003192 // If either is hidden, it is not considered to match.
3193 if (left->isHidden() || right->isHidden())
3194 return false;
3195
David Blaikiebbafb8a2012-03-11 07:00:24 +00003196 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003197 (left->hasAttr<NSReturnsRetainedAttr>()
3198 != right->hasAttr<NSReturnsRetainedAttr>() ||
3199 left->hasAttr<NSConsumesSelfAttr>()
3200 != right->hasAttr<NSConsumesSelfAttr>()))
3201 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003202
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00003203 ObjCMethodDecl::param_const_iterator
Douglas Gregor0bf70f42012-05-17 23:13:29 +00003204 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
3205 re = right->param_end();
Mike Stump11289f42009-09-09 15:08:12 +00003206
Douglas Gregor0bf70f42012-05-17 23:13:29 +00003207 for (; li != le && ri != re; ++li, ++ri) {
John McCall31168b02011-06-15 23:02:42 +00003208 assert(ri != right->param_end() && "Param mismatch");
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00003209 const ParmVarDecl *lparm = *li, *rparm = *ri;
John McCall31168b02011-06-15 23:02:42 +00003210
3211 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
3212 return false;
3213
David Blaikiebbafb8a2012-03-11 07:00:24 +00003214 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003215 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
3216 return false;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003217 }
3218 return true;
3219}
3220
Manman Ren71224532016-04-09 18:59:48 +00003221static bool isMethodContextSameForKindofLookup(ObjCMethodDecl *Method,
3222 ObjCMethodDecl *MethodInList) {
3223 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3224 auto *MethodInListProtocol =
3225 dyn_cast<ObjCProtocolDecl>(MethodInList->getDeclContext());
3226 // If this method belongs to a protocol but the method in list does not, or
3227 // vice versa, we say the context is not the same.
3228 if ((MethodProtocol && !MethodInListProtocol) ||
3229 (!MethodProtocol && MethodInListProtocol))
3230 return false;
3231
3232 if (MethodProtocol && MethodInListProtocol)
3233 return true;
3234
3235 ObjCInterfaceDecl *MethodInterface = Method->getClassInterface();
3236 ObjCInterfaceDecl *MethodInListInterface =
3237 MethodInList->getClassInterface();
3238 return MethodInterface == MethodInListInterface;
3239}
3240
Nico Weber2e0c8f72014-12-27 03:58:08 +00003241void Sema::addMethodToGlobalList(ObjCMethodList *List,
3242 ObjCMethodDecl *Method) {
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003243 // Record at the head of the list whether there were 0, 1, or >= 2 methods
3244 // inside categories.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003245 if (ObjCCategoryDecl *CD =
3246 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
Argyrios Kyrtzidis04703a62013-04-27 00:10:12 +00003247 if (!CD->IsClassExtension() && List->getBits() < 2)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003248 List->setBits(List->getBits() + 1);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003249
Douglas Gregorc454afe2012-01-25 00:19:56 +00003250 // If the list is empty, make it a singleton list.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003251 if (List->getMethod() == nullptr) {
3252 List->setMethod(Method);
Craig Topperc3ec1492014-05-26 06:22:03 +00003253 List->setNext(nullptr);
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003254 return;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003255 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003256
Douglas Gregorc454afe2012-01-25 00:19:56 +00003257 // We've seen a method with this name, see if we have already seen this type
3258 // signature.
3259 ObjCMethodList *Previous = List;
Manman Ren051d0b62016-04-13 23:43:56 +00003260 ObjCMethodList *ListWithSameDeclaration = nullptr;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003261 for (; List; Previous = List, List = List->getNext()) {
Douglas Gregor600a2f52013-06-21 00:20:25 +00003262 // If we are building a module, keep all of the methods.
Richard Smithbbcc9f02016-08-26 00:14:38 +00003263 if (getLangOpts().isCompilingModule())
Douglas Gregor600a2f52013-06-21 00:20:25 +00003264 continue;
3265
Manman Ren051d0b62016-04-13 23:43:56 +00003266 bool SameDeclaration = MatchTwoMethodDeclarations(Method,
3267 List->getMethod());
Manman Ren71224532016-04-09 18:59:48 +00003268 // Looking for method with a type bound requires the correct context exists.
Manman Ren051d0b62016-04-13 23:43:56 +00003269 // We need to insert a method into the list if the context is different.
3270 // If the method's declaration matches the list
3271 // a> the method belongs to a different context: we need to insert it, in
3272 // order to emit the availability message, we need to prioritize over
3273 // availability among the methods with the same declaration.
3274 // b> the method belongs to the same context: there is no need to insert a
3275 // new entry.
3276 // If the method's declaration does not match the list, we insert it to the
3277 // end.
3278 if (!SameDeclaration ||
Manman Ren71224532016-04-09 18:59:48 +00003279 !isMethodContextSameForKindofLookup(Method, List->getMethod())) {
Fariborz Jahaniand436b2a2015-04-07 16:56:27 +00003280 // Even if two method types do not match, we would like to say
3281 // there is more than one declaration so unavailability/deprecated
3282 // warning is not too noisy.
3283 if (!Method->isDefined())
3284 List->setHasMoreThanOneDecl(true);
Manman Ren051d0b62016-04-13 23:43:56 +00003285
3286 // For methods with the same declaration, the one that is deprecated
3287 // should be put in the front for better diagnostics.
3288 if (Method->isDeprecated() && SameDeclaration &&
3289 !ListWithSameDeclaration && !List->getMethod()->isDeprecated())
3290 ListWithSameDeclaration = List;
3291
3292 if (Method->isUnavailable() && SameDeclaration &&
3293 !ListWithSameDeclaration &&
3294 List->getMethod()->getAvailability() < AR_Deprecated)
3295 ListWithSameDeclaration = List;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003296 continue;
Fariborz Jahaniand436b2a2015-04-07 16:56:27 +00003297 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003298
3299 ObjCMethodDecl *PrevObjCMethod = List->getMethod();
Douglas Gregorc454afe2012-01-25 00:19:56 +00003300
3301 // Propagate the 'defined' bit.
3302 if (Method->isDefined())
3303 PrevObjCMethod->setDefined(true);
Nico Webere3b11042014-12-27 07:09:37 +00003304 else {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003305 // Objective-C doesn't allow an @interface for a class after its
3306 // @implementation. So if Method is not defined and there already is
3307 // an entry for this type signature, Method has to be for a different
3308 // class than PrevObjCMethod.
3309 List->setHasMoreThanOneDecl(true);
3310 }
3311
Douglas Gregorc454afe2012-01-25 00:19:56 +00003312 // If a method is deprecated, push it in the global pool.
3313 // This is used for better diagnostics.
3314 if (Method->isDeprecated()) {
3315 if (!PrevObjCMethod->isDeprecated())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003316 List->setMethod(Method);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003317 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003318 // If the new method is unavailable, push it into global pool
Douglas Gregorc454afe2012-01-25 00:19:56 +00003319 // unless previous one is deprecated.
3320 if (Method->isUnavailable()) {
3321 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003322 List->setMethod(Method);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003323 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003324
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003325 return;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003326 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003327
Douglas Gregorc454afe2012-01-25 00:19:56 +00003328 // We have a new signature for an existing method - add it.
3329 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
Douglas Gregore1716012012-01-25 00:49:42 +00003330 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
Manman Ren71224532016-04-09 18:59:48 +00003331
Manman Ren051d0b62016-04-13 23:43:56 +00003332 // We insert it right before ListWithSameDeclaration.
3333 if (ListWithSameDeclaration) {
3334 auto *List = new (Mem) ObjCMethodList(*ListWithSameDeclaration);
3335 // FIXME: should we clear the other bits in ListWithSameDeclaration?
3336 ListWithSameDeclaration->setMethod(Method);
3337 ListWithSameDeclaration->setNext(List);
Manman Ren71224532016-04-09 18:59:48 +00003338 return;
3339 }
3340
Nico Weber2e0c8f72014-12-27 03:58:08 +00003341 Previous->setNext(new (Mem) ObjCMethodList(Method));
Douglas Gregorc454afe2012-01-25 00:19:56 +00003342}
3343
Sebastian Redl75d8a322010-08-02 23:18:59 +00003344/// \brief Read the contents of the method pool for a given selector from
3345/// external storage.
Douglas Gregore1716012012-01-25 00:49:42 +00003346void Sema::ReadMethodPool(Selector Sel) {
Douglas Gregorc78d3462009-04-24 21:10:55 +00003347 assert(ExternalSource && "We need an external AST source");
Douglas Gregore1716012012-01-25 00:49:42 +00003348 ExternalSource->ReadMethodPool(Sel);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003349}
3350
Manman Rena0f31a02016-04-29 19:04:05 +00003351void Sema::updateOutOfDateSelector(Selector Sel) {
3352 if (!ExternalSource)
3353 return;
3354 ExternalSource->updateOutOfDateSelector(Sel);
3355}
3356
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003357void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
Sebastian Redl75d8a322010-08-02 23:18:59 +00003358 bool instance) {
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00003359 // Ignore methods of invalid containers.
3360 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003361 return;
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00003362
Douglas Gregor70f449b2012-01-25 00:59:09 +00003363 if (ExternalSource)
3364 ReadMethodPool(Method->getSelector());
3365
Sebastian Redl75d8a322010-08-02 23:18:59 +00003366 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
Douglas Gregor70f449b2012-01-25 00:59:09 +00003367 if (Pos == MethodPool.end())
3368 Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
3369 GlobalMethods())).first;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003370
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003371 Method->setDefined(impl);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003372
Sebastian Redl75d8a322010-08-02 23:18:59 +00003373 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003374 addMethodToGlobalList(&Entry, Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003375}
3376
John McCall31168b02011-06-15 23:02:42 +00003377/// Determines if this is an "acceptable" loose mismatch in the global
3378/// method pool. This exists mostly as a hack to get around certain
3379/// global mismatches which we can't afford to make warnings / errors.
3380/// Really, what we want is a way to take a method out of the global
3381/// method pool.
3382static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
3383 ObjCMethodDecl *other) {
3384 if (!chosen->isInstanceMethod())
3385 return false;
3386
3387 Selector sel = chosen->getSelector();
3388 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
3389 return false;
3390
3391 // Don't complain about mismatches for -length if the method we
3392 // chose has an integral result type.
Alp Toker314cc812014-01-25 16:55:45 +00003393 return (chosen->getReturnType()->isIntegerType());
John McCall31168b02011-06-15 23:02:42 +00003394}
3395
Manman Ren7ed4f982016-04-07 19:32:24 +00003396/// Return true if the given method is wthin the type bound.
3397static bool FilterMethodsByTypeBound(ObjCMethodDecl *Method,
3398 const ObjCObjectType *TypeBound) {
3399 if (!TypeBound)
3400 return true;
3401
3402 if (TypeBound->isObjCId())
3403 // FIXME: should we handle the case of bounding to id<A, B> differently?
3404 return true;
3405
3406 auto *BoundInterface = TypeBound->getInterface();
3407 assert(BoundInterface && "unexpected object type!");
3408
3409 // Check if the Method belongs to a protocol. We should allow any method
3410 // defined in any protocol, because any subclass could adopt the protocol.
3411 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3412 if (MethodProtocol) {
3413 return true;
3414 }
3415
3416 // If the Method belongs to a class, check if it belongs to the class
3417 // hierarchy of the class bound.
3418 if (ObjCInterfaceDecl *MethodInterface = Method->getClassInterface()) {
3419 // We allow methods declared within classes that are part of the hierarchy
3420 // of the class bound (superclass of, subclass of, or the same as the class
3421 // bound).
3422 return MethodInterface == BoundInterface ||
3423 MethodInterface->isSuperClassOf(BoundInterface) ||
3424 BoundInterface->isSuperClassOf(MethodInterface);
3425 }
3426 llvm_unreachable("unknow method context");
3427}
3428
Manman Rend2a3cd72016-04-07 19:30:20 +00003429/// We first select the type of the method: Instance or Factory, then collect
3430/// all methods with that type.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003431bool Sema::CollectMultipleMethodsInGlobalPool(
Manman Rend2a3cd72016-04-07 19:30:20 +00003432 Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods,
Manman Ren7ed4f982016-04-07 19:32:24 +00003433 bool InstanceFirst, bool CheckTheOther,
3434 const ObjCObjectType *TypeBound) {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003435 if (ExternalSource)
3436 ReadMethodPool(Sel);
3437
3438 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3439 if (Pos == MethodPool.end())
3440 return false;
Manman Rend2a3cd72016-04-07 19:30:20 +00003441
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003442 // Gather the non-hidden methods.
Manman Rend2a3cd72016-04-07 19:30:20 +00003443 ObjCMethodList &MethList = InstanceFirst ? Pos->second.first :
3444 Pos->second.second;
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003445 for (ObjCMethodList *M = &MethList; M; M = M->getNext())
Manman Ren7ed4f982016-04-07 19:32:24 +00003446 if (M->getMethod() && !M->getMethod()->isHidden()) {
3447 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3448 Methods.push_back(M->getMethod());
3449 }
Manman Rend2a3cd72016-04-07 19:30:20 +00003450
3451 // Return if we find any method with the desired kind.
3452 if (!Methods.empty())
3453 return Methods.size() > 1;
3454
3455 if (!CheckTheOther)
3456 return false;
3457
3458 // Gather the other kind.
3459 ObjCMethodList &MethList2 = InstanceFirst ? Pos->second.second :
3460 Pos->second.first;
3461 for (ObjCMethodList *M = &MethList2; M; M = M->getNext())
Manman Ren7ed4f982016-04-07 19:32:24 +00003462 if (M->getMethod() && !M->getMethod()->isHidden()) {
3463 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3464 Methods.push_back(M->getMethod());
3465 }
Manman Rend2a3cd72016-04-07 19:30:20 +00003466
Nico Weber2e0c8f72014-12-27 03:58:08 +00003467 return Methods.size() > 1;
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003468}
3469
Manman Rend2a3cd72016-04-07 19:30:20 +00003470bool Sema::AreMultipleMethodsInGlobalPool(
3471 Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R,
3472 bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl *> &Methods) {
3473 // Diagnose finding more than one method in global pool.
3474 SmallVector<ObjCMethodDecl *, 4> FilteredMethods;
3475 FilteredMethods.push_back(BestMethod);
3476
3477 for (auto *M : Methods)
3478 if (M != BestMethod && !M->hasAttr<UnavailableAttr>())
3479 FilteredMethods.push_back(M);
3480
3481 if (FilteredMethods.size() > 1)
3482 DiagnoseMultipleMethodInGlobalPool(FilteredMethods, Sel, R,
3483 receiverIdOrClass);
3484
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003485 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
Nico Weber2e0c8f72014-12-27 03:58:08 +00003486 // Test for no method in the pool which should not trigger any warning by
3487 // caller.
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003488 if (Pos == MethodPool.end())
3489 return true;
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003490 ObjCMethodList &MethList =
3491 BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003492 return MethList.hasMoreThanOneDecl();
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003493}
3494
Sebastian Redl75d8a322010-08-02 23:18:59 +00003495ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00003496 bool receiverIdOrClass,
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003497 bool instance) {
Douglas Gregor70f449b2012-01-25 00:59:09 +00003498 if (ExternalSource)
3499 ReadMethodPool(Sel);
3500
Sebastian Redl75d8a322010-08-02 23:18:59 +00003501 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
Douglas Gregor70f449b2012-01-25 00:59:09 +00003502 if (Pos == MethodPool.end())
Craig Topperc3ec1492014-05-26 06:22:03 +00003503 return nullptr;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003504
Douglas Gregor77f49a42013-01-16 18:47:38 +00003505 // Gather the non-hidden methods.
Sebastian Redl75d8a322010-08-02 23:18:59 +00003506 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00003507 SmallVector<ObjCMethodDecl *, 4> Methods;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003508 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003509 if (M->getMethod() && !M->getMethod()->isHidden())
3510 return M->getMethod();
Douglas Gregorc78d3462009-04-24 21:10:55 +00003511 }
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003512 return nullptr;
3513}
Douglas Gregor77f49a42013-01-16 18:47:38 +00003514
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003515void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3516 Selector Sel, SourceRange R,
3517 bool receiverIdOrClass) {
Douglas Gregor77f49a42013-01-16 18:47:38 +00003518 // We found multiple methods, so we may have to complain.
3519 bool issueDiagnostic = false, issueError = false;
Jonathan Roelofs74411362015-04-28 18:04:44 +00003520
Douglas Gregor77f49a42013-01-16 18:47:38 +00003521 // We support a warning which complains about *any* difference in
3522 // method signature.
3523 bool strictSelectorMatch =
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003524 receiverIdOrClass &&
3525 !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
Douglas Gregor77f49a42013-01-16 18:47:38 +00003526 if (strictSelectorMatch) {
3527 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3528 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
3529 issueDiagnostic = true;
3530 break;
3531 }
3532 }
3533 }
Jonathan Roelofs74411362015-04-28 18:04:44 +00003534
Douglas Gregor77f49a42013-01-16 18:47:38 +00003535 // If we didn't see any strict differences, we won't see any loose
3536 // differences. In ARC, however, we also need to check for loose
3537 // mismatches, because most of them are errors.
3538 if (!strictSelectorMatch ||
3539 (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
3540 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3541 // This checks if the methods differ in type mismatch.
3542 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
3543 !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
3544 issueDiagnostic = true;
3545 if (getLangOpts().ObjCAutoRefCount)
3546 issueError = true;
3547 break;
3548 }
3549 }
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003550
Douglas Gregor77f49a42013-01-16 18:47:38 +00003551 if (issueDiagnostic) {
3552 if (issueError)
3553 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
3554 else if (strictSelectorMatch)
3555 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
3556 else
3557 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003558
Douglas Gregor77f49a42013-01-16 18:47:38 +00003559 Diag(Methods[0]->getLocStart(),
3560 issueError ? diag::note_possibility : diag::note_using)
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003561 << Methods[0]->getSourceRange();
Douglas Gregor77f49a42013-01-16 18:47:38 +00003562 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3563 Diag(Methods[I]->getLocStart(), diag::note_also_found)
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003564 << Methods[I]->getSourceRange();
3565 }
Douglas Gregor77f49a42013-01-16 18:47:38 +00003566 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003567}
3568
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003569ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
Sebastian Redl75d8a322010-08-02 23:18:59 +00003570 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3571 if (Pos == MethodPool.end())
Craig Topperc3ec1492014-05-26 06:22:03 +00003572 return nullptr;
Sebastian Redl75d8a322010-08-02 23:18:59 +00003573
3574 GlobalMethods &Methods = Pos->second;
Fariborz Jahanianec762bd2014-03-26 20:59:26 +00003575 for (const ObjCMethodList *Method = &Methods.first; Method;
3576 Method = Method->getNext())
Fariborz Jahanian4019c7f2015-02-19 21:52:41 +00003577 if (Method->getMethod() &&
3578 (Method->getMethod()->isDefined() ||
3579 Method->getMethod()->isPropertyAccessor()))
Nico Weber2e0c8f72014-12-27 03:58:08 +00003580 return Method->getMethod();
Fariborz Jahanianec762bd2014-03-26 20:59:26 +00003581
3582 for (const ObjCMethodList *Method = &Methods.second; Method;
3583 Method = Method->getNext())
Fariborz Jahanian4019c7f2015-02-19 21:52:41 +00003584 if (Method->getMethod() &&
3585 (Method->getMethod()->isDefined() ||
3586 Method->getMethod()->isPropertyAccessor()))
Nico Weber2e0c8f72014-12-27 03:58:08 +00003587 return Method->getMethod();
Craig Topperc3ec1492014-05-26 06:22:03 +00003588 return nullptr;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003589}
3590
Fariborz Jahanian42f89382013-05-30 21:48:58 +00003591static void
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003592HelperSelectorsForTypoCorrection(
3593 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
3594 StringRef Typo, const ObjCMethodDecl * Method) {
3595 const unsigned MaxEditDistance = 1;
3596 unsigned BestEditDistance = MaxEditDistance + 1;
Richard Trieuea8d3702013-06-06 02:22:29 +00003597 std::string MethodName = Method->getSelector().getAsString();
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003598
3599 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
3600 if (MinPossibleEditDistance > 0 &&
3601 Typo.size() / MinPossibleEditDistance < 1)
3602 return;
3603 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
3604 if (EditDistance > MaxEditDistance)
3605 return;
3606 if (EditDistance == BestEditDistance)
3607 BestMethod.push_back(Method);
3608 else if (EditDistance < BestEditDistance) {
3609 BestMethod.clear();
3610 BestMethod.push_back(Method);
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003611 }
3612}
3613
Fariborz Jahanian75481672013-06-17 17:10:54 +00003614static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
3615 QualType ObjectType) {
3616 if (ObjectType.isNull())
3617 return true;
3618 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
3619 return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003620 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
3621 nullptr;
Fariborz Jahanian75481672013-06-17 17:10:54 +00003622}
3623
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003624const ObjCMethodDecl *
Fariborz Jahanian75481672013-06-17 17:10:54 +00003625Sema::SelectorsForTypoCorrection(Selector Sel,
3626 QualType ObjectType) {
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003627 unsigned NumArgs = Sel.getNumArgs();
3628 SmallVector<const ObjCMethodDecl *, 8> Methods;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003629 bool ObjectIsId = true, ObjectIsClass = true;
3630 if (ObjectType.isNull())
3631 ObjectIsId = ObjectIsClass = false;
3632 else if (!ObjectType->isObjCObjectPointerType())
Craig Topperc3ec1492014-05-26 06:22:03 +00003633 return nullptr;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003634 else if (const ObjCObjectPointerType *ObjCPtr =
3635 ObjectType->getAsObjCInterfacePointerType()) {
3636 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
3637 ObjectIsId = ObjectIsClass = false;
3638 }
3639 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
3640 ObjectIsClass = false;
3641 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
3642 ObjectIsId = false;
3643 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003644 return nullptr;
3645
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003646 for (GlobalMethodPool::iterator b = MethodPool.begin(),
3647 e = MethodPool.end(); b != e; b++) {
3648 // instance methods
3649 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003650 if (M->getMethod() &&
3651 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3652 (M->getMethod()->getSelector() != Sel)) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003653 if (ObjectIsId)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003654 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003655 else if (!ObjectIsClass &&
Nico Weber2e0c8f72014-12-27 03:58:08 +00003656 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3657 ObjectType))
3658 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003659 }
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003660 // class methods
3661 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003662 if (M->getMethod() &&
3663 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3664 (M->getMethod()->getSelector() != Sel)) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003665 if (ObjectIsClass)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003666 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003667 else if (!ObjectIsId &&
Nico Weber2e0c8f72014-12-27 03:58:08 +00003668 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3669 ObjectType))
3670 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003671 }
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003672 }
3673
3674 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
3675 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
3676 HelperSelectorsForTypoCorrection(SelectedMethods,
3677 Sel.getAsString(), Methods[i]);
3678 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003679 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003680}
3681
Fariborz Jahanian42f89382013-05-30 21:48:58 +00003682/// DiagnoseDuplicateIvars -
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003683/// Check for duplicate ivars in the entire class at the start of
James Dennett634962f2012-06-14 21:40:34 +00003684/// \@implementation. This becomes necesssary because class extension can
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003685/// add ivars to a class in random order which will not be known until
James Dennett634962f2012-06-14 21:40:34 +00003686/// class's \@implementation is seen.
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003687void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
3688 ObjCInterfaceDecl *SID) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00003689 for (auto *Ivar : ID->ivars()) {
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003690 if (Ivar->isInvalidDecl())
3691 continue;
3692 if (IdentifierInfo *II = Ivar->getIdentifier()) {
3693 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
3694 if (prevIvar) {
3695 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3696 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
3697 Ivar->setInvalidDecl();
3698 }
3699 }
3700 }
3701}
3702
John McCallb61e14e2015-10-27 04:54:50 +00003703/// Diagnose attempts to define ARC-__weak ivars when __weak is disabled.
3704static void DiagnoseWeakIvars(Sema &S, ObjCImplementationDecl *ID) {
3705 if (S.getLangOpts().ObjCWeak) return;
3706
3707 for (auto ivar = ID->getClassInterface()->all_declared_ivar_begin();
3708 ivar; ivar = ivar->getNextIvar()) {
3709 if (ivar->isInvalidDecl()) continue;
3710 if (ivar->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
3711 if (S.getLangOpts().ObjCWeakRuntime) {
3712 S.Diag(ivar->getLocation(), diag::err_arc_weak_disabled);
3713 } else {
3714 S.Diag(ivar->getLocation(), diag::err_arc_weak_no_runtime);
3715 }
3716 }
3717 }
3718}
3719
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003720Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
3721 switch (CurContext->getDeclKind()) {
3722 case Decl::ObjCInterface:
3723 return Sema::OCK_Interface;
3724 case Decl::ObjCProtocol:
3725 return Sema::OCK_Protocol;
3726 case Decl::ObjCCategory:
Benjamin Kramera008d3a2015-04-10 11:37:55 +00003727 if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003728 return Sema::OCK_ClassExtension;
Benjamin Kramera008d3a2015-04-10 11:37:55 +00003729 return Sema::OCK_Category;
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003730 case Decl::ObjCImplementation:
3731 return Sema::OCK_Implementation;
3732 case Decl::ObjCCategoryImpl:
3733 return Sema::OCK_CategoryImplementation;
3734
3735 default:
3736 return Sema::OCK_None;
3737 }
3738}
3739
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003740// Note: For class/category implementations, allMethods is always null.
Robert Wilhelm57c67112013-07-17 21:14:35 +00003741Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
Fariborz Jahaniandfb76872013-07-17 00:05:08 +00003742 ArrayRef<DeclGroupPtrTy> allTUVars) {
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003743 if (getObjCContainerKind() == Sema::OCK_None)
Craig Topperc3ec1492014-05-26 06:22:03 +00003744 return nullptr;
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003745
3746 assert(AtEnd.isValid() && "Invalid location for '@end'");
3747
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00003748 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
3749 Decl *ClassDecl = cast<Decl>(OCD);
Fariborz Jahanian9290ede2009-11-16 18:57:01 +00003750
Mike Stump11289f42009-09-09 15:08:12 +00003751 bool isInterfaceDeclKind =
Chris Lattner219b3e92008-03-16 21:17:37 +00003752 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
3753 || isa<ObjCProtocolDecl>(ClassDecl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003754 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
Steve Naroffb3a87982009-01-09 15:36:25 +00003755
Steve Naroff35c62ae2009-01-08 17:28:14 +00003756 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
3757 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
3758 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
3759
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003760 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003761 ObjCMethodDecl *Method =
John McCall48871652010-08-21 09:40:31 +00003762 cast_or_null<ObjCMethodDecl>(allMethods[i]);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003763
3764 if (!Method) continue; // Already issued a diagnostic.
Douglas Gregorffca3a22009-01-09 17:18:27 +00003765 if (Method->isInstanceMethod()) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00003766 /// Check for instance method of the same name with incompatible types
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003767 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
Mike Stump11289f42009-09-09 15:08:12 +00003768 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
Chris Lattnerda463fe2007-12-12 07:09:47 +00003769 : false;
Mike Stump11289f42009-09-09 15:08:12 +00003770 if ((isInterfaceDeclKind && PrevMethod && !match)
Eli Friedman42b1e9e2008-12-16 20:15:50 +00003771 || (checkIdenticalMethods && match)) {
Chris Lattner0369c572008-11-23 23:12:31 +00003772 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00003773 << Method->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003774 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Douglas Gregor87e92752010-12-21 17:34:17 +00003775 Method->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00003776 } else {
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003777 if (PrevMethod) {
Argyrios Kyrtzidisdcaaa212011-10-14 08:02:31 +00003778 Method->setAsRedeclaration(PrevMethod);
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003779 if (!Context.getSourceManager().isInSystemHeader(
3780 Method->getLocation()))
3781 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3782 << Method->getDeclName();
3783 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3784 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003785 InsMap[Method->getSelector()] = Method;
3786 /// The following allows us to typecheck messages to "id".
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003787 AddInstanceMethodToGlobalPool(Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003788 }
Mike Stump12b8ce12009-08-04 21:02:39 +00003789 } else {
Chris Lattnerda463fe2007-12-12 07:09:47 +00003790 /// Check for class method of the same name with incompatible types
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003791 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
Mike Stump11289f42009-09-09 15:08:12 +00003792 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
Chris Lattnerda463fe2007-12-12 07:09:47 +00003793 : false;
Mike Stump11289f42009-09-09 15:08:12 +00003794 if ((isInterfaceDeclKind && PrevMethod && !match)
Eli Friedman42b1e9e2008-12-16 20:15:50 +00003795 || (checkIdenticalMethods && match)) {
Chris Lattner0369c572008-11-23 23:12:31 +00003796 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00003797 << Method->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003798 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Douglas Gregor87e92752010-12-21 17:34:17 +00003799 Method->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00003800 } else {
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003801 if (PrevMethod) {
Argyrios Kyrtzidisdcaaa212011-10-14 08:02:31 +00003802 Method->setAsRedeclaration(PrevMethod);
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003803 if (!Context.getSourceManager().isInSystemHeader(
3804 Method->getLocation()))
3805 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3806 << Method->getDeclName();
3807 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3808 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003809 ClsMap[Method->getSelector()] = Method;
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003810 AddFactoryMethodToGlobalPool(Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003811 }
3812 }
3813 }
Douglas Gregorb8982092013-01-21 19:42:21 +00003814 if (isa<ObjCInterfaceDecl>(ClassDecl)) {
3815 // Nothing to do here.
Steve Naroffb3a87982009-01-09 15:36:25 +00003816 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
Fariborz Jahanian62293f42008-12-06 19:59:02 +00003817 // Categories are used to extend the class by declaring new methods.
Mike Stump11289f42009-09-09 15:08:12 +00003818 // By the same token, they are also used to add new properties. No
Fariborz Jahanian62293f42008-12-06 19:59:02 +00003819 // need to compare the added property to those in the class.
Daniel Dunbar4684f372008-08-27 05:40:03 +00003820
Fariborz Jahanianc21f5432010-12-10 23:36:33 +00003821 if (C->IsClassExtension()) {
3822 ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
3823 DiagnoseClassExtensionDupMethods(C, CCPrimary);
Fariborz Jahanianc21f5432010-12-10 23:36:33 +00003824 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003825 }
Steve Naroffb3a87982009-01-09 15:36:25 +00003826 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
Fariborz Jahanian30a42922010-02-15 21:55:26 +00003827 if (CDecl->getIdentifier())
3828 // ProcessPropertyDecl is responsible for diagnosing conflicts with any
3829 // user-defined setter/getter. It also synthesizes setter/getter methods
3830 // and adds them to the DeclContext and global method pools.
Manman Renefe1bac2016-01-27 20:00:32 +00003831 for (auto *I : CDecl->properties())
Douglas Gregore17765e2015-11-03 17:02:34 +00003832 ProcessPropertyDecl(I);
Ted Kremenekc7c64312010-01-07 01:20:12 +00003833 CDecl->setAtEndRange(AtEnd);
Steve Naroffb3a87982009-01-09 15:36:25 +00003834 }
3835 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
Ted Kremenekc7c64312010-01-07 01:20:12 +00003836 IC->setAtEndRange(AtEnd);
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00003837 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003838 // Any property declared in a class extension might have user
3839 // declared setter or getter in current class extension or one
3840 // of the other class extensions. Mark them as synthesized as
3841 // property will be synthesized when property with same name is
3842 // seen in the @implementation.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00003843 for (const auto *Ext : IDecl->visible_extensions()) {
Manman Rena7a8b1f2016-01-26 18:05:23 +00003844 for (const auto *Property : Ext->instance_properties()) {
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003845 // Skip over properties declared @dynamic
3846 if (const ObjCPropertyImplDecl *PIDecl
Manman Ren5b786402016-01-28 18:49:28 +00003847 = IC->FindPropertyImplDecl(Property->getIdentifier(),
3848 Property->getQueryKind()))
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003849 if (PIDecl->getPropertyImplementation()
3850 == ObjCPropertyImplDecl::Dynamic)
3851 continue;
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003852
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00003853 for (const auto *Ext : IDecl->visible_extensions()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003854 if (ObjCMethodDecl *GetterMethod
3855 = Ext->getInstanceMethod(Property->getGetterName()))
Jordan Rosed01e83a2012-10-10 16:42:25 +00003856 GetterMethod->setPropertyAccessor(true);
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003857 if (!Property->isReadOnly())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003858 if (ObjCMethodDecl *SetterMethod
3859 = Ext->getInstanceMethod(Property->getSetterName()))
Jordan Rosed01e83a2012-10-10 16:42:25 +00003860 SetterMethod->setPropertyAccessor(true);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003861 }
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003862 }
3863 }
Fariborz Jahanian25491a22010-05-05 21:52:17 +00003864 ImplMethodsVsClassMethods(S, IC, IDecl);
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00003865 AtomicPropertySetterGetterRules(IC, IDecl);
John McCall31168b02011-06-15 23:02:42 +00003866 DiagnoseOwningPropertyGetterSynthesis(IC);
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00003867 DiagnoseUnusedBackingIvarInAccessor(S, IC);
Fariborz Jahanian20cfff32015-03-11 16:59:48 +00003868 if (IDecl->hasDesignatedInitializers())
3869 DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
John McCallb61e14e2015-10-27 04:54:50 +00003870 DiagnoseWeakIvars(*this, IC);
Argyrios Kyrtzidisdb5ce0f2013-12-03 21:11:54 +00003871
Patrick Beardacfbe9e2012-04-06 18:12:22 +00003872 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
Craig Topperc3ec1492014-05-26 06:22:03 +00003873 if (IDecl->getSuperClass() == nullptr) {
Patrick Beardacfbe9e2012-04-06 18:12:22 +00003874 // This class has no superclass, so check that it has been marked with
3875 // __attribute((objc_root_class)).
3876 if (!HasRootClassAttr) {
3877 SourceLocation DeclLoc(IDecl->getLocation());
Alp Tokerb6cc5922014-05-03 03:45:55 +00003878 SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
Patrick Beardacfbe9e2012-04-06 18:12:22 +00003879 Diag(DeclLoc, diag::warn_objc_root_class_missing)
3880 << IDecl->getIdentifier();
3881 // See if NSObject is in the current scope, and if it is, suggest
3882 // adding " : NSObject " to the class declaration.
3883 NamedDecl *IF = LookupSingleName(TUScope,
3884 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
3885 DeclLoc, LookupOrdinaryName);
3886 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
3887 if (NSObjectDecl && NSObjectDecl->getDefinition()) {
3888 Diag(SuperClassLoc, diag::note_objc_needs_superclass)
3889 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
3890 } else {
3891 Diag(SuperClassLoc, diag::note_objc_needs_superclass);
3892 }
3893 }
3894 } else if (HasRootClassAttr) {
3895 // Complain that only root classes may have this attribute.
3896 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
3897 }
3898
Alex Lorenza8c44ba2016-10-28 10:25:10 +00003899 if (const ObjCInterfaceDecl *Super = IDecl->getSuperClass()) {
3900 // An interface can subclass another interface with a
3901 // objc_subclassing_restricted attribute when it has that attribute as
3902 // well (because of interfaces imported from Swift). Therefore we have
3903 // to check if we can subclass in the implementation as well.
3904 if (IDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
3905 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
3906 Diag(IC->getLocation(), diag::err_restricted_superclass_mismatch);
3907 Diag(Super->getLocation(), diag::note_class_declared);
3908 }
3909 }
3910
John McCall5fb5df92012-06-20 06:18:46 +00003911 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003912 while (IDecl->getSuperClass()) {
3913 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
3914 IDecl = IDecl->getSuperClass();
3915 }
Patrick Beardacfbe9e2012-04-06 18:12:22 +00003916 }
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00003917 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00003918 SetIvarInitializers(IC);
Mike Stump11289f42009-09-09 15:08:12 +00003919 } else if (ObjCCategoryImplDecl* CatImplClass =
Steve Naroffb3a87982009-01-09 15:36:25 +00003920 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
Ted Kremenekc7c64312010-01-07 01:20:12 +00003921 CatImplClass->setAtEndRange(AtEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003922
Chris Lattnerda463fe2007-12-12 07:09:47 +00003923 // Find category interface decl and then check that all methods declared
Daniel Dunbar4684f372008-08-27 05:40:03 +00003924 // in this interface are implemented in the category @implementation.
Chris Lattner41fd42e2009-02-16 18:32:47 +00003925 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003926 if (ObjCCategoryDecl *Cat
3927 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
3928 ImplMethodsVsClassMethods(S, CatImplClass, Cat);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003929 }
3930 }
Alex Lorenza8c44ba2016-10-28 10:25:10 +00003931 } else if (const auto *IntfDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
3932 if (const ObjCInterfaceDecl *Super = IntfDecl->getSuperClass()) {
3933 if (!IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
3934 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
3935 Diag(IntfDecl->getLocation(), diag::err_restricted_superclass_mismatch);
3936 Diag(Super->getLocation(), diag::note_class_declared);
3937 }
3938 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003939 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00003940 if (isInterfaceDeclKind) {
3941 // Reject invalid vardecls.
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003942 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003943 DeclGroupRef DG = allTUVars[i].get();
Chris Lattner5bbb3c82009-03-29 16:50:03 +00003944 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
3945 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003946 if (!VDecl->hasExternalStorage())
Steve Naroff42959b22009-04-13 17:58:46 +00003947 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
Fariborz Jahanian629aed92009-03-21 18:06:45 +00003948 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00003949 }
Fariborz Jahanian3654e652009-03-18 22:33:24 +00003950 }
Fariborz Jahanian4327b322011-08-29 17:33:12 +00003951 ActOnObjCContainerFinishDefinition();
Argyrios Kyrtzidisbd8b1502011-10-17 19:48:13 +00003952
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003953 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003954 DeclGroupRef DG = allTUVars[i].get();
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00003955 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
3956 (*I)->setTopLevelDeclInObjCContainer();
Argyrios Kyrtzidisbd8b1502011-10-17 19:48:13 +00003957 Consumer.HandleTopLevelDeclInObjCContainer(DG);
3958 }
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003959
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +00003960 ActOnDocumentableDecl(ClassDecl);
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003961 return ClassDecl;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003962}
3963
Chris Lattnerda463fe2007-12-12 07:09:47 +00003964/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
3965/// objective-c's type qualifier from the parser version of the same info.
Mike Stump11289f42009-09-09 15:08:12 +00003966static Decl::ObjCDeclQualifier
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003967CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
John McCallca872902011-05-01 03:04:29 +00003968 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003969}
3970
Douglas Gregor33823722011-06-11 01:09:30 +00003971/// \brief Check whether the declared result type of the given Objective-C
3972/// method declaration is compatible with the method's class.
3973///
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003974static Sema::ResultTypeCompatibilityKind
Douglas Gregor33823722011-06-11 01:09:30 +00003975CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
3976 ObjCInterfaceDecl *CurrentClass) {
Alp Toker314cc812014-01-25 16:55:45 +00003977 QualType ResultType = Method->getReturnType();
3978
Douglas Gregor33823722011-06-11 01:09:30 +00003979 // If an Objective-C method inherits its related result type, then its
3980 // declared result type must be compatible with its own class type. The
3981 // declared result type is compatible if:
3982 if (const ObjCObjectPointerType *ResultObjectType
3983 = ResultType->getAs<ObjCObjectPointerType>()) {
3984 // - it is id or qualified id, or
3985 if (ResultObjectType->isObjCIdType() ||
3986 ResultObjectType->isObjCQualifiedIdType())
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003987 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00003988
3989 if (CurrentClass) {
3990 if (ObjCInterfaceDecl *ResultClass
3991 = ResultObjectType->getInterfaceDecl()) {
3992 // - it is the same as the method's class type, or
Douglas Gregor0b144e12011-12-15 00:29:59 +00003993 if (declaresSameEntity(CurrentClass, ResultClass))
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003994 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00003995
3996 // - it is a superclass of the method's class type
3997 if (ResultClass->isSuperClassOf(CurrentClass))
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003998 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00003999 }
Douglas Gregorbab8a962011-09-08 01:46:34 +00004000 } else {
4001 // Any Objective-C pointer type might be acceptable for a protocol
4002 // method; we just don't know.
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004003 return Sema::RTC_Unknown;
Douglas Gregor33823722011-06-11 01:09:30 +00004004 }
4005 }
4006
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004007 return Sema::RTC_Incompatible;
Douglas Gregor33823722011-06-11 01:09:30 +00004008}
4009
John McCalld2930c22011-07-22 02:45:48 +00004010namespace {
4011/// A helper class for searching for methods which a particular method
4012/// overrides.
4013class OverrideSearch {
Daniel Dunbard6d74c32012-02-29 03:04:05 +00004014public:
John McCalld2930c22011-07-22 02:45:48 +00004015 Sema &S;
4016 ObjCMethodDecl *Method;
Daniel Dunbard6d74c32012-02-29 03:04:05 +00004017 llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden;
John McCalld2930c22011-07-22 02:45:48 +00004018 bool Recursive;
4019
4020public:
4021 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
4022 Selector selector = method->getSelector();
4023
4024 // Bypass this search if we've never seen an instance/class method
4025 // with this selector before.
4026 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
4027 if (it == S.MethodPool.end()) {
Axel Naumanndd433f02012-10-18 19:05:02 +00004028 if (!S.getExternalSource()) return;
Douglas Gregore1716012012-01-25 00:49:42 +00004029 S.ReadMethodPool(selector);
4030
4031 it = S.MethodPool.find(selector);
4032 if (it == S.MethodPool.end())
4033 return;
John McCalld2930c22011-07-22 02:45:48 +00004034 }
4035 ObjCMethodList &list =
4036 method->isInstanceMethod() ? it->second.first : it->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00004037 if (!list.getMethod()) return;
John McCalld2930c22011-07-22 02:45:48 +00004038
4039 ObjCContainerDecl *container
4040 = cast<ObjCContainerDecl>(method->getDeclContext());
4041
4042 // Prevent the search from reaching this container again. This is
4043 // important with categories, which override methods from the
4044 // interface and each other.
Douglas Gregorcf4ac442012-05-03 21:25:24 +00004045 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) {
4046 searchFromContainer(container);
Douglas Gregorc5928af2012-05-17 22:39:14 +00004047 if (ObjCInterfaceDecl *Interface = Category->getClassInterface())
4048 searchFromContainer(Interface);
Douglas Gregorcf4ac442012-05-03 21:25:24 +00004049 } else {
4050 searchFromContainer(container);
4051 }
Douglas Gregor33823722011-06-11 01:09:30 +00004052 }
John McCalld2930c22011-07-22 02:45:48 +00004053
Matthias Braun1d030072016-01-30 01:27:06 +00004054 typedef llvm::SmallPtrSetImpl<ObjCMethodDecl*>::iterator iterator;
John McCalld2930c22011-07-22 02:45:48 +00004055 iterator begin() const { return Overridden.begin(); }
4056 iterator end() const { return Overridden.end(); }
4057
4058private:
4059 void searchFromContainer(ObjCContainerDecl *container) {
4060 if (container->isInvalidDecl()) return;
4061
4062 switch (container->getDeclKind()) {
4063#define OBJCCONTAINER(type, base) \
4064 case Decl::type: \
4065 searchFrom(cast<type##Decl>(container)); \
4066 break;
4067#define ABSTRACT_DECL(expansion)
4068#define DECL(type, base) \
4069 case Decl::type:
4070#include "clang/AST/DeclNodes.inc"
4071 llvm_unreachable("not an ObjC container!");
4072 }
4073 }
4074
4075 void searchFrom(ObjCProtocolDecl *protocol) {
Douglas Gregore6e48b12012-01-01 19:29:29 +00004076 if (!protocol->hasDefinition())
4077 return;
4078
John McCalld2930c22011-07-22 02:45:48 +00004079 // A method in a protocol declaration overrides declarations from
4080 // referenced ("parent") protocols.
4081 search(protocol->getReferencedProtocols());
4082 }
4083
4084 void searchFrom(ObjCCategoryDecl *category) {
4085 // A method in a category declaration overrides declarations from
4086 // the main class and from protocols the category references.
Douglas Gregorcf4ac442012-05-03 21:25:24 +00004087 // The main class is handled in the constructor.
John McCalld2930c22011-07-22 02:45:48 +00004088 search(category->getReferencedProtocols());
4089 }
4090
4091 void searchFrom(ObjCCategoryImplDecl *impl) {
4092 // A method in a category definition that has a category
4093 // declaration overrides declarations from the category
4094 // declaration.
4095 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
4096 search(category);
Douglas Gregorc5928af2012-05-17 22:39:14 +00004097 if (ObjCInterfaceDecl *Interface = category->getClassInterface())
4098 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00004099
4100 // Otherwise it overrides declarations from the class.
Douglas Gregorc5928af2012-05-17 22:39:14 +00004101 } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) {
4102 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00004103 }
4104 }
4105
4106 void searchFrom(ObjCInterfaceDecl *iface) {
4107 // A method in a class declaration overrides declarations from
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00004108 if (!iface->hasDefinition())
4109 return;
4110
John McCalld2930c22011-07-22 02:45:48 +00004111 // - categories,
Aaron Ballman15063e12014-03-13 21:35:02 +00004112 for (auto *Cat : iface->known_categories())
4113 search(Cat);
John McCalld2930c22011-07-22 02:45:48 +00004114
4115 // - the super class, and
4116 if (ObjCInterfaceDecl *super = iface->getSuperClass())
4117 search(super);
4118
4119 // - any referenced protocols.
4120 search(iface->getReferencedProtocols());
4121 }
4122
4123 void searchFrom(ObjCImplementationDecl *impl) {
4124 // A method in a class implementation overrides declarations from
4125 // the class interface.
Douglas Gregorc5928af2012-05-17 22:39:14 +00004126 if (ObjCInterfaceDecl *Interface = impl->getClassInterface())
4127 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00004128 }
4129
John McCalld2930c22011-07-22 02:45:48 +00004130 void search(const ObjCProtocolList &protocols) {
4131 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
4132 i != e; ++i)
4133 search(*i);
4134 }
4135
4136 void search(ObjCContainerDecl *container) {
John McCalld2930c22011-07-22 02:45:48 +00004137 // Check for a method in this container which matches this selector.
4138 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
Argyrios Kyrtzidisbd8cd3e2013-03-29 21:51:48 +00004139 Method->isInstanceMethod(),
4140 /*AllowHidden=*/true);
John McCalld2930c22011-07-22 02:45:48 +00004141
4142 // If we find one, record it and bail out.
4143 if (meth) {
4144 Overridden.insert(meth);
4145 return;
4146 }
4147
4148 // Otherwise, search for methods that a hypothetical method here
4149 // would have overridden.
4150
4151 // Note that we're now in a recursive case.
4152 Recursive = true;
4153
4154 searchFromContainer(container);
4155 }
4156};
Hans Wennborgdcfba332015-10-06 23:40:43 +00004157} // end anonymous namespace
Douglas Gregor33823722011-06-11 01:09:30 +00004158
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004159void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
4160 ObjCInterfaceDecl *CurrentClass,
4161 ResultTypeCompatibilityKind RTC) {
4162 // Search for overridden methods and merge information down from them.
4163 OverrideSearch overrides(*this, ObjCMethod);
4164 // Keep track if the method overrides any method in the class's base classes,
4165 // its protocols, or its categories' protocols; we will keep that info
4166 // in the ObjCMethodDecl.
4167 // For this info, a method in an implementation is not considered as
4168 // overriding the same method in the interface or its categories.
4169 bool hasOverriddenMethodsInBaseOrProtocol = false;
4170 for (OverrideSearch::iterator
4171 i = overrides.begin(), e = overrides.end(); i != e; ++i) {
4172 ObjCMethodDecl *overridden = *i;
4173
Argyrios Kyrtzidisc2091d52013-04-17 00:09:08 +00004174 if (!hasOverriddenMethodsInBaseOrProtocol) {
4175 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
4176 CurrentClass != overridden->getClassInterface() ||
4177 overridden->isOverriding()) {
4178 hasOverriddenMethodsInBaseOrProtocol = true;
4179
4180 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
4181 // OverrideSearch will return as "overridden" the same method in the
4182 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
4183 // check whether a category of a base class introduced a method with the
4184 // same selector, after the interface method declaration.
4185 // To avoid unnecessary lookups in the majority of cases, we use the
4186 // extra info bits in GlobalMethodPool to check whether there were any
4187 // category methods with this selector.
4188 GlobalMethodPool::iterator It =
4189 MethodPool.find(ObjCMethod->getSelector());
4190 if (It != MethodPool.end()) {
4191 ObjCMethodList &List =
4192 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
4193 unsigned CategCount = List.getBits();
4194 if (CategCount > 0) {
4195 // If the method is in a category we'll do lookup if there were at
4196 // least 2 category methods recorded, otherwise only one will do.
4197 if (CategCount > 1 ||
4198 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
4199 OverrideSearch overrides(*this, overridden);
4200 for (OverrideSearch::iterator
4201 OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) {
4202 ObjCMethodDecl *SuperOverridden = *OI;
Argyrios Kyrtzidis04703a62013-04-27 00:10:12 +00004203 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
4204 CurrentClass != SuperOverridden->getClassInterface()) {
Argyrios Kyrtzidisc2091d52013-04-17 00:09:08 +00004205 hasOverriddenMethodsInBaseOrProtocol = true;
4206 overridden->setOverriding(true);
4207 break;
4208 }
4209 }
4210 }
4211 }
4212 }
4213 }
4214 }
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004215
4216 // Propagate down the 'related result type' bit from overridden methods.
4217 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
4218 ObjCMethod->SetRelatedResultType();
4219
4220 // Then merge the declarations.
4221 mergeObjCMethodDecls(ObjCMethod, overridden);
4222
4223 if (ObjCMethod->isImplicit() && overridden->isImplicit())
4224 continue; // Conflicting properties are detected elsewhere.
4225
4226 // Check for overriding methods
4227 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
4228 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
4229 CheckConflictingOverridingMethod(ObjCMethod, overridden,
4230 isa<ObjCProtocolDecl>(overridden->getDeclContext()));
4231
4232 if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
Fariborz Jahanian31a25682012-07-05 22:26:07 +00004233 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
4234 !overridden->isImplicit() /* not meant for properties */) {
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004235 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
4236 E = ObjCMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +00004237 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
4238 PrevE = overridden->param_end();
4239 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004240 assert(PrevI != overridden->param_end() && "Param mismatch");
4241 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
4242 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
4243 // If type of argument of method in this class does not match its
4244 // respective argument type in the super class method, issue warning;
4245 if (!Context.typesAreCompatible(T1, T2)) {
4246 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
4247 << T1 << T2;
4248 Diag(overridden->getLocation(), diag::note_previous_declaration);
4249 break;
4250 }
4251 }
4252 }
4253 }
4254
4255 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
4256}
4257
Douglas Gregor813a0662015-06-19 18:14:38 +00004258/// Merge type nullability from for a redeclaration of the same entity,
4259/// producing the updated type of the redeclared entity.
4260static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc,
4261 QualType type,
4262 bool usesCSKeyword,
4263 SourceLocation prevLoc,
4264 QualType prevType,
4265 bool prevUsesCSKeyword) {
4266 // Determine the nullability of both types.
4267 auto nullability = type->getNullability(S.Context);
4268 auto prevNullability = prevType->getNullability(S.Context);
4269
4270 // Easy case: both have nullability.
4271 if (nullability.hasValue() == prevNullability.hasValue()) {
4272 // Neither has nullability; continue.
4273 if (!nullability)
4274 return type;
4275
4276 // The nullabilities are equivalent; do nothing.
4277 if (*nullability == *prevNullability)
4278 return type;
4279
4280 // Complain about mismatched nullability.
4281 S.Diag(loc, diag::err_nullability_conflicting)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00004282 << DiagNullabilityKind(*nullability, usesCSKeyword)
4283 << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword);
Douglas Gregor813a0662015-06-19 18:14:38 +00004284 return type;
4285 }
4286
4287 // If it's the redeclaration that has nullability, don't change anything.
4288 if (nullability)
4289 return type;
4290
4291 // Otherwise, provide the result with the same nullability.
4292 return S.Context.getAttributedType(
4293 AttributedType::getNullabilityAttrKind(*prevNullability),
4294 type, type);
4295}
4296
NAKAMURA Takumi2df5c3c2015-06-20 03:52:52 +00004297/// Merge information from the declaration of a method in the \@interface
Douglas Gregor813a0662015-06-19 18:14:38 +00004298/// (or a category/extension) into the corresponding method in the
4299/// @implementation (for a class or category).
4300static void mergeInterfaceMethodToImpl(Sema &S,
4301 ObjCMethodDecl *method,
4302 ObjCMethodDecl *prevMethod) {
4303 // Merge the objc_requires_super attribute.
4304 if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() &&
4305 !method->hasAttr<ObjCRequiresSuperAttr>()) {
4306 // merge the attribute into implementation.
4307 method->addAttr(
4308 ObjCRequiresSuperAttr::CreateImplicit(S.Context,
4309 method->getLocation()));
4310 }
4311
4312 // Merge nullability of the result type.
4313 QualType newReturnType
4314 = mergeTypeNullabilityForRedecl(
4315 S, method->getReturnTypeSourceRange().getBegin(),
4316 method->getReturnType(),
4317 method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4318 prevMethod->getReturnTypeSourceRange().getBegin(),
4319 prevMethod->getReturnType(),
4320 prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4321 method->setReturnType(newReturnType);
4322
4323 // Handle each of the parameters.
4324 unsigned numParams = method->param_size();
4325 unsigned numPrevParams = prevMethod->param_size();
4326 for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) {
4327 ParmVarDecl *param = method->param_begin()[i];
4328 ParmVarDecl *prevParam = prevMethod->param_begin()[i];
4329
4330 // Merge nullability.
4331 QualType newParamType
4332 = mergeTypeNullabilityForRedecl(
4333 S, param->getLocation(), param->getType(),
4334 param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4335 prevParam->getLocation(), prevParam->getType(),
4336 prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4337 param->setType(newParamType);
4338 }
4339}
4340
Alex Lorenza8a372d2017-04-27 10:43:48 +00004341/// Verify that the method parameters/return value have types that are supported
4342/// by the x86 target.
4343static void checkObjCMethodX86VectorTypes(Sema &SemaRef,
4344 const ObjCMethodDecl *Method) {
4345 assert(SemaRef.getASTContext().getTargetInfo().getTriple().getArch() ==
4346 llvm::Triple::x86 &&
4347 "x86-specific check invoked for a different target");
4348 SourceLocation Loc;
4349 QualType T;
4350 for (const ParmVarDecl *P : Method->parameters()) {
4351 if (P->getType()->isVectorType()) {
4352 Loc = P->getLocStart();
4353 T = P->getType();
4354 break;
4355 }
4356 }
4357 if (Loc.isInvalid()) {
4358 if (Method->getReturnType()->isVectorType()) {
4359 Loc = Method->getReturnTypeSourceRange().getBegin();
4360 T = Method->getReturnType();
4361 } else
4362 return;
4363 }
4364
4365 // Vector parameters/return values are not supported by objc_msgSend on x86 in
4366 // iOS < 9 and macOS < 10.11.
4367 const auto &Triple = SemaRef.getASTContext().getTargetInfo().getTriple();
4368 VersionTuple AcceptedInVersion;
4369 if (Triple.getOS() == llvm::Triple::IOS)
4370 AcceptedInVersion = VersionTuple(/*Major=*/9);
4371 else if (Triple.isMacOSX())
4372 AcceptedInVersion = VersionTuple(/*Major=*/10, /*Minor=*/11);
4373 else
4374 return;
Alex Lorenza8a372d2017-04-27 10:43:48 +00004375 if (SemaRef.getASTContext().getTargetInfo().getPlatformMinVersion() >=
Alex Lorenz92824832017-05-05 16:15:17 +00004376 AcceptedInVersion)
Alex Lorenza8a372d2017-04-27 10:43:48 +00004377 return;
4378 SemaRef.Diag(Loc, diag::err_objc_method_unsupported_param_ret_type)
4379 << T << (Method->getReturnType()->isVectorType() ? /*return value*/ 1
4380 : /*parameter*/ 0)
4381 << (Triple.isMacOSX() ? "macOS 10.11" : "iOS 9");
4382}
4383
John McCall48871652010-08-21 09:40:31 +00004384Decl *Sema::ActOnMethodDeclaration(
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004385 Scope *S,
Chris Lattnerda463fe2007-12-12 07:09:47 +00004386 SourceLocation MethodLoc, SourceLocation EndLoc,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004387 tok::TokenKind MethodType,
John McCallba7bf592010-08-24 05:47:05 +00004388 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004389 ArrayRef<SourceLocation> SelectorLocs,
Chris Lattnerda463fe2007-12-12 07:09:47 +00004390 Selector Sel,
4391 // optional arguments. The number of types/arguments is obtained
4392 // from the Sel.getNumArgs().
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004393 ObjCArgInfo *ArgInfo,
Fariborz Jahanian60462092010-04-08 00:30:06 +00004394 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
Chris Lattnerda463fe2007-12-12 07:09:47 +00004395 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
Fariborz Jahanianc677f692011-03-12 18:54:30 +00004396 bool isVariadic, bool MethodDefinition) {
Steve Naroff83777fe2008-02-29 21:48:07 +00004397 // Make sure we can establish a context for the method.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004398 if (!CurContext->isObjCContainer()) {
Richard Smithf8812672016-12-02 22:38:31 +00004399 Diag(MethodLoc, diag::err_missing_method_context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004400 return nullptr;
Steve Naroff83777fe2008-02-29 21:48:07 +00004401 }
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004402 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
4403 Decl *ClassDecl = cast<Decl>(OCD);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004404 QualType resultDeclType;
Mike Stump11289f42009-09-09 15:08:12 +00004405
Douglas Gregorbab8a962011-09-08 01:46:34 +00004406 bool HasRelatedResultType = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00004407 TypeSourceInfo *ReturnTInfo = nullptr;
Steve Naroff32606412009-02-20 22:59:16 +00004408 if (ReturnType) {
Alp Toker314cc812014-01-25 16:55:45 +00004409 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004410
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004411 if (CheckFunctionReturnType(resultDeclType, MethodLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00004412 return nullptr;
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004413
Douglas Gregor813a0662015-06-19 18:14:38 +00004414 QualType bareResultType = resultDeclType;
4415 (void)AttributedType::stripOuterNullability(bareResultType);
4416 HasRelatedResultType = (bareResultType == Context.getObjCInstanceType());
Fariborz Jahanianb5a52ca2011-07-21 17:00:47 +00004417 } else { // get the type for "id".
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004418 resultDeclType = Context.getObjCIdType();
Fariborz Jahanianb21138f2011-07-21 17:38:14 +00004419 Diag(MethodLoc, diag::warn_missing_method_return_type)
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004420 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
Fariborz Jahanianb5a52ca2011-07-21 17:00:47 +00004421 }
Mike Stump11289f42009-09-09 15:08:12 +00004422
Alp Toker314cc812014-01-25 16:55:45 +00004423 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
4424 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
4425 MethodType == tok::minus, isVariadic,
4426 /*isPropertyAccessor=*/false,
4427 /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
4428 MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
4429 : ObjCMethodDecl::Required,
4430 HasRelatedResultType);
Mike Stump11289f42009-09-09 15:08:12 +00004431
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004432 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump11289f42009-09-09 15:08:12 +00004433
Chris Lattner23b0faf2009-04-11 19:42:43 +00004434 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
John McCall856bbea2009-10-23 21:48:59 +00004435 QualType ArgType;
John McCallbcd03502009-12-07 02:54:59 +00004436 TypeSourceInfo *DI;
Mike Stump11289f42009-09-09 15:08:12 +00004437
David Blaikie7d170102013-05-15 07:37:26 +00004438 if (!ArgInfo[i].Type) {
John McCall856bbea2009-10-23 21:48:59 +00004439 ArgType = Context.getObjCIdType();
Craig Topperc3ec1492014-05-26 06:22:03 +00004440 DI = nullptr;
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004441 } else {
John McCall856bbea2009-10-23 21:48:59 +00004442 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004443 }
Mike Stump11289f42009-09-09 15:08:12 +00004444
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004445 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
4446 LookupOrdinaryName, ForRedeclaration);
4447 LookupName(R, S);
4448 if (R.isSingleResult()) {
4449 NamedDecl *PrevDecl = R.getFoundDecl();
4450 if (S->isDeclScope(PrevDecl)) {
Fariborz Jahanianc677f692011-03-12 18:54:30 +00004451 Diag(ArgInfo[i].NameLoc,
4452 (MethodDefinition ? diag::warn_method_param_redefinition
4453 : diag::warn_method_param_declaration))
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004454 << ArgInfo[i].Name;
4455 Diag(PrevDecl->getLocation(),
4456 diag::note_previous_declaration);
4457 }
4458 }
4459
Abramo Bagnaradff19302011-03-08 08:55:46 +00004460 SourceLocation StartLoc = DI
4461 ? DI->getTypeLoc().getBeginLoc()
4462 : ArgInfo[i].NameLoc;
4463
John McCalld44f4d72011-04-23 02:46:06 +00004464 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
4465 ArgInfo[i].NameLoc, ArgInfo[i].Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004466 ArgType, DI, SC_None);
Mike Stump11289f42009-09-09 15:08:12 +00004467
John McCall82490832011-05-02 00:30:12 +00004468 Param->setObjCMethodScopeInfo(i);
4469
Chris Lattnerc5ffed42008-04-04 06:12:32 +00004470 Param->setObjCDeclQualifier(
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004471 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
Mike Stump11289f42009-09-09 15:08:12 +00004472
Chris Lattner9713a1c2009-04-11 19:34:56 +00004473 // Apply the attributes to the parameter.
Douglas Gregor758a8692009-06-17 21:51:59 +00004474 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00004475 AddPragmaAttributes(TUScope, Param);
Mike Stump11289f42009-09-09 15:08:12 +00004476
Fariborz Jahanian52d02f62012-01-14 18:44:35 +00004477 if (Param->hasAttr<BlocksAttr>()) {
4478 Diag(Param->getLocation(), diag::err_block_on_nonlocal);
4479 Param->setInvalidDecl();
4480 }
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004481 S->AddDecl(Param);
4482 IdResolver.AddDecl(Param);
4483
Chris Lattnerc5ffed42008-04-04 06:12:32 +00004484 Params.push_back(Param);
4485 }
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004486
Fariborz Jahanian60462092010-04-08 00:30:06 +00004487 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +00004488 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
Fariborz Jahanian60462092010-04-08 00:30:06 +00004489 QualType ArgType = Param->getType();
4490 if (ArgType.isNull())
4491 ArgType = Context.getObjCIdType();
4492 else
4493 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
Douglas Gregor84280642011-07-12 04:42:08 +00004494 ArgType = Context.getAdjustedParameterType(ArgType);
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004495
Fariborz Jahanian60462092010-04-08 00:30:06 +00004496 Param->setDeclContext(ObjCMethod);
Fariborz Jahanian60462092010-04-08 00:30:06 +00004497 Params.push_back(Param);
4498 }
4499
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004500 ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004501 ObjCMethod->setObjCDeclQualifier(
4502 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
Daniel Dunbarc136e0c2008-09-26 04:12:28 +00004503
4504 if (AttrList)
Douglas Gregor758a8692009-06-17 21:51:59 +00004505 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00004506 AddPragmaAttributes(TUScope, ObjCMethod);
Mike Stump11289f42009-09-09 15:08:12 +00004507
Douglas Gregor87e92752010-12-21 17:34:17 +00004508 // Add the method now.
Craig Topperc3ec1492014-05-26 06:22:03 +00004509 const ObjCMethodDecl *PrevMethod = nullptr;
John McCalld2930c22011-07-22 02:45:48 +00004510 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00004511 if (MethodType == tok::minus) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004512 PrevMethod = ImpDecl->getInstanceMethod(Sel);
4513 ImpDecl->addInstanceMethod(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004514 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004515 PrevMethod = ImpDecl->getClassMethod(Sel);
4516 ImpDecl->addClassMethod(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004517 }
Douglas Gregor33823722011-06-11 01:09:30 +00004518
Douglas Gregor813a0662015-06-19 18:14:38 +00004519 // Merge information from the @interface declaration into the
4520 // @implementation.
4521 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) {
4522 if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
4523 ObjCMethod->isInstanceMethod())) {
4524 mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD);
4525
4526 // Warn about defining -dealloc in a category.
4527 if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() &&
4528 ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) {
4529 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
4530 << ObjCMethod->getDeclName();
4531 }
4532 }
Fariborz Jahanian7e350d22013-12-17 22:44:28 +00004533 }
Douglas Gregor87e92752010-12-21 17:34:17 +00004534 } else {
4535 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004536 }
John McCalld2930c22011-07-22 02:45:48 +00004537
Chris Lattnerda463fe2007-12-12 07:09:47 +00004538 if (PrevMethod) {
4539 // You can never have two method definitions with the same name.
Chris Lattner0369c572008-11-23 23:12:31 +00004540 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00004541 << ObjCMethod->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00004542 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian096f7c12013-05-13 17:27:00 +00004543 ObjCMethod->setInvalidDecl();
4544 return ObjCMethod;
Mike Stump11289f42009-09-09 15:08:12 +00004545 }
John McCall28a6aea2009-11-04 02:18:39 +00004546
Douglas Gregor33823722011-06-11 01:09:30 +00004547 // If this Objective-C method does not have a related result type, but we
4548 // are allowed to infer related result types, try to do so based on the
4549 // method family.
4550 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
4551 if (!CurrentClass) {
4552 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
4553 CurrentClass = Cat->getClassInterface();
4554 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
4555 CurrentClass = Impl->getClassInterface();
4556 else if (ObjCCategoryImplDecl *CatImpl
4557 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
4558 CurrentClass = CatImpl->getClassInterface();
4559 }
John McCalld2930c22011-07-22 02:45:48 +00004560
Douglas Gregorbab8a962011-09-08 01:46:34 +00004561 ResultTypeCompatibilityKind RTC
4562 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
John McCalld2930c22011-07-22 02:45:48 +00004563
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004564 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
John McCalld2930c22011-07-22 02:45:48 +00004565
John McCall31168b02011-06-15 23:02:42 +00004566 bool ARCError = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004567 if (getLangOpts().ObjCAutoRefCount)
John McCalle48f3892013-04-04 01:38:37 +00004568 ARCError = CheckARCMethodDecl(ObjCMethod);
John McCall31168b02011-06-15 23:02:42 +00004569
Douglas Gregorbab8a962011-09-08 01:46:34 +00004570 // Infer the related result type when possible.
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004571 if (!ARCError && RTC == Sema::RTC_Compatible &&
Douglas Gregorbab8a962011-09-08 01:46:34 +00004572 !ObjCMethod->hasRelatedResultType() &&
4573 LangOpts.ObjCInferRelatedResultType) {
Douglas Gregor33823722011-06-11 01:09:30 +00004574 bool InferRelatedResultType = false;
4575 switch (ObjCMethod->getMethodFamily()) {
4576 case OMF_None:
4577 case OMF_copy:
4578 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +00004579 case OMF_finalize:
Douglas Gregor33823722011-06-11 01:09:30 +00004580 case OMF_mutableCopy:
4581 case OMF_release:
4582 case OMF_retainCount:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00004583 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00004584 case OMF_performSelector:
Douglas Gregor33823722011-06-11 01:09:30 +00004585 break;
4586
4587 case OMF_alloc:
4588 case OMF_new:
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00004589 InferRelatedResultType = ObjCMethod->isClassMethod();
Douglas Gregor33823722011-06-11 01:09:30 +00004590 break;
4591
4592 case OMF_init:
4593 case OMF_autorelease:
4594 case OMF_retain:
4595 case OMF_self:
4596 InferRelatedResultType = ObjCMethod->isInstanceMethod();
4597 break;
4598 }
4599
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00004600 if (InferRelatedResultType &&
4601 !ObjCMethod->getReturnType()->isObjCIndependentClassType())
Douglas Gregor33823722011-06-11 01:09:30 +00004602 ObjCMethod->SetRelatedResultType();
Douglas Gregor33823722011-06-11 01:09:30 +00004603 }
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00004604
Alex Lorenza8a372d2017-04-27 10:43:48 +00004605 if (MethodDefinition &&
4606 Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
4607 checkObjCMethodX86VectorTypes(*this, ObjCMethod);
4608
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00004609 ActOnDocumentableDecl(ObjCMethod);
4610
John McCall48871652010-08-21 09:40:31 +00004611 return ObjCMethod;
Chris Lattnerda463fe2007-12-12 07:09:47 +00004612}
4613
Chris Lattner438e5012008-12-17 07:13:27 +00004614bool Sema::CheckObjCDeclScope(Decl *D) {
Fariborz Jahanianf36734d2011-08-22 18:34:22 +00004615 // Following is also an error. But it is caused by a missing @end
4616 // and diagnostic is issued elsewhere.
Argyrios Kyrtzidis822c4332012-03-23 23:24:23 +00004617 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004618 return false;
Argyrios Kyrtzidis822c4332012-03-23 23:24:23 +00004619
4620 // If we switched context to translation unit while we are still lexically in
4621 // an objc container, it means the parser missed emitting an error.
4622 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
4623 return false;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004624
Anders Carlssona6b508a2008-11-04 16:57:32 +00004625 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
4626 D->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004627
Anders Carlssona6b508a2008-11-04 16:57:32 +00004628 return true;
4629}
Chris Lattner438e5012008-12-17 07:13:27 +00004630
James Dennett634962f2012-06-14 21:40:34 +00004631/// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
Chris Lattner438e5012008-12-17 07:13:27 +00004632/// instance variables of ClassName into Decls.
John McCall48871652010-08-21 09:40:31 +00004633void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
Chris Lattner438e5012008-12-17 07:13:27 +00004634 IdentifierInfo *ClassName,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004635 SmallVectorImpl<Decl*> &Decls) {
Chris Lattner438e5012008-12-17 07:13:27 +00004636 // Check that ClassName is a valid class
Douglas Gregorb2ccf012010-04-15 22:33:43 +00004637 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
Chris Lattner438e5012008-12-17 07:13:27 +00004638 if (!Class) {
4639 Diag(DeclStart, diag::err_undef_interface) << ClassName;
4640 return;
4641 }
John McCall5fb5df92012-06-20 06:18:46 +00004642 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanianece1b2b2009-04-21 20:28:41 +00004643 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
4644 return;
4645 }
Mike Stump11289f42009-09-09 15:08:12 +00004646
Chris Lattner438e5012008-12-17 07:13:27 +00004647 // Collect the instance variables
Jordy Rosea91768e2011-07-22 02:08:32 +00004648 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004649 Context.DeepCollectObjCIvars(Class, true, Ivars);
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004650 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004651 for (unsigned i = 0; i < Ivars.size(); i++) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004652 const FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
John McCall48871652010-08-21 09:40:31 +00004653 RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
Abramo Bagnaradff19302011-03-08 08:55:46 +00004654 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
4655 /*FIXME: StartL=*/ID->getLocation(),
4656 ID->getLocation(),
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004657 ID->getIdentifier(), ID->getType(),
4658 ID->getBitWidth());
John McCall48871652010-08-21 09:40:31 +00004659 Decls.push_back(FD);
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004660 }
Mike Stump11289f42009-09-09 15:08:12 +00004661
Chris Lattner438e5012008-12-17 07:13:27 +00004662 // Introduce all of these fields into the appropriate scope.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004663 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
Chris Lattner438e5012008-12-17 07:13:27 +00004664 D != Decls.end(); ++D) {
John McCall48871652010-08-21 09:40:31 +00004665 FieldDecl *FD = cast<FieldDecl>(*D);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004666 if (getLangOpts().CPlusPlus)
Chris Lattner438e5012008-12-17 07:13:27 +00004667 PushOnScopeChains(cast<FieldDecl>(FD), S);
John McCall48871652010-08-21 09:40:31 +00004668 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004669 Record->addDecl(FD);
Chris Lattner438e5012008-12-17 07:13:27 +00004670 }
4671}
4672
Douglas Gregorf3564192010-04-26 17:32:49 +00004673/// \brief Build a type-check a new Objective-C exception variable declaration.
Abramo Bagnaradff19302011-03-08 08:55:46 +00004674VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
4675 SourceLocation StartLoc,
4676 SourceLocation IdLoc,
4677 IdentifierInfo *Id,
Douglas Gregorf3564192010-04-26 17:32:49 +00004678 bool Invalid) {
4679 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
4680 // duration shall not be qualified by an address-space qualifier."
4681 // Since all parameters have automatic store duration, they can not have
4682 // an address space.
4683 if (T.getAddressSpace() != 0) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004684 Diag(IdLoc, diag::err_arg_with_address_space);
Douglas Gregorf3564192010-04-26 17:32:49 +00004685 Invalid = true;
4686 }
4687
4688 // An @catch parameter must be an unqualified object pointer type;
4689 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
4690 if (Invalid) {
4691 // Don't do any further checking.
Douglas Gregorf4e837f2010-04-26 17:57:08 +00004692 } else if (T->isDependentType()) {
4693 // Okay: we don't know what this type will instantiate to.
Douglas Gregorf3564192010-04-26 17:32:49 +00004694 } else if (!T->isObjCObjectPointerType()) {
4695 Invalid = true;
Abramo Bagnaradff19302011-03-08 08:55:46 +00004696 Diag(IdLoc ,diag::err_catch_param_not_objc_type);
Douglas Gregorf3564192010-04-26 17:32:49 +00004697 } else if (T->isObjCQualifiedIdType()) {
4698 Invalid = true;
Abramo Bagnaradff19302011-03-08 08:55:46 +00004699 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00004700 }
4701
Abramo Bagnaradff19302011-03-08 08:55:46 +00004702 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004703 T, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00004704 New->setExceptionVariable(true);
4705
Douglas Gregor8ca0c642011-12-10 01:22:52 +00004706 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004707 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
Douglas Gregor8ca0c642011-12-10 01:22:52 +00004708 Invalid = true;
4709
Douglas Gregorf3564192010-04-26 17:32:49 +00004710 if (Invalid)
4711 New->setInvalidDecl();
4712 return New;
4713}
4714
John McCall48871652010-08-21 09:40:31 +00004715Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
Douglas Gregorf3564192010-04-26 17:32:49 +00004716 const DeclSpec &DS = D.getDeclSpec();
4717
4718 // We allow the "register" storage class on exception variables because
4719 // GCC did, but we drop it completely. Any other storage class is an error.
4720 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
4721 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
4722 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
Richard Smithb4a9e862013-04-12 22:46:28 +00004723 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
Douglas Gregorf3564192010-04-26 17:32:49 +00004724 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
Richard Smithb4a9e862013-04-12 22:46:28 +00004725 << DeclSpec::getSpecifierName(SCS);
4726 }
Richard Smith62f19e72016-06-25 00:15:56 +00004727 if (DS.isInlineSpecified())
4728 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4729 << getLangOpts().CPlusPlus1z;
Richard Smithb4a9e862013-04-12 22:46:28 +00004730 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
4731 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
4732 diag::err_invalid_thread)
4733 << DeclSpec::getSpecifierName(TSCS);
Douglas Gregorf3564192010-04-26 17:32:49 +00004734 D.getMutableDeclSpec().ClearStorageClassSpecs();
4735
Richard Smithb1402ae2013-03-18 22:52:47 +00004736 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregorf3564192010-04-26 17:32:49 +00004737
4738 // Check that there are no default arguments inside the type of this
4739 // exception object (C++ only).
David Blaikiebbafb8a2012-03-11 07:00:24 +00004740 if (getLangOpts().CPlusPlus)
Douglas Gregorf3564192010-04-26 17:32:49 +00004741 CheckExtraCXXDefaultArguments(D);
4742
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00004743 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00004744 QualType ExceptionType = TInfo->getType();
Douglas Gregorf3564192010-04-26 17:32:49 +00004745
Abramo Bagnaradff19302011-03-08 08:55:46 +00004746 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
4747 D.getSourceRange().getBegin(),
4748 D.getIdentifierLoc(),
4749 D.getIdentifier(),
Douglas Gregorf3564192010-04-26 17:32:49 +00004750 D.isInvalidType());
4751
4752 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
4753 if (D.getCXXScopeSpec().isSet()) {
4754 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
4755 << D.getCXXScopeSpec().getRange();
4756 New->setInvalidDecl();
4757 }
4758
4759 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00004760 S->AddDecl(New);
Douglas Gregorf3564192010-04-26 17:32:49 +00004761 if (D.getIdentifier())
4762 IdResolver.AddDecl(New);
4763
4764 ProcessDeclAttributes(S, New, D);
4765
4766 if (New->hasAttr<BlocksAttr>())
4767 Diag(New->getLocation(), diag::err_block_on_nonlocal);
John McCall48871652010-08-21 09:40:31 +00004768 return New;
Douglas Gregore11ee112010-04-23 23:01:43 +00004769}
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004770
4771/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004772/// initialization.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004773void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004774 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004775 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
4776 Iv= Iv->getNextIvar()) {
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004777 QualType QT = Context.getBaseElementType(Iv->getType());
Douglas Gregor527786e2010-05-20 02:24:22 +00004778 if (QT->isRecordType())
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004779 Ivars.push_back(Iv);
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004780 }
4781}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004782
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004783void Sema::DiagnoseUseOfUnimplementedSelectors() {
Douglas Gregor72e357f2011-07-28 14:54:22 +00004784 // Load referenced selectors from the external source.
4785 if (ExternalSource) {
4786 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
4787 ExternalSource->ReadReferencedSelectors(Sels);
4788 for (unsigned I = 0, N = Sels.size(); I != N; ++I)
4789 ReferencedSelectors[Sels[I].first] = Sels[I].second;
4790 }
4791
Fariborz Jahanianc9b7c202011-02-04 23:19:27 +00004792 // Warning will be issued only when selector table is
4793 // generated (which means there is at lease one implementation
4794 // in the TU). This is to match gcc's behavior.
4795 if (ReferencedSelectors.empty() ||
4796 !Context.AnyObjCImplementation())
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004797 return;
Chandler Carruth12c8f652015-03-27 00:55:05 +00004798 for (auto &SelectorAndLocation : ReferencedSelectors) {
4799 Selector Sel = SelectorAndLocation.first;
4800 SourceLocation Loc = SelectorAndLocation.second;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004801 if (!LookupImplementedMethodInGlobalPool(Sel))
Chandler Carruth12c8f652015-03-27 00:55:05 +00004802 Diag(Loc, diag::warn_unimplemented_selector) << Sel;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004803 }
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004804}
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004805
4806ObjCIvarDecl *
4807Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4808 const ObjCPropertyDecl *&PDecl) const {
Fariborz Jahanian1cc7ae12014-01-02 17:24:32 +00004809 if (Method->isClassMethod())
Craig Topperc3ec1492014-05-26 06:22:03 +00004810 return nullptr;
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004811 const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
4812 if (!IDecl)
Craig Topperc3ec1492014-05-26 06:22:03 +00004813 return nullptr;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004814 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
4815 /*shallowCategoryLookup=*/false,
4816 /*followSuper=*/false);
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004817 if (!Method || !Method->isPropertyAccessor())
Craig Topperc3ec1492014-05-26 06:22:03 +00004818 return nullptr;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004819 if ((PDecl = Method->findPropertyDecl()))
Fariborz Jahanian122d94f2014-01-27 22:27:43 +00004820 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
4821 // property backing ivar must belong to property's class
4822 // or be a private ivar in class's implementation.
4823 // FIXME. fix the const-ness issue.
4824 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
4825 IV->getIdentifier());
4826 return IV;
4827 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004828 return nullptr;
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004829}
4830
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004831namespace {
4832 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
4833 /// accessor references the backing ivar.
Argyrios Kyrtzidis98045c12014-01-03 19:53:09 +00004834 class UnusedBackingIvarChecker :
Richard Smith50668452015-11-24 03:55:01 +00004835 public RecursiveASTVisitor<UnusedBackingIvarChecker> {
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004836 public:
4837 Sema &S;
4838 const ObjCMethodDecl *Method;
4839 const ObjCIvarDecl *IvarD;
4840 bool AccessedIvar;
4841 bool InvokedSelfMethod;
4842
4843 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
4844 const ObjCIvarDecl *IvarD)
4845 : S(S), Method(Method), IvarD(IvarD),
4846 AccessedIvar(false), InvokedSelfMethod(false) {
4847 assert(IvarD);
4848 }
4849
4850 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
4851 if (E->getDecl() == IvarD) {
4852 AccessedIvar = true;
4853 return false;
4854 }
4855 return true;
4856 }
4857
4858 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
4859 if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
4860 S.isSelfExpr(E->getInstanceReceiver(), Method)) {
4861 InvokedSelfMethod = true;
4862 }
4863 return true;
4864 }
4865 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00004866} // end anonymous namespace
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004867
4868void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
4869 const ObjCImplementationDecl *ImplD) {
4870 if (S->hasUnrecoverableErrorOccurred())
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004871 return;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004872
Aaron Ballmanf26acce2014-03-13 19:50:17 +00004873 for (const auto *CurMethod : ImplD->instance_methods()) {
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004874 unsigned DIAG = diag::warn_unused_property_backing_ivar;
4875 SourceLocation Loc = CurMethod->getLocation();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004876 if (Diags.isIgnored(DIAG, Loc))
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004877 continue;
4878
4879 const ObjCPropertyDecl *PDecl;
4880 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
4881 if (!IV)
4882 continue;
4883
4884 UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
4885 Checker.TraverseStmt(CurMethod->getBody());
4886 if (Checker.AccessedIvar)
4887 continue;
4888
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00004889 // Do not issue this warning if backing ivar is used somewhere and accessor
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004890 // implementation makes a self call. This is to prevent false positive in
4891 // cases where the ivar is accessed by another method that the accessor
4892 // delegates to.
4893 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
Argyrios Kyrtzidisd8a35322014-01-03 19:39:23 +00004894 Diag(Loc, DIAG) << IV;
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00004895 Diag(PDecl->getLocation(), diag::note_property_declare);
4896 }
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004897 }
4898}