blob: ac1d8cf7a381f72a027fc293f94ac40dbb335a78 [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
Akira Hatanakaa6b5e002018-07-28 04:06:13 +0000112/// Issue a warning if the parameter of the overridden method is non-escaping
113/// but the parameter of the overriding method is not.
114static bool diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD,
115 Sema &S) {
116 if (OldD->hasAttr<NoEscapeAttr>() && !NewD->hasAttr<NoEscapeAttr>()) {
117 S.Diag(NewD->getLocation(), diag::warn_overriding_method_missing_noescape);
118 S.Diag(OldD->getLocation(), diag::note_overridden_marked_noescape);
119 return false;
120 }
121
122 return true;
123}
124
125/// Produce additional diagnostics if a category conforms to a protocol that
126/// defines a method taking a non-escaping parameter.
127static void diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD,
128 const ObjCCategoryDecl *CD,
129 const ObjCProtocolDecl *PD, Sema &S) {
130 if (!diagnoseNoescape(NewD, OldD, S))
131 S.Diag(CD->getLocation(), diag::note_cat_conform_to_noescape_prot)
132 << CD->IsClassExtension() << PD
133 << cast<ObjCMethodDecl>(NewD->getDeclContext());
134}
135
Fangrui Song6907ce22018-07-30 19:24:48 +0000136void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
Douglas Gregor66a8ca02013-01-15 22:43:08 +0000137 const ObjCMethodDecl *Overridden) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000138 if (Overridden->hasRelatedResultType() &&
Douglas Gregor33823722011-06-11 01:09:30 +0000139 !NewMethod->hasRelatedResultType()) {
140 // This can only happen when the method follows a naming convention that
141 // implies a related result type, and the original (overridden) method has
142 // a suitable return type, but the new (overriding) method does not have
143 // a suitable return type.
Alp Toker314cc812014-01-25 16:55:45 +0000144 QualType ResultType = NewMethod->getReturnType();
Aaron Ballman41b10ac2014-08-01 13:20:09 +0000145 SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange();
Fangrui Song6907ce22018-07-30 19:24:48 +0000146
Douglas Gregor33823722011-06-11 01:09:30 +0000147 // Figure out which class this method is part of, if any.
Fangrui Song6907ce22018-07-30 19:24:48 +0000148 ObjCInterfaceDecl *CurrentClass
Douglas Gregor33823722011-06-11 01:09:30 +0000149 = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
150 if (!CurrentClass) {
151 DeclContext *DC = NewMethod->getDeclContext();
152 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
153 CurrentClass = Cat->getClassInterface();
154 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
155 CurrentClass = Impl->getClassInterface();
156 else if (ObjCCategoryImplDecl *CatImpl
157 = dyn_cast<ObjCCategoryImplDecl>(DC))
158 CurrentClass = CatImpl->getClassInterface();
159 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000160
Douglas Gregor33823722011-06-11 01:09:30 +0000161 if (CurrentClass) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000162 Diag(NewMethod->getLocation(),
Douglas Gregor33823722011-06-11 01:09:30 +0000163 diag::warn_related_result_type_compatibility_class)
164 << Context.getObjCInterfaceType(CurrentClass)
165 << ResultType
166 << ResultTypeRange;
167 } else {
Fangrui Song6907ce22018-07-30 19:24:48 +0000168 Diag(NewMethod->getLocation(),
Douglas Gregor33823722011-06-11 01:09:30 +0000169 diag::warn_related_result_type_compatibility_protocol)
170 << ResultType
171 << ResultTypeRange;
172 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000173
Douglas Gregorbab8a962011-09-08 01:46:34 +0000174 if (ObjCMethodFamily Family = Overridden->getMethodFamily())
Fangrui Song6907ce22018-07-30 19:24:48 +0000175 Diag(Overridden->getLocation(),
John McCall5ec7e7d2013-03-19 07:04:25 +0000176 diag::note_related_result_type_family)
177 << /*overridden method*/ 0
Douglas Gregorbab8a962011-09-08 01:46:34 +0000178 << Family;
179 else
Fangrui Song6907ce22018-07-30 19:24:48 +0000180 Diag(Overridden->getLocation(),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000181 diag::note_related_result_type_overridden);
Douglas Gregor33823722011-06-11 01:09:30 +0000182 }
Akira Hatanaka7d85b8f2017-09-20 05:39:18 +0000183
184 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
185 Overridden->hasAttr<NSReturnsRetainedAttr>())) {
186 Diag(NewMethod->getLocation(),
Alex Lorenz26d282f2018-01-03 23:52:42 +0000187 getLangOpts().ObjCAutoRefCount
188 ? diag::err_nsreturns_retained_attribute_mismatch
189 : diag::warn_nsreturns_retained_attribute_mismatch)
190 << 1;
Akira Hatanaka7d85b8f2017-09-20 05:39:18 +0000191 Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
192 }
193 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
194 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
195 Diag(NewMethod->getLocation(),
Alex Lorenz26d282f2018-01-03 23:52:42 +0000196 getLangOpts().ObjCAutoRefCount
197 ? diag::err_nsreturns_retained_attribute_mismatch
198 : diag::warn_nsreturns_retained_attribute_mismatch)
199 << 0;
Akira Hatanaka7d85b8f2017-09-20 05:39:18 +0000200 Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
201 }
202
203 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
204 oe = Overridden->param_end();
205 for (ObjCMethodDecl::param_iterator ni = NewMethod->param_begin(),
206 ne = NewMethod->param_end();
207 ni != ne && oi != oe; ++ni, ++oi) {
208 const ParmVarDecl *oldDecl = (*oi);
209 ParmVarDecl *newDecl = (*ni);
210 if (newDecl->hasAttr<NSConsumedAttr>() !=
211 oldDecl->hasAttr<NSConsumedAttr>()) {
Alex Lorenz26d282f2018-01-03 23:52:42 +0000212 Diag(newDecl->getLocation(),
213 getLangOpts().ObjCAutoRefCount
214 ? diag::err_nsconsumed_attribute_mismatch
215 : diag::warn_nsconsumed_attribute_mismatch);
Akira Hatanaka7d85b8f2017-09-20 05:39:18 +0000216 Diag(oldDecl->getLocation(), diag::note_previous_decl) << "parameter";
Fariborz Jahanianac8dbf02011-09-27 22:35:36 +0000217 }
Akira Hatanaka98a49332017-09-22 00:41:05 +0000218
Akira Hatanakaa6b5e002018-07-28 04:06:13 +0000219 diagnoseNoescape(newDecl, oldDecl, *this);
Fariborz Jahanianac8dbf02011-09-27 22:35:36 +0000220 }
Douglas Gregor33823722011-06-11 01:09:30 +0000221}
222
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000223/// Check a method declaration for compatibility with the Objective-C
John McCall31168b02011-06-15 23:02:42 +0000224/// ARC conventions.
John McCalle48f3892013-04-04 01:38:37 +0000225bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
John McCall31168b02011-06-15 23:02:42 +0000226 ObjCMethodFamily family = method->getMethodFamily();
227 switch (family) {
228 case OMF_None:
Nico Weber1fb82662011-08-28 22:35:17 +0000229 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +0000230 case OMF_retain:
231 case OMF_release:
232 case OMF_autorelease:
233 case OMF_retainCount:
234 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +0000235 case OMF_initialize:
John McCalld2930c22011-07-22 02:45:48 +0000236 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +0000237 return false;
238
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000239 case OMF_dealloc:
Alp Toker314cc812014-01-25 16:55:45 +0000240 if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
Aaron Ballman41b10ac2014-08-01 13:20:09 +0000241 SourceRange ResultTypeRange = method->getReturnTypeSourceRange();
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000242 if (ResultTypeRange.isInvalid())
Richard Smithf8812672016-12-02 22:38:31 +0000243 Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
Alp Toker314cc812014-01-25 16:55:45 +0000244 << method->getReturnType()
245 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000246 else
Richard Smithf8812672016-12-02 22:38:31 +0000247 Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
Alp Toker314cc812014-01-25 16:55:45 +0000248 << method->getReturnType()
249 << FixItHint::CreateReplacement(ResultTypeRange, "void");
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000250 return true;
251 }
252 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000253
John McCall31168b02011-06-15 23:02:42 +0000254 case OMF_init:
255 // If the method doesn't obey the init rules, don't bother annotating it.
John McCalle48f3892013-04-04 01:38:37 +0000256 if (checkInitMethod(method, QualType()))
John McCall31168b02011-06-15 23:02:42 +0000257 return true;
258
Aaron Ballman36a53502014-01-16 13:03:14 +0000259 method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
John McCall31168b02011-06-15 23:02:42 +0000260
261 // Don't add a second copy of this attribute, but otherwise don't
262 // let it be suppressed.
263 if (method->hasAttr<NSReturnsRetainedAttr>())
264 return false;
265 break;
266
267 case OMF_alloc:
268 case OMF_copy:
269 case OMF_mutableCopy:
270 case OMF_new:
271 if (method->hasAttr<NSReturnsRetainedAttr>() ||
272 method->hasAttr<NSReturnsNotRetainedAttr>() ||
273 method->hasAttr<NSReturnsAutoreleasedAttr>())
274 return false;
275 break;
276 }
277
Aaron Ballman36a53502014-01-16 13:03:14 +0000278 method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
John McCall31168b02011-06-15 23:02:42 +0000279 return false;
280}
281
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000282static void DiagnoseObjCImplementedDeprecations(Sema &S, const NamedDecl *ND,
283 SourceLocation ImplLoc) {
284 if (!ND)
285 return;
286 bool IsCategory = false;
Alex Lorenzf4d4cfb2018-05-03 01:12:06 +0000287 StringRef RealizedPlatform;
288 AvailabilityResult Availability = ND->getAvailability(
289 /*Message=*/nullptr, /*EnclosingVersion=*/VersionTuple(),
290 &RealizedPlatform);
Alex Lorenze1088dc2017-07-13 16:37:11 +0000291 if (Availability != AR_Deprecated) {
Eric Christopher7aba9782017-07-14 01:42:57 +0000292 if (isa<ObjCMethodDecl>(ND)) {
Alex Lorenze1088dc2017-07-13 16:37:11 +0000293 if (Availability != AR_Unavailable)
294 return;
Alex Lorenzf4d4cfb2018-05-03 01:12:06 +0000295 if (RealizedPlatform.empty())
296 RealizedPlatform = S.Context.getTargetInfo().getPlatformName();
297 // Warn about implementing unavailable methods, unless the unavailable
298 // is for an app extension.
299 if (RealizedPlatform.endswith("_app_extension"))
300 return;
Alex Lorenze1088dc2017-07-13 16:37:11 +0000301 S.Diag(ImplLoc, diag::warn_unavailable_def);
302 S.Diag(ND->getLocation(), diag::note_method_declared_at)
303 << ND->getDeclName();
304 return;
305 }
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000306 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND)) {
307 if (!CD->getClassInterface()->isDeprecated())
308 return;
309 ND = CD->getClassInterface();
310 IsCategory = true;
311 } else
312 return;
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000313 }
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000314 S.Diag(ImplLoc, diag::warn_deprecated_def)
315 << (isa<ObjCMethodDecl>(ND)
316 ? /*Method*/ 0
317 : isa<ObjCCategoryDecl>(ND) || IsCategory ? /*Category*/ 2
318 : /*Class*/ 1);
319 if (isa<ObjCMethodDecl>(ND))
320 S.Diag(ND->getLocation(), diag::note_method_declared_at)
321 << ND->getDeclName();
322 else
323 S.Diag(ND->getLocation(), diag::note_previous_decl)
324 << (isa<ObjCCategoryDecl>(ND) ? "category" : "class");
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000325}
326
Fariborz Jahanianbd0642f2011-08-31 17:37:55 +0000327/// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
328/// pool.
329void Sema::AddAnyMethodToGlobalPool(Decl *D) {
330 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
Fangrui Song6907ce22018-07-30 19:24:48 +0000331
Fariborz Jahanianbd0642f2011-08-31 17:37:55 +0000332 // If we don't have a valid method decl, simply return.
333 if (!MDecl)
334 return;
335 if (MDecl->isInstanceMethod())
336 AddInstanceMethodToGlobalPool(MDecl, true);
337 else
338 AddFactoryMethodToGlobalPool(MDecl, true);
339}
340
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000341/// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
342/// has explicit ownership attribute; false otherwise.
343static bool
344HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
345 QualType T = Param->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000346
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000347 if (const PointerType *PT = T->getAs<PointerType>()) {
348 T = PT->getPointeeType();
349 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
350 T = RT->getPointeeType();
351 } else {
352 return true;
353 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000354
355 // If we have a lifetime qualifier, but it's local, we must have
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000356 // inferred it. So, it is implicit.
357 return !T.getLocalQualifiers().hasObjCLifetime();
358}
359
Fariborz Jahanian18d0a5d2012-08-08 23:41:08 +0000360/// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
361/// and user declared, in the method definition's AST.
362void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000363 assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
John McCall48871652010-08-21 09:40:31 +0000364 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
Fangrui Song6907ce22018-07-30 19:24:48 +0000365
Steve Naroff542cd5d2008-07-25 17:57:26 +0000366 // If we don't have a valid method decl, simply return.
367 if (!MDecl)
368 return;
Steve Naroff1d2538c2007-12-18 01:30:32 +0000369
Akira Hatanakaff6c4f32018-04-12 06:01:41 +0000370 QualType ResultType = MDecl->getReturnType();
371 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
372 !MDecl->isInvalidDecl() &&
373 RequireCompleteType(MDecl->getLocation(), ResultType,
374 diag::err_func_def_incomplete_result))
375 MDecl->setInvalidDecl();
376
Chris Lattnerda463fe2007-12-12 07:09:47 +0000377 // Allow all of Sema to see that we are entering a method definition.
Douglas Gregor91f84212008-12-11 16:49:14 +0000378 PushDeclContext(FnBodyScope, MDecl);
Douglas Gregor9a28e842010-03-01 23:15:13 +0000379 PushFunctionScope();
Fangrui Song6907ce22018-07-30 19:24:48 +0000380
Chris Lattnerda463fe2007-12-12 07:09:47 +0000381 // Create Decl objects for each parameter, entrring them in the scope for
382 // binding to their use.
Chris Lattnerda463fe2007-12-12 07:09:47 +0000383
384 // Insert the invisible arguments, self and _cmd!
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000385 MDecl->createImplicitParams(Context, MDecl->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000386
Daniel Dunbar279d1cc2008-08-26 06:07:48 +0000387 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
388 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000389
Reid Kleckner5a115802013-06-24 14:38:26 +0000390 // The ObjC parser requires parameter names so there's no need to check.
David Majnemer59f77922016-06-24 04:05:48 +0000391 CheckParmsForFunctionDef(MDecl->parameters(),
Reid Kleckner5a115802013-06-24 14:38:26 +0000392 /*CheckParameterNames=*/false);
393
Chris Lattner58258242008-04-10 02:22:51 +0000394 // Introduce all of the other parameters into this scope.
David Majnemer59f77922016-06-24 04:05:48 +0000395 for (auto *Param : MDecl->parameters()) {
Fariborz Jahanianb3e87122010-09-17 22:07:07 +0000396 if (!Param->isInvalidDecl() &&
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000397 getLangOpts().ObjCAutoRefCount &&
398 !HasExplicitOwnershipAttr(*this, Param))
399 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
400 Param->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000401
Aaron Ballman43b68be2014-03-07 17:50:17 +0000402 if (Param->getIdentifier())
403 PushOnScopeChains(Param, FnBodyScope);
Fariborz Jahanianb3e87122010-09-17 22:07:07 +0000404 }
John McCall31168b02011-06-15 23:02:42 +0000405
406 // In ARC, disallow definition of retain/release/autorelease/retainCount
David Blaikiebbafb8a2012-03-11 07:00:24 +0000407 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +0000408 switch (MDecl->getMethodFamily()) {
409 case OMF_retain:
410 case OMF_retainCount:
411 case OMF_release:
412 case OMF_autorelease:
413 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
Fariborz Jahanian39d1c422013-05-16 19:08:44 +0000414 << 0 << MDecl->getSelector();
John McCall31168b02011-06-15 23:02:42 +0000415 break;
416
417 case OMF_None:
418 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +0000419 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +0000420 case OMF_alloc:
421 case OMF_init:
422 case OMF_mutableCopy:
423 case OMF_copy:
424 case OMF_new:
425 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +0000426 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +0000427 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +0000428 break;
429 }
430 }
431
Nico Weber715abaf2011-08-22 17:25:57 +0000432 // Warn on deprecated methods under -Wdeprecated-implementations,
433 // and prepare for warning on missing super calls.
434 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000435 ObjCMethodDecl *IMD =
Fariborz Jahanian566fff02012-09-07 23:46:23 +0000436 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
Fangrui Song6907ce22018-07-30 19:24:48 +0000437
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000438 if (IMD) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000439 ObjCImplDecl *ImplDeclOfMethodDef =
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000440 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
Fangrui Song6907ce22018-07-30 19:24:48 +0000441 ObjCContainerDecl *ContDeclOfMethodDecl =
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000442 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
Craig Topperc3ec1492014-05-26 06:22:03 +0000443 ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000444 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
445 ImplDeclOfMethodDecl = OID->getImplementation();
Fariborz Jahanianed39e7c2014-03-18 16:25:22 +0000446 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
447 if (CD->IsClassExtension()) {
448 if (ObjCInterfaceDecl *OID = CD->getClassInterface())
449 ImplDeclOfMethodDecl = OID->getImplementation();
450 } else
451 ImplDeclOfMethodDecl = CD->getImplementation();
Fariborz Jahanian19a08bb2014-03-18 00:10:37 +0000452 }
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000453 // No need to issue deprecated warning if deprecated mehod in class/category
454 // is being implemented in its own implementation (no overriding is involved).
Fariborz Jahanianed39e7c2014-03-18 16:25:22 +0000455 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000456 DiagnoseObjCImplementedDeprecations(*this, IMD, MDecl->getLocation());
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000457 }
Nico Weber715abaf2011-08-22 17:25:57 +0000458
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000459 if (MDecl->getMethodFamily() == OMF_init) {
460 if (MDecl->isDesignatedInitializerForTheInterface()) {
461 getCurFunction()->ObjCIsDesignatedInit = true;
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +0000462 getCurFunction()->ObjCWarnForNoDesignatedInitChain =
Craig Topperc3ec1492014-05-26 06:22:03 +0000463 IC->getSuperClass() != nullptr;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000464 } else if (IC->hasDesignatedInitializers()) {
465 getCurFunction()->ObjCIsSecondaryInit = true;
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +0000466 getCurFunction()->ObjCWarnForNoInitDelegation = true;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000467 }
468 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +0000469
Nico Weber1fb82662011-08-28 22:35:17 +0000470 // If this is "dealloc" or "finalize", set some bit here.
Nico Weber715abaf2011-08-22 17:25:57 +0000471 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
472 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
473 // Only do this if the current class actually has a superclass.
Jordan Rosed03d99d2013-03-05 01:27:54 +0000474 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
Jordan Rose2afd6612012-10-19 16:05:26 +0000475 ObjCMethodFamily Family = MDecl->getMethodFamily();
476 if (Family == OMF_dealloc) {
477 if (!(getLangOpts().ObjCAutoRefCount ||
478 getLangOpts().getGC() == LangOptions::GCOnly))
479 getCurFunction()->ObjCShouldCallSuper = true;
480
481 } else if (Family == OMF_finalize) {
482 if (Context.getLangOpts().getGC() != LangOptions::NonGC)
483 getCurFunction()->ObjCShouldCallSuper = true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000484
Fariborz Jahaniance4bbb22013-11-05 00:28:21 +0000485 } else {
Jordan Rose2afd6612012-10-19 16:05:26 +0000486 const ObjCMethodDecl *SuperMethod =
Jordan Rosed03d99d2013-03-05 01:27:54 +0000487 SuperClass->lookupMethod(MDecl->getSelector(),
488 MDecl->isInstanceMethod());
Fangrui Song6907ce22018-07-30 19:24:48 +0000489 getCurFunction()->ObjCShouldCallSuper =
Jordan Rose2afd6612012-10-19 16:05:26 +0000490 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
Fariborz Jahaniand6876b22012-09-10 18:04:25 +0000491 }
Nico Weber1fb82662011-08-28 22:35:17 +0000492 }
Nico Weber715abaf2011-08-22 17:25:57 +0000493 }
Chris Lattnerda463fe2007-12-12 07:09:47 +0000494}
495
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000496namespace {
497
498// Callback to only accept typo corrections that are Objective-C classes.
499// If an ObjCInterfaceDecl* is given to the constructor, then the validation
500// function will reject corrections to that class.
501class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback {
502 public:
Craig Topperc3ec1492014-05-26 06:22:03 +0000503 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000504 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
505 : CurrentIDecl(IDecl) {}
506
Craig Toppere14c0f82014-03-12 04:55:44 +0000507 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000508 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
509 return ID && !declaresSameEntity(ID, CurrentIDecl);
510 }
511
512 private:
513 ObjCInterfaceDecl *CurrentIDecl;
514};
515
Hans Wennborgdcfba332015-10-06 23:40:43 +0000516} // end anonymous namespace
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000517
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +0000518static void diagnoseUseOfProtocols(Sema &TheSema,
519 ObjCContainerDecl *CD,
520 ObjCProtocolDecl *const *ProtoRefs,
521 unsigned NumProtoRefs,
522 const SourceLocation *ProtoLocs) {
523 assert(ProtoRefs);
524 // Diagnose availability in the context of the ObjC container.
525 Sema::ContextRAII SavedContext(TheSema, CD);
526 for (unsigned i = 0; i < NumProtoRefs; ++i) {
Alex Lorenzcdd596f2017-07-07 09:15:29 +0000527 (void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i],
528 /*UnknownObjCClass=*/nullptr,
529 /*ObjCPropertyAccess=*/false,
530 /*AvoidPartialAvailabilityChecks=*/true);
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +0000531 }
532}
533
Douglas Gregore9d95f12015-07-07 03:57:35 +0000534void Sema::
535ActOnSuperClassOfClassInterface(Scope *S,
536 SourceLocation AtInterfaceLoc,
537 ObjCInterfaceDecl *IDecl,
538 IdentifierInfo *ClassName,
539 SourceLocation ClassLoc,
540 IdentifierInfo *SuperName,
541 SourceLocation SuperLoc,
542 ArrayRef<ParsedType> SuperTypeArgs,
543 SourceRange SuperTypeArgsRange) {
544 // Check if a different kind of symbol declared in this scope.
545 NamedDecl *PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
546 LookupOrdinaryName);
547
548 if (!PrevDecl) {
549 // Try to correct for a typo in the superclass name without correcting
550 // to the class we're defining.
551 if (TypoCorrection Corrected = CorrectTypo(
552 DeclarationNameInfo(SuperName, SuperLoc),
553 LookupOrdinaryName, TUScope,
Hans Wennborgdcfba332015-10-06 23:40:43 +0000554 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(IDecl),
Douglas Gregore9d95f12015-07-07 03:57:35 +0000555 CTK_ErrorRecovery)) {
556 diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
557 << SuperName << ClassName);
558 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
559 }
560 }
561
562 if (declaresSameEntity(PrevDecl, IDecl)) {
563 Diag(SuperLoc, diag::err_recursive_superclass)
564 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
565 IDecl->setEndOfDefinitionLoc(ClassLoc);
566 } else {
567 ObjCInterfaceDecl *SuperClassDecl =
568 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
569 QualType SuperClassType;
570
571 // Diagnose classes that inherit from deprecated classes.
572 if (SuperClassDecl) {
573 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
574 SuperClassType = Context.getObjCInterfaceType(SuperClassDecl);
575 }
576
Hans Wennborgdcfba332015-10-06 23:40:43 +0000577 if (PrevDecl && !SuperClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +0000578 // The previous declaration was not a class decl. Check if we have a
579 // typedef. If we do, get the underlying class type.
580 if (const TypedefNameDecl *TDecl =
581 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
582 QualType T = TDecl->getUnderlyingType();
583 if (T->isObjCObjectType()) {
584 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
585 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
586 SuperClassType = Context.getTypeDeclType(TDecl);
587
588 // This handles the following case:
589 // @interface NewI @end
590 // typedef NewI DeprI __attribute__((deprecated("blah")))
591 // @interface SI : DeprI /* warn here */ @end
592 (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
593 }
594 }
595 }
596
597 // This handles the following case:
598 //
599 // typedef int SuperClass;
600 // @interface MyClass : SuperClass {} @end
601 //
602 if (!SuperClassDecl) {
603 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
604 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
605 }
606 }
607
608 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
609 if (!SuperClassDecl)
610 Diag(SuperLoc, diag::err_undef_superclass)
611 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
612 else if (RequireCompleteType(SuperLoc,
613 SuperClassType,
614 diag::err_forward_superclass,
615 SuperClassDecl->getDeclName(),
616 ClassName,
617 SourceRange(AtInterfaceLoc, ClassLoc))) {
Hans Wennborgdcfba332015-10-06 23:40:43 +0000618 SuperClassDecl = nullptr;
Douglas Gregore9d95f12015-07-07 03:57:35 +0000619 SuperClassType = QualType();
620 }
621 }
622
623 if (SuperClassType.isNull()) {
624 assert(!SuperClassDecl && "Failed to set SuperClassType?");
625 return;
626 }
627
628 // Handle type arguments on the superclass.
629 TypeSourceInfo *SuperClassTInfo = nullptr;
Fangrui Song6907ce22018-07-30 19:24:48 +0000630 if (!SuperTypeArgs.empty()) {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000631 TypeResult fullSuperClassType = actOnObjCTypeArgsAndProtocolQualifiers(
632 S,
633 SuperLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +0000634 CreateParsedType(SuperClassType,
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000635 nullptr),
636 SuperTypeArgsRange.getBegin(),
637 SuperTypeArgs,
638 SuperTypeArgsRange.getEnd(),
639 SourceLocation(),
640 { },
641 { },
642 SourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +0000643 if (!fullSuperClassType.isUsable())
644 return;
645
Fangrui Song6907ce22018-07-30 19:24:48 +0000646 SuperClassType = GetTypeFromParser(fullSuperClassType.get(),
Douglas Gregore9d95f12015-07-07 03:57:35 +0000647 &SuperClassTInfo);
648 }
649
650 if (!SuperClassTInfo) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000651 SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType,
Douglas Gregore9d95f12015-07-07 03:57:35 +0000652 SuperLoc);
653 }
654
655 IDecl->setSuperClass(SuperClassTInfo);
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000656 IDecl->setEndOfDefinitionLoc(SuperClassTInfo->getTypeLoc().getEndLoc());
Douglas Gregore9d95f12015-07-07 03:57:35 +0000657 }
658}
659
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000660DeclResult Sema::actOnObjCTypeParam(Scope *S,
661 ObjCTypeParamVariance variance,
662 SourceLocation varianceLoc,
663 unsigned index,
Douglas Gregore83b9562015-07-07 03:57:53 +0000664 IdentifierInfo *paramName,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000665 SourceLocation paramLoc,
666 SourceLocation colonLoc,
667 ParsedType parsedTypeBound) {
668 // If there was an explicitly-provided type bound, check it.
669 TypeSourceInfo *typeBoundInfo = nullptr;
670 if (parsedTypeBound) {
671 // The type bound can be any Objective-C pointer type.
672 QualType typeBound = GetTypeFromParser(parsedTypeBound, &typeBoundInfo);
673 if (typeBound->isObjCObjectPointerType()) {
674 // okay
675 } else if (typeBound->isObjCObjectType()) {
676 // The user forgot the * on an Objective-C pointer type, e.g.,
677 // "T : NSView".
Craig Topper07fa1762015-11-15 02:31:46 +0000678 SourceLocation starLoc = getLocForEndOfToken(
Douglas Gregor85f3f952015-07-07 03:57:15 +0000679 typeBoundInfo->getTypeLoc().getEndLoc());
680 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
681 diag::err_objc_type_param_bound_missing_pointer)
682 << typeBound << paramName
683 << FixItHint::CreateInsertion(starLoc, " *");
684
685 // Create a new type location builder so we can update the type
686 // location information we have.
687 TypeLocBuilder builder;
688 builder.pushFullCopy(typeBoundInfo->getTypeLoc());
689
690 // Create the Objective-C pointer type.
691 typeBound = Context.getObjCObjectPointerType(typeBound);
692 ObjCObjectPointerTypeLoc newT
693 = builder.push<ObjCObjectPointerTypeLoc>(typeBound);
694 newT.setStarLoc(starLoc);
695
696 // Form the new type source information.
697 typeBoundInfo = builder.getTypeSourceInfo(Context, typeBound);
698 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +0000699 // Not a valid type bound.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000700 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
701 diag::err_objc_type_param_bound_nonobject)
702 << typeBound << paramName;
703
704 // Forget the bound; we'll default to id later.
705 typeBoundInfo = nullptr;
706 }
Douglas Gregore83b9562015-07-07 03:57:53 +0000707
John McCall69975252015-09-23 22:14:21 +0000708 // Type bounds cannot have qualifiers (even indirectly) or explicit
709 // nullability.
Douglas Gregore83b9562015-07-07 03:57:53 +0000710 if (typeBoundInfo) {
John McCall69975252015-09-23 22:14:21 +0000711 QualType typeBound = typeBoundInfo->getType();
712 TypeLoc qual = typeBoundInfo->getTypeLoc().findExplicitQualifierLoc();
713 if (qual || typeBound.hasQualifiers()) {
714 bool diagnosed = false;
715 SourceRange rangeToRemove;
716 if (qual) {
717 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
718 rangeToRemove = attr.getLocalSourceRange();
719 if (attr.getTypePtr()->getImmediateNullability()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000720 Diag(attr.getBeginLoc(),
John McCall69975252015-09-23 22:14:21 +0000721 diag::err_objc_type_param_bound_explicit_nullability)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000722 << paramName << typeBound
723 << FixItHint::CreateRemoval(rangeToRemove);
John McCall69975252015-09-23 22:14:21 +0000724 diagnosed = true;
725 }
726 }
727 }
728
729 if (!diagnosed) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000730 Diag(qual ? qual.getBeginLoc()
731 : typeBoundInfo->getTypeLoc().getBeginLoc(),
732 diag::err_objc_type_param_bound_qualified)
733 << paramName << typeBound
734 << typeBound.getQualifiers().getAsString()
735 << FixItHint::CreateRemoval(rangeToRemove);
John McCall69975252015-09-23 22:14:21 +0000736 }
737
738 // If the type bound has qualifiers other than CVR, we need to strip
739 // them or we'll probably assert later when trying to apply new
740 // qualifiers.
741 Qualifiers quals = typeBound.getQualifiers();
742 quals.removeCVRQualifiers();
743 if (!quals.empty()) {
744 typeBoundInfo =
745 Context.getTrivialTypeSourceInfo(typeBound.getUnqualifiedType());
746 }
Douglas Gregore83b9562015-07-07 03:57:53 +0000747 }
748 }
Douglas Gregor85f3f952015-07-07 03:57:15 +0000749 }
750
751 // If there was no explicit type bound (or we removed it due to an error),
752 // use 'id' instead.
753 if (!typeBoundInfo) {
754 colonLoc = SourceLocation();
755 typeBoundInfo = Context.getTrivialTypeSourceInfo(Context.getObjCIdType());
756 }
757
758 // Create the type parameter.
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000759 return ObjCTypeParamDecl::Create(Context, CurContext, variance, varianceLoc,
760 index, paramLoc, paramName, colonLoc,
761 typeBoundInfo);
Douglas Gregor85f3f952015-07-07 03:57:15 +0000762}
763
764ObjCTypeParamList *Sema::actOnObjCTypeParamList(Scope *S,
765 SourceLocation lAngleLoc,
766 ArrayRef<Decl *> typeParamsIn,
767 SourceLocation rAngleLoc) {
768 // We know that the array only contains Objective-C type parameters.
769 ArrayRef<ObjCTypeParamDecl *>
770 typeParams(
771 reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()),
772 typeParamsIn.size());
773
774 // Diagnose redeclarations of type parameters.
775 // We do this now because Objective-C type parameters aren't pushed into
776 // scope until later (after the instance variable block), but we want the
777 // diagnostics to occur right after we parse the type parameter list.
778 llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams;
779 for (auto typeParam : typeParams) {
780 auto known = knownParams.find(typeParam->getIdentifier());
781 if (known != knownParams.end()) {
782 Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl)
783 << typeParam->getIdentifier()
784 << SourceRange(known->second->getLocation());
785
786 typeParam->setInvalidDecl();
787 } else {
788 knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam));
789
790 // Push the type parameter into scope.
791 PushOnScopeChains(typeParam, S, /*AddToContext=*/false);
792 }
793 }
794
795 // Create the parameter list.
796 return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc);
797}
798
799void Sema::popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList) {
800 for (auto typeParam : *typeParamList) {
801 if (!typeParam->isInvalidDecl()) {
802 S->RemoveDecl(typeParam);
803 IdResolver.RemoveDecl(typeParam);
804 }
805 }
806}
807
808namespace {
809 /// The context in which an Objective-C type parameter list occurs, for use
810 /// in diagnostics.
811 enum class TypeParamListContext {
812 ForwardDeclaration,
813 Definition,
814 Category,
815 Extension
816 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000817} // end anonymous namespace
Douglas Gregor85f3f952015-07-07 03:57:15 +0000818
819/// Check consistency between two Objective-C type parameter lists, e.g.,
NAKAMURA Takumi4c3ab452015-07-08 02:35:56 +0000820/// between a category/extension and an \@interface or between an \@class and an
821/// \@interface.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000822static bool checkTypeParamListConsistency(Sema &S,
823 ObjCTypeParamList *prevTypeParams,
824 ObjCTypeParamList *newTypeParams,
825 TypeParamListContext newContext) {
826 // If the sizes don't match, complain about that.
827 if (prevTypeParams->size() != newTypeParams->size()) {
828 SourceLocation diagLoc;
829 if (newTypeParams->size() > prevTypeParams->size()) {
830 diagLoc = newTypeParams->begin()[prevTypeParams->size()]->getLocation();
831 } else {
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000832 diagLoc = S.getLocForEndOfToken(newTypeParams->back()->getEndLoc());
Douglas Gregor85f3f952015-07-07 03:57:15 +0000833 }
834
835 S.Diag(diagLoc, diag::err_objc_type_param_arity_mismatch)
836 << static_cast<unsigned>(newContext)
837 << (newTypeParams->size() > prevTypeParams->size())
838 << prevTypeParams->size()
839 << newTypeParams->size();
840
841 return true;
842 }
843
844 // Match up the type parameters.
845 for (unsigned i = 0, n = prevTypeParams->size(); i != n; ++i) {
846 ObjCTypeParamDecl *prevTypeParam = prevTypeParams->begin()[i];
847 ObjCTypeParamDecl *newTypeParam = newTypeParams->begin()[i];
848
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000849 // Check for consistency of the variance.
850 if (newTypeParam->getVariance() != prevTypeParam->getVariance()) {
851 if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant &&
852 newContext != TypeParamListContext::Definition) {
853 // When the new type parameter is invariant and is not part
854 // of the definition, just propagate the variance.
855 newTypeParam->setVariance(prevTypeParam->getVariance());
Fangrui Song6907ce22018-07-30 19:24:48 +0000856 } else if (prevTypeParam->getVariance()
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000857 == ObjCTypeParamVariance::Invariant &&
858 !(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) &&
859 cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext())
860 ->getDefinition() == prevTypeParam->getDeclContext())) {
861 // When the old parameter is invariant and was not part of the
862 // definition, just ignore the difference because it doesn't
863 // matter.
864 } else {
865 {
866 // Diagnose the conflict and update the second declaration.
867 SourceLocation diagLoc = newTypeParam->getVarianceLoc();
868 if (diagLoc.isInvalid())
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000869 diagLoc = newTypeParam->getBeginLoc();
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000870
871 auto diag = S.Diag(diagLoc,
872 diag::err_objc_type_param_variance_conflict)
873 << static_cast<unsigned>(newTypeParam->getVariance())
874 << newTypeParam->getDeclName()
875 << static_cast<unsigned>(prevTypeParam->getVariance())
876 << prevTypeParam->getDeclName();
877 switch (prevTypeParam->getVariance()) {
878 case ObjCTypeParamVariance::Invariant:
879 diag << FixItHint::CreateRemoval(newTypeParam->getVarianceLoc());
880 break;
881
882 case ObjCTypeParamVariance::Covariant:
883 case ObjCTypeParamVariance::Contravariant: {
884 StringRef newVarianceStr
885 = prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant
886 ? "__covariant"
887 : "__contravariant";
888 if (newTypeParam->getVariance()
889 == ObjCTypeParamVariance::Invariant) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000890 diag << FixItHint::CreateInsertion(newTypeParam->getBeginLoc(),
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000891 (newVarianceStr + " ").str());
892 } else {
893 diag << FixItHint::CreateReplacement(newTypeParam->getVarianceLoc(),
894 newVarianceStr);
895 }
896 }
897 }
898 }
899
900 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
901 << prevTypeParam->getDeclName();
902
903 // Override the variance.
904 newTypeParam->setVariance(prevTypeParam->getVariance());
905 }
906 }
907
Douglas Gregor85f3f952015-07-07 03:57:15 +0000908 // If the bound types match, there's nothing to do.
909 if (S.Context.hasSameType(prevTypeParam->getUnderlyingType(),
910 newTypeParam->getUnderlyingType()))
911 continue;
912
913 // If the new type parameter's bound was explicit, complain about it being
914 // different from the original.
915 if (newTypeParam->hasExplicitBound()) {
916 SourceRange newBoundRange = newTypeParam->getTypeSourceInfo()
917 ->getTypeLoc().getSourceRange();
918 S.Diag(newBoundRange.getBegin(), diag::err_objc_type_param_bound_conflict)
919 << newTypeParam->getUnderlyingType()
920 << newTypeParam->getDeclName()
921 << prevTypeParam->hasExplicitBound()
922 << prevTypeParam->getUnderlyingType()
923 << (newTypeParam->getDeclName() == prevTypeParam->getDeclName())
924 << prevTypeParam->getDeclName()
925 << FixItHint::CreateReplacement(
926 newBoundRange,
927 prevTypeParam->getUnderlyingType().getAsString(
928 S.Context.getPrintingPolicy()));
929
930 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
931 << prevTypeParam->getDeclName();
932
933 // Override the new type parameter's bound type with the previous type,
934 // so that it's consistent.
935 newTypeParam->setTypeSourceInfo(
936 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
937 continue;
938 }
939
940 // The new type parameter got the implicit bound of 'id'. That's okay for
941 // categories and extensions (overwrite it later), but not for forward
942 // declarations and @interfaces, because those must be standalone.
943 if (newContext == TypeParamListContext::ForwardDeclaration ||
944 newContext == TypeParamListContext::Definition) {
945 // Diagnose this problem for forward declarations and definitions.
946 SourceLocation insertionLoc
Craig Topper07fa1762015-11-15 02:31:46 +0000947 = S.getLocForEndOfToken(newTypeParam->getLocation());
Douglas Gregor85f3f952015-07-07 03:57:15 +0000948 std::string newCode
949 = " : " + prevTypeParam->getUnderlyingType().getAsString(
950 S.Context.getPrintingPolicy());
951 S.Diag(newTypeParam->getLocation(),
952 diag::err_objc_type_param_bound_missing)
953 << prevTypeParam->getUnderlyingType()
954 << newTypeParam->getDeclName()
955 << (newContext == TypeParamListContext::ForwardDeclaration)
956 << FixItHint::CreateInsertion(insertionLoc, newCode);
957
958 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
959 << prevTypeParam->getDeclName();
960 }
961
962 // Update the new type parameter's bound to match the previous one.
963 newTypeParam->setTypeSourceInfo(
964 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
965 }
966
967 return false;
968}
969
Erich Keanec480f302018-07-12 21:09:05 +0000970Decl *Sema::ActOnStartClassInterface(
971 Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
972 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
973 IdentifierInfo *SuperName, SourceLocation SuperLoc,
974 ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
975 Decl *const *ProtoRefs, unsigned NumProtoRefs,
976 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
977 const ParsedAttributesView &AttrList) {
Chris Lattnerda463fe2007-12-12 07:09:47 +0000978 assert(ClassName && "Missing class identifier");
Mike Stump11289f42009-09-09 15:08:12 +0000979
Chris Lattnerda463fe2007-12-12 07:09:47 +0000980 // Check for another declaration kind with the same name.
Richard Smithbecb92d2017-10-10 22:33:17 +0000981 NamedDecl *PrevDecl =
982 LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
983 forRedeclarationInCurContext());
Douglas Gregor5101c242008-12-05 18:15:24 +0000984
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000985 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +0000986 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Chris Lattner0369c572008-11-23 23:12:31 +0000987 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +0000988 }
Mike Stump11289f42009-09-09 15:08:12 +0000989
Douglas Gregordc9166c2011-12-15 20:29:51 +0000990 // Create a declaration to describe this @interface.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +0000991 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidisdd710632013-06-18 21:26:33 +0000992
993 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
994 // A previous decl with a different name is because of
995 // @compatibility_alias, for example:
996 // \code
997 // @class NewImage;
998 // @compatibility_alias OldImage NewImage;
999 // \endcode
1000 // A lookup for 'OldImage' will return the 'NewImage' decl.
1001 //
1002 // In such a case use the real declaration name, instead of the alias one,
1003 // otherwise we will break IdentifierResolver and redecls-chain invariants.
1004 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
1005 // has been aliased.
1006 ClassName = PrevIDecl->getIdentifier();
1007 }
1008
Douglas Gregor85f3f952015-07-07 03:57:15 +00001009 // If there was a forward declaration with type parameters, check
1010 // for consistency.
1011 if (PrevIDecl) {
1012 if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) {
1013 if (typeParamList) {
1014 // Both have type parameter lists; check for consistency.
Fangrui Song6907ce22018-07-30 19:24:48 +00001015 if (checkTypeParamListConsistency(*this, prevTypeParamList,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001016 typeParamList,
1017 TypeParamListContext::Definition)) {
1018 typeParamList = nullptr;
1019 }
1020 } else {
1021 Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first)
1022 << ClassName;
1023 Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl)
1024 << ClassName;
1025
1026 // Clone the type parameter list.
1027 SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams;
1028 for (auto typeParam : *prevTypeParamList) {
1029 clonedTypeParams.push_back(
1030 ObjCTypeParamDecl::Create(
1031 Context,
1032 CurContext,
Douglas Gregor1ac1b632015-07-07 03:58:54 +00001033 typeParam->getVariance(),
1034 SourceLocation(),
Douglas Gregore83b9562015-07-07 03:57:53 +00001035 typeParam->getIndex(),
Douglas Gregor85f3f952015-07-07 03:57:15 +00001036 SourceLocation(),
1037 typeParam->getIdentifier(),
1038 SourceLocation(),
1039 Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType())));
1040 }
1041
Fangrui Song6907ce22018-07-30 19:24:48 +00001042 typeParamList = ObjCTypeParamList::create(Context,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001043 SourceLocation(),
1044 clonedTypeParams,
1045 SourceLocation());
1046 }
1047 }
1048 }
1049
Douglas Gregordc9166c2011-12-15 20:29:51 +00001050 ObjCInterfaceDecl *IDecl
1051 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001052 typeParamList, PrevIDecl, ClassLoc);
Douglas Gregordc9166c2011-12-15 20:29:51 +00001053 if (PrevIDecl) {
1054 // Class already seen. Was it a definition?
1055 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
1056 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
1057 << PrevIDecl->getDeclName();
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001058 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregordc9166c2011-12-15 20:29:51 +00001059 IDecl->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00001060 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001061 }
Erich Keanec480f302018-07-12 21:09:05 +00001062
1063 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001064 AddPragmaAttributes(TUScope, IDecl);
Douglas Gregordc9166c2011-12-15 20:29:51 +00001065 PushOnScopeChains(IDecl, TUScope);
Mike Stump11289f42009-09-09 15:08:12 +00001066
Fangrui Song6907ce22018-07-30 19:24:48 +00001067 // Start the definition of this class. If we're in a redefinition case, there
Douglas Gregordc9166c2011-12-15 20:29:51 +00001068 // may already be a definition, so we'll end up adding to it.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001069 if (!IDecl->hasDefinition())
1070 IDecl->startDefinition();
Fangrui Song6907ce22018-07-30 19:24:48 +00001071
Chris Lattnerda463fe2007-12-12 07:09:47 +00001072 if (SuperName) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001073 // Diagnose availability in the context of the @interface.
1074 ContextRAII SavedContext(*this, IDecl);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001075
Fangrui Song6907ce22018-07-30 19:24:48 +00001076 ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl,
1077 ClassName, ClassLoc,
1078 SuperName, SuperLoc, SuperTypeArgs,
Douglas Gregore9d95f12015-07-07 03:57:35 +00001079 SuperTypeArgsRange);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001080 } else { // we have a root class.
Douglas Gregor16408322011-12-15 22:34:59 +00001081 IDecl->setEndOfDefinitionLoc(ClassLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001082 }
Mike Stump11289f42009-09-09 15:08:12 +00001083
Sebastian Redle7c1fe62010-08-13 00:28:03 +00001084 // Check then save referenced protocols.
Chris Lattnerdf59f5a2008-07-26 04:13:19 +00001085 if (NumProtoRefs) {
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001086 diagnoseUseOfProtocols(*this, IDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1087 NumProtoRefs, ProtoLocs);
Roman Divackye6377112012-09-06 15:59:27 +00001088 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001089 ProtoLocs, Context);
Douglas Gregor16408322011-12-15 22:34:59 +00001090 IDecl->setEndOfDefinitionLoc(EndProtoLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001091 }
Mike Stump11289f42009-09-09 15:08:12 +00001092
Anders Carlssona6b508a2008-11-04 16:57:32 +00001093 CheckObjCDeclScope(IDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001094 return ActOnObjCContainerStartDefinition(IDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001095}
1096
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001097/// ActOnTypedefedProtocols - this action finds protocol list as part of the
1098/// typedef'ed use for a qualified super class and adds them to the list
1099/// of the protocols.
1100void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
Argyrios Kyrtzidisf95a0002016-11-09 02:47:07 +00001101 SmallVectorImpl<SourceLocation> &ProtocolLocs,
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001102 IdentifierInfo *SuperName,
1103 SourceLocation SuperLoc) {
1104 if (!SuperName)
1105 return;
1106 NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
1107 LookupOrdinaryName);
1108 if (!IDecl)
1109 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001110
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001111 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
1112 QualType T = TDecl->getUnderlyingType();
1113 if (T->isObjCObjectType())
Argyrios Kyrtzidisf95a0002016-11-09 02:47:07 +00001114 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>()) {
Benjamin Kramerf9890422015-02-17 16:48:30 +00001115 ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
Argyrios Kyrtzidisf95a0002016-11-09 02:47:07 +00001116 // FIXME: Consider whether this should be an invalid loc since the loc
1117 // is not actually pointing to a protocol name reference but to the
1118 // typedef reference. Note that the base class name loc is also pointing
1119 // at the typedef.
1120 ProtocolLocs.append(OPT->getNumProtocols(), SuperLoc);
1121 }
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001122 }
1123}
1124
Richard Smithac4e36d2012-08-08 23:32:13 +00001125/// ActOnCompatibilityAlias - this action is called after complete parsing of
James Dennett634962f2012-06-14 21:40:34 +00001126/// a \@compatibility_alias declaration. It sets up the alias relationships.
Richard Smithac4e36d2012-08-08 23:32:13 +00001127Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
1128 IdentifierInfo *AliasName,
1129 SourceLocation AliasLocation,
1130 IdentifierInfo *ClassName,
1131 SourceLocation ClassLocation) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00001132 // Look for previous declaration of alias name
Richard Smithbecb92d2017-10-10 22:33:17 +00001133 NamedDecl *ADecl =
1134 LookupSingleName(TUScope, AliasName, AliasLocation, LookupOrdinaryName,
1135 forRedeclarationInCurContext());
Chris Lattnerda463fe2007-12-12 07:09:47 +00001136 if (ADecl) {
Eli Friedmanfd6b3f82013-06-21 01:49:53 +00001137 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
Chris Lattnerd0685032008-11-23 23:20:13 +00001138 Diag(ADecl->getLocation(), diag::note_previous_declaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001139 return nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001140 }
1141 // Check for class declaration
Richard Smithbecb92d2017-10-10 22:33:17 +00001142 NamedDecl *CDeclU =
1143 LookupSingleName(TUScope, ClassName, ClassLocation, LookupOrdinaryName,
1144 forRedeclarationInCurContext());
Richard Smithdda56e42011-04-15 14:24:37 +00001145 if (const TypedefNameDecl *TDecl =
1146 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001147 QualType T = TDecl->getUnderlyingType();
John McCall8b07ec22010-05-15 11:32:37 +00001148 if (T->isObjCObjectType()) {
1149 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001150 ClassName = IDecl->getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001151 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
Richard Smithbecb92d2017-10-10 22:33:17 +00001152 LookupOrdinaryName,
1153 forRedeclarationInCurContext());
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001154 }
1155 }
1156 }
Chris Lattner219b3e92008-03-16 21:17:37 +00001157 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
Craig Topperc3ec1492014-05-26 06:22:03 +00001158 if (!CDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001159 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
Chris Lattner219b3e92008-03-16 21:17:37 +00001160 if (CDeclU)
Chris Lattnerd0685032008-11-23 23:20:13 +00001161 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001162 return nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001163 }
Mike Stump11289f42009-09-09 15:08:12 +00001164
Chris Lattner219b3e92008-03-16 21:17:37 +00001165 // Everything checked out, instantiate a new alias declaration AST.
Mike Stump11289f42009-09-09 15:08:12 +00001166 ObjCCompatibleAliasDecl *AliasDecl =
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001167 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001168
Anders Carlssona6b508a2008-11-04 16:57:32 +00001169 if (!CheckObjCDeclScope(AliasDecl))
Douglas Gregor38feed82009-04-24 02:57:34 +00001170 PushOnScopeChains(AliasDecl, TUScope);
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001171
John McCall48871652010-08-21 09:40:31 +00001172 return AliasDecl;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001173}
1174
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001175bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
Steve Naroff41d09ad2009-03-05 15:22:01 +00001176 IdentifierInfo *PName,
1177 SourceLocation &Ploc, SourceLocation PrevLoc,
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001178 const ObjCList<ObjCProtocolDecl> &PList) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001179
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001180 bool res = false;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001181 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
1182 E = PList.end(); I != E; ++I) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001183 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
1184 Ploc)) {
Steve Naroff41d09ad2009-03-05 15:22:01 +00001185 if (PDecl->getIdentifier() == PName) {
1186 Diag(Ploc, diag::err_protocol_has_circular_dependency);
1187 Diag(PrevLoc, diag::note_previous_definition);
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001188 res = true;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001189 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001190
Douglas Gregore6e48b12012-01-01 19:29:29 +00001191 if (!PDecl->hasDefinition())
1192 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00001193
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001194 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
1195 PDecl->getLocation(), PDecl->getReferencedProtocols()))
1196 res = true;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001197 }
1198 }
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001199 return res;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001200}
1201
Erich Keanec480f302018-07-12 21:09:05 +00001202Decl *Sema::ActOnStartProtocolInterface(
1203 SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
1204 SourceLocation ProtocolLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs,
1205 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
1206 const ParsedAttributesView &AttrList) {
Fariborz Jahaniancadf7c52011-05-12 22:04:39 +00001207 bool err = false;
Daniel Dunbar26e2ab42008-09-26 04:48:09 +00001208 // FIXME: Deal with AttrList.
Chris Lattnerda463fe2007-12-12 07:09:47 +00001209 assert(ProtocolName && "Missing protocol identifier");
Douglas Gregor32c17572012-01-01 20:30:41 +00001210 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
Richard Smithbecb92d2017-10-10 22:33:17 +00001211 forRedeclarationInCurContext());
Craig Topperc3ec1492014-05-26 06:22:03 +00001212 ObjCProtocolDecl *PDecl = nullptr;
1213 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
Douglas Gregor32c17572012-01-01 20:30:41 +00001214 // If we already have a definition, complain.
1215 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
1216 Diag(Def->getLocation(), diag::note_previous_definition);
Mike Stump11289f42009-09-09 15:08:12 +00001217
Douglas Gregor32c17572012-01-01 20:30:41 +00001218 // Create a new protocol that is completely distinct from previous
1219 // declarations, and do not make this protocol available for name lookup.
1220 // That way, we'll end up completely ignoring the duplicate.
1221 // FIXME: Can we turn this into an error?
1222 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
1223 ProtocolLoc, AtProtoInterfaceLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +00001224 /*PrevDecl=*/nullptr);
Bruno Cardoso Lopes7dcf23e2018-06-30 00:49:27 +00001225
1226 // If we are using modules, add the decl to the context in order to
1227 // serialize something meaningful.
1228 if (getLangOpts().Modules)
1229 PushOnScopeChains(PDecl, TUScope);
Douglas Gregor32c17572012-01-01 20:30:41 +00001230 PDecl->startDefinition();
1231 } else {
1232 if (PrevDecl) {
1233 // Check for circular dependencies among protocol declarations. This can
1234 // only happen if this protocol was forward-declared.
Argyrios Kyrtzidis95dfc122011-11-13 22:08:30 +00001235 ObjCList<ObjCProtocolDecl> PList;
1236 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
1237 err = CheckForwardProtocolDeclarationForCircularDependency(
Douglas Gregor32c17572012-01-01 20:30:41 +00001238 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
Argyrios Kyrtzidis95dfc122011-11-13 22:08:30 +00001239 }
Douglas Gregor32c17572012-01-01 20:30:41 +00001240
1241 // Create the new declaration.
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001242 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
Argyrios Kyrtzidis1f4bee52011-10-17 19:48:06 +00001243 ProtocolLoc, AtProtoInterfaceLoc,
Douglas Gregor05a1f4d2012-01-01 22:06:18 +00001244 /*PrevDecl=*/PrevDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00001245
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001246 PushOnScopeChains(PDecl, TUScope);
Douglas Gregore6e48b12012-01-01 19:29:29 +00001247 PDecl->startDefinition();
Chris Lattnerf87ca0a2008-03-16 01:23:04 +00001248 }
Erich Keanec480f302018-07-12 21:09:05 +00001249
1250 ProcessDeclAttributeList(TUScope, PDecl, AttrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001251 AddPragmaAttributes(TUScope, PDecl);
1252
Douglas Gregor32c17572012-01-01 20:30:41 +00001253 // Merge attributes from previous declarations.
1254 if (PrevDecl)
1255 mergeDeclAttributes(PDecl, PrevDecl);
1256
Fariborz Jahaniancadf7c52011-05-12 22:04:39 +00001257 if (!err && NumProtoRefs ) {
Chris Lattneracc04a92008-03-16 20:19:15 +00001258 /// Check then save referenced protocols.
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001259 diagnoseUseOfProtocols(*this, PDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1260 NumProtoRefs, ProtoLocs);
Roman Divackye6377112012-09-06 15:59:27 +00001261 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001262 ProtoLocs, Context);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001263 }
Mike Stump11289f42009-09-09 15:08:12 +00001264
1265 CheckObjCDeclScope(PDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001266 return ActOnObjCContainerStartDefinition(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001267}
1268
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001269static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
1270 ObjCProtocolDecl *&UndefinedProtocol) {
1271 if (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()) {
1272 UndefinedProtocol = PDecl;
1273 return true;
1274 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001275
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001276 for (auto *PI : PDecl->protocols())
1277 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
1278 UndefinedProtocol = PI;
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001279 return true;
1280 }
1281 return false;
1282}
1283
Chris Lattnerda463fe2007-12-12 07:09:47 +00001284/// FindProtocolDeclaration - This routine looks up protocols and
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00001285/// issues an error if they are not declared. It returns list of
1286/// protocol declarations in its 'Protocols' argument.
Chris Lattnerda463fe2007-12-12 07:09:47 +00001287void
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001288Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
Craig Toppera9247eb2015-10-22 04:59:56 +00001289 ArrayRef<IdentifierLocPair> ProtocolId,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001290 SmallVectorImpl<Decl *> &Protocols) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001291 for (const IdentifierLocPair &Pair : ProtocolId) {
1292 ObjCProtocolDecl *PDecl = LookupProtocol(Pair.first, Pair.second);
Chris Lattner9c1842b2008-07-26 03:47:43 +00001293 if (!PDecl) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001294 TypoCorrection Corrected = CorrectTypo(
Craig Toppera9247eb2015-10-22 04:59:56 +00001295 DeclarationNameInfo(Pair.first, Pair.second),
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001296 LookupObjCProtocolName, TUScope, nullptr,
1297 llvm::make_unique<DeclFilterCCC<ObjCProtocolDecl>>(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001298 CTK_ErrorRecovery);
Richard Smithf9b15102013-08-17 00:46:16 +00001299 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
1300 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
Craig Toppera9247eb2015-10-22 04:59:56 +00001301 << Pair.first);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001302 }
1303
1304 if (!PDecl) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001305 Diag(Pair.second, diag::err_undeclared_protocol) << Pair.first;
Chris Lattner9c1842b2008-07-26 03:47:43 +00001306 continue;
1307 }
Fariborz Jahanianada44a22013-04-09 17:52:29 +00001308 // If this is a forward protocol declaration, get its definition.
1309 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
1310 PDecl = PDecl->getDefinition();
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001311
1312 // For an objc container, delay protocol reference checking until after we
1313 // can set the objc decl as the availability context, otherwise check now.
1314 if (!ForObjCContainer) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001315 (void)DiagnoseUseOfDecl(PDecl, Pair.second);
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001316 }
Chris Lattner9c1842b2008-07-26 03:47:43 +00001317
1318 // If this is a forward declaration and we are supposed to warn in this
1319 // case, do it.
Douglas Gregoreed49792013-01-17 00:38:46 +00001320 // FIXME: Recover nicely in the hidden case.
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001321 ObjCProtocolDecl *UndefinedProtocol;
Fangrui Song6907ce22018-07-30 19:24:48 +00001322
Douglas Gregoreed49792013-01-17 00:38:46 +00001323 if (WarnOnDeclarations &&
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001324 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001325 Diag(Pair.second, diag::warn_undef_protocolref) << Pair.first;
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001326 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
1327 << UndefinedProtocol;
1328 }
John McCall48871652010-08-21 09:40:31 +00001329 Protocols.push_back(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001330 }
1331}
1332
Benjamin Kramer8b851d02015-07-13 20:42:13 +00001333namespace {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001334// Callback to only accept typo corrections that are either
1335// Objective-C protocols or valid Objective-C type arguments.
1336class ObjCTypeArgOrProtocolValidatorCCC : public CorrectionCandidateCallback {
1337 ASTContext &Context;
1338 Sema::LookupNameKind LookupKind;
1339 public:
1340 ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context,
1341 Sema::LookupNameKind lookupKind)
1342 : Context(context), LookupKind(lookupKind) { }
1343
1344 bool ValidateCandidate(const TypoCorrection &candidate) override {
1345 // If we're allowed to find protocols and we have a protocol, accept it.
1346 if (LookupKind != Sema::LookupOrdinaryName) {
1347 if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>())
1348 return true;
1349 }
1350
1351 // If we're allowed to find type names and we have one, accept it.
1352 if (LookupKind != Sema::LookupObjCProtocolName) {
1353 // If we have a type declaration, we might accept this result.
1354 if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) {
1355 // If we found a tag declaration outside of C++, skip it. This
1356 // can happy because we look for any name when there is no
1357 // bias to protocol or type names.
1358 if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus)
1359 return false;
1360
1361 // Make sure the type is something we would accept as a type
1362 // argument.
1363 auto type = Context.getTypeDeclType(typeDecl);
1364 if (type->isObjCObjectPointerType() ||
1365 type->isBlockPointerType() ||
1366 type->isDependentType() ||
1367 type->isObjCObjectType())
1368 return true;
1369
1370 return false;
1371 }
1372
1373 // If we have an Objective-C class type, accept it; there will
1374 // be another fix to add the '*'.
1375 if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>())
1376 return true;
1377
1378 return false;
1379 }
1380
1381 return false;
1382 }
1383};
Benjamin Kramer8b851d02015-07-13 20:42:13 +00001384} // end anonymous namespace
Douglas Gregore9d95f12015-07-07 03:57:35 +00001385
Bruno Cardoso Lopesc54768f2016-04-13 20:59:07 +00001386void Sema::DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
1387 SourceLocation ProtocolLoc,
1388 IdentifierInfo *TypeArgId,
1389 SourceLocation TypeArgLoc,
1390 bool SelectProtocolFirst) {
1391 Diag(TypeArgLoc, diag::err_objc_type_args_and_protocols)
1392 << SelectProtocolFirst << TypeArgId << ProtocolId
1393 << SourceRange(ProtocolLoc);
1394}
1395
Douglas Gregore9d95f12015-07-07 03:57:35 +00001396void Sema::actOnObjCTypeArgsOrProtocolQualifiers(
1397 Scope *S,
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001398 ParsedType baseType,
Douglas Gregore9d95f12015-07-07 03:57:35 +00001399 SourceLocation lAngleLoc,
1400 ArrayRef<IdentifierInfo *> identifiers,
1401 ArrayRef<SourceLocation> identifierLocs,
1402 SourceLocation rAngleLoc,
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001403 SourceLocation &typeArgsLAngleLoc,
1404 SmallVectorImpl<ParsedType> &typeArgs,
1405 SourceLocation &typeArgsRAngleLoc,
1406 SourceLocation &protocolLAngleLoc,
1407 SmallVectorImpl<Decl *> &protocols,
1408 SourceLocation &protocolRAngleLoc,
Douglas Gregore9d95f12015-07-07 03:57:35 +00001409 bool warnOnIncompleteProtocols) {
1410 // Local function that updates the declaration specifiers with
1411 // protocol information.
Douglas Gregore9d95f12015-07-07 03:57:35 +00001412 unsigned numProtocolsResolved = 0;
1413 auto resolvedAsProtocols = [&] {
1414 assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols");
Fangrui Song6907ce22018-07-30 19:24:48 +00001415
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001416 // Determine whether the base type is a parameterized class, in
1417 // which case we want to warn about typos such as
1418 // "NSArray<NSObject>" (that should be NSArray<NSObject *>).
1419 ObjCInterfaceDecl *baseClass = nullptr;
1420 QualType base = GetTypeFromParser(baseType, nullptr);
1421 bool allAreTypeNames = false;
1422 SourceLocation firstClassNameLoc;
1423 if (!base.isNull()) {
1424 if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) {
1425 baseClass = objcObjectType->getInterface();
1426 if (baseClass) {
1427 if (auto typeParams = baseClass->getTypeParamList()) {
1428 if (typeParams->size() == numProtocolsResolved) {
1429 // Note that we should be looking for type names, too.
1430 allAreTypeNames = true;
1431 }
1432 }
1433 }
1434 }
1435 }
1436
Douglas Gregore9d95f12015-07-07 03:57:35 +00001437 for (unsigned i = 0, n = protocols.size(); i != n; ++i) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001438 ObjCProtocolDecl *&proto
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001439 = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001440 // For an objc container, delay protocol reference checking until after we
1441 // can set the objc decl as the availability context, otherwise check now.
1442 if (!warnOnIncompleteProtocols) {
1443 (void)DiagnoseUseOfDecl(proto, identifierLocs[i]);
1444 }
1445
1446 // If this is a forward protocol declaration, get its definition.
1447 if (!proto->isThisDeclarationADefinition() && proto->getDefinition())
1448 proto = proto->getDefinition();
1449
1450 // If this is a forward declaration and we are supposed to warn in this
1451 // case, do it.
1452 // FIXME: Recover nicely in the hidden case.
1453 ObjCProtocolDecl *forwardDecl = nullptr;
1454 if (warnOnIncompleteProtocols &&
1455 NestedProtocolHasNoDefinition(proto, forwardDecl)) {
1456 Diag(identifierLocs[i], diag::warn_undef_protocolref)
1457 << proto->getDeclName();
1458 Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined)
1459 << forwardDecl;
1460 }
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001461
1462 // If everything this far has been a type name (and we care
1463 // about such things), check whether this name refers to a type
1464 // as well.
1465 if (allAreTypeNames) {
1466 if (auto *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1467 LookupOrdinaryName)) {
1468 if (isa<ObjCInterfaceDecl>(decl)) {
1469 if (firstClassNameLoc.isInvalid())
1470 firstClassNameLoc = identifierLocs[i];
1471 } else if (!isa<TypeDecl>(decl)) {
1472 // Not a type.
1473 allAreTypeNames = false;
1474 }
1475 } else {
1476 allAreTypeNames = false;
1477 }
1478 }
1479 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001480
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001481 // All of the protocols listed also have type names, and at least
1482 // one is an Objective-C class name. Check whether all of the
1483 // protocol conformances are declared by the base class itself, in
1484 // which case we warn.
1485 if (allAreTypeNames && firstClassNameLoc.isValid()) {
1486 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> knownProtocols;
1487 Context.CollectInheritedProtocols(baseClass, knownProtocols);
1488 bool allProtocolsDeclared = true;
1489 for (auto proto : protocols) {
1490 if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) {
1491 allProtocolsDeclared = false;
1492 break;
1493 }
1494 }
1495
1496 if (allProtocolsDeclared) {
1497 Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type)
1498 << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc)
Craig Topper07fa1762015-11-15 02:31:46 +00001499 << FixItHint::CreateInsertion(getLocForEndOfToken(firstClassNameLoc),
1500 " *");
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001501 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00001502 }
1503
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001504 protocolLAngleLoc = lAngleLoc;
1505 protocolRAngleLoc = rAngleLoc;
1506 assert(protocols.size() == identifierLocs.size());
Douglas Gregore9d95f12015-07-07 03:57:35 +00001507 };
1508
1509 // Attempt to resolve all of the identifiers as protocols.
1510 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1511 ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]);
1512 protocols.push_back(proto);
1513 if (proto)
1514 ++numProtocolsResolved;
1515 }
1516
1517 // If all of the names were protocols, these were protocol qualifiers.
1518 if (numProtocolsResolved == identifiers.size())
1519 return resolvedAsProtocols();
1520
1521 // Attempt to resolve all of the identifiers as type names or
1522 // Objective-C class names. The latter is technically ill-formed,
1523 // but is probably something like \c NSArray<NSView *> missing the
1524 // \c*.
1525 typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl;
1526 SmallVector<TypeOrClassDecl, 4> typeDecls;
1527 unsigned numTypeDeclsResolved = 0;
1528 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1529 NamedDecl *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1530 LookupOrdinaryName);
1531 if (!decl) {
1532 typeDecls.push_back(TypeOrClassDecl());
1533 continue;
1534 }
1535
1536 if (auto typeDecl = dyn_cast<TypeDecl>(decl)) {
1537 typeDecls.push_back(typeDecl);
1538 ++numTypeDeclsResolved;
1539 continue;
1540 }
1541
1542 if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) {
1543 typeDecls.push_back(objcClass);
1544 ++numTypeDeclsResolved;
1545 continue;
1546 }
1547
1548 typeDecls.push_back(TypeOrClassDecl());
1549 }
1550
1551 AttributeFactory attrFactory;
1552
1553 // Local function that forms a reference to the given type or
1554 // Objective-C class declaration.
Fangrui Song6907ce22018-07-30 19:24:48 +00001555 auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc)
Douglas Gregore9d95f12015-07-07 03:57:35 +00001556 -> TypeResult {
1557 // Form declaration specifiers. They simply refer to the type.
1558 DeclSpec DS(attrFactory);
1559 const char* prevSpec; // unused
1560 unsigned diagID; // unused
1561 QualType type;
1562 if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>())
1563 type = Context.getTypeDeclType(actualTypeDecl);
1564 else
1565 type = Context.getObjCInterfaceType(typeDecl.get<ObjCInterfaceDecl *>());
1566 TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc);
1567 ParsedType parsedType = CreateParsedType(type, parsedTSInfo);
1568 DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID,
1569 parsedType, Context.getPrintingPolicy());
1570 // Use the identifier location for the type source range.
1571 DS.SetRangeStart(loc);
1572 DS.SetRangeEnd(loc);
1573
1574 // Form the declarator.
Faisal Vali421b2d12017-12-29 05:41:00 +00001575 Declarator D(DS, DeclaratorContext::TypeNameContext);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001576
1577 // If we have a typedef of an Objective-C class type that is missing a '*',
1578 // add the '*'.
1579 if (type->getAs<ObjCInterfaceType>()) {
Craig Topper07fa1762015-11-15 02:31:46 +00001580 SourceLocation starLoc = getLocForEndOfToken(loc);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001581 D.AddTypeInfo(DeclaratorChunk::getPointer(/*typeQuals=*/0, starLoc,
1582 SourceLocation(),
1583 SourceLocation(),
1584 SourceLocation(),
Andrey Bokhanko45d41322016-05-11 18:38:21 +00001585 SourceLocation(),
Douglas Gregore9d95f12015-07-07 03:57:35 +00001586 SourceLocation()),
Hans Wennborgdcfba332015-10-06 23:40:43 +00001587 starLoc);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001588
1589 // Diagnose the missing '*'.
1590 Diag(loc, diag::err_objc_type_arg_missing_star)
1591 << type
1592 << FixItHint::CreateInsertion(starLoc, " *");
1593 }
1594
1595 // Convert this to a type.
1596 return ActOnTypeName(S, D);
1597 };
1598
1599 // Local function that updates the declaration specifiers with
1600 // type argument information.
1601 auto resolvedAsTypeDecls = [&] {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001602 // We did not resolve these as protocols.
1603 protocols.clear();
1604
Douglas Gregore9d95f12015-07-07 03:57:35 +00001605 assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl");
1606 // Map type declarations to type arguments.
Douglas Gregore9d95f12015-07-07 03:57:35 +00001607 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1608 // Map type reference to a type.
1609 TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]);
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001610 if (!type.isUsable()) {
1611 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001612 return;
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001613 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00001614
1615 typeArgs.push_back(type.get());
1616 }
1617
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001618 typeArgsLAngleLoc = lAngleLoc;
1619 typeArgsRAngleLoc = rAngleLoc;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001620 };
1621
1622 // If all of the identifiers can be resolved as type names or
1623 // Objective-C class names, we have type arguments.
1624 if (numTypeDeclsResolved == identifiers.size())
1625 return resolvedAsTypeDecls();
1626
1627 // Error recovery: some names weren't found, or we have a mix of
1628 // type and protocol names. Go resolve all of the unresolved names
1629 // and complain if we can't find a consistent answer.
1630 LookupNameKind lookupKind = LookupAnyName;
1631 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1632 // If we already have a protocol or type. Check whether it is the
1633 // right thing.
1634 if (protocols[i] || typeDecls[i]) {
1635 // If we haven't figured out whether we want types or protocols
1636 // yet, try to figure it out from this name.
1637 if (lookupKind == LookupAnyName) {
1638 // If this name refers to both a protocol and a type (e.g., \c
1639 // NSObject), don't conclude anything yet.
1640 if (protocols[i] && typeDecls[i])
1641 continue;
1642
1643 // Otherwise, let this name decide whether we'll be correcting
1644 // toward types or protocols.
1645 lookupKind = protocols[i] ? LookupObjCProtocolName
1646 : LookupOrdinaryName;
1647 continue;
1648 }
1649
1650 // If we want protocols and we have a protocol, there's nothing
1651 // more to do.
1652 if (lookupKind == LookupObjCProtocolName && protocols[i])
1653 continue;
1654
1655 // If we want types and we have a type declaration, there's
1656 // nothing more to do.
1657 if (lookupKind == LookupOrdinaryName && typeDecls[i])
1658 continue;
1659
1660 // We have a conflict: some names refer to protocols and others
1661 // refer to types.
Bruno Cardoso Lopesc54768f2016-04-13 20:59:07 +00001662 DiagnoseTypeArgsAndProtocols(identifiers[0], identifierLocs[0],
1663 identifiers[i], identifierLocs[i],
1664 protocols[i] != nullptr);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001665
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001666 protocols.clear();
1667 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001668 return;
1669 }
1670
1671 // Perform typo correction on the name.
1672 TypoCorrection corrected = CorrectTypo(
1673 DeclarationNameInfo(identifiers[i], identifierLocs[i]), lookupKind, S,
1674 nullptr,
1675 llvm::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(Context,
1676 lookupKind),
1677 CTK_ErrorRecovery);
1678 if (corrected) {
1679 // Did we find a protocol?
1680 if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) {
1681 diagnoseTypo(corrected,
1682 PDiag(diag::err_undeclared_protocol_suggest)
1683 << identifiers[i]);
1684 lookupKind = LookupObjCProtocolName;
1685 protocols[i] = proto;
1686 ++numProtocolsResolved;
1687 continue;
1688 }
1689
1690 // Did we find a type?
1691 if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) {
1692 diagnoseTypo(corrected,
1693 PDiag(diag::err_unknown_typename_suggest)
1694 << identifiers[i]);
1695 lookupKind = LookupOrdinaryName;
1696 typeDecls[i] = typeDecl;
1697 ++numTypeDeclsResolved;
1698 continue;
1699 }
1700
1701 // Did we find an Objective-C class?
1702 if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1703 diagnoseTypo(corrected,
1704 PDiag(diag::err_unknown_type_or_class_name_suggest)
1705 << identifiers[i] << true);
1706 lookupKind = LookupOrdinaryName;
1707 typeDecls[i] = objcClass;
1708 ++numTypeDeclsResolved;
1709 continue;
1710 }
1711 }
1712
1713 // We couldn't find anything.
1714 Diag(identifierLocs[i],
1715 (lookupKind == LookupAnyName ? diag::err_objc_type_arg_missing
1716 : lookupKind == LookupObjCProtocolName ? diag::err_undeclared_protocol
1717 : diag::err_unknown_typename))
1718 << identifiers[i];
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001719 protocols.clear();
1720 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001721 return;
1722 }
1723
1724 // If all of the names were (corrected to) protocols, these were
1725 // protocol qualifiers.
1726 if (numProtocolsResolved == identifiers.size())
1727 return resolvedAsProtocols();
1728
1729 // Otherwise, all of the names were (corrected to) types.
1730 assert(numTypeDeclsResolved == identifiers.size() && "Not all types?");
1731 return resolvedAsTypeDecls();
1732}
1733
Fariborz Jahanianabf63e7b2009-03-02 19:06:08 +00001734/// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001735/// a class method in its extension.
1736///
Mike Stump11289f42009-09-09 15:08:12 +00001737void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001738 ObjCInterfaceDecl *ID) {
1739 if (!ID)
1740 return; // Possibly due to previous error
1741
1742 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
Aaron Ballmanaff18c02014-03-13 19:03:34 +00001743 for (auto *MD : ID->methods())
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001744 MethodMap[MD->getSelector()] = MD;
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001745
1746 if (MethodMap.empty())
1747 return;
Aaron Ballmanaff18c02014-03-13 19:03:34 +00001748 for (const auto *Method : CAT->methods()) {
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001749 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
Fariborz Jahanian83d674e2014-03-17 17:46:10 +00001750 if (PrevMethod &&
1751 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
1752 !MatchTwoMethodDeclarations(Method, PrevMethod)) {
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001753 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1754 << Method->getDeclName();
1755 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1756 }
1757 }
1758}
1759
James Dennett634962f2012-06-14 21:40:34 +00001760/// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
Douglas Gregorf6102672012-01-01 21:23:57 +00001761Sema::DeclGroupPtrTy
Chris Lattnerda463fe2007-12-12 07:09:47 +00001762Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
Craig Topper0f723bb2015-10-22 05:00:01 +00001763 ArrayRef<IdentifierLocPair> IdentList,
Erich Keanec480f302018-07-12 21:09:05 +00001764 const ParsedAttributesView &attrList) {
Douglas Gregorf6102672012-01-01 21:23:57 +00001765 SmallVector<Decl *, 8> DeclsInGroup;
Craig Topper0f723bb2015-10-22 05:00:01 +00001766 for (const IdentifierLocPair &IdentPair : IdentList) {
1767 IdentifierInfo *Ident = IdentPair.first;
1768 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentPair.second,
Richard Smithbecb92d2017-10-10 22:33:17 +00001769 forRedeclarationInCurContext());
Douglas Gregor32c17572012-01-01 20:30:41 +00001770 ObjCProtocolDecl *PDecl
Fangrui Song6907ce22018-07-30 19:24:48 +00001771 = ObjCProtocolDecl::Create(Context, CurContext, Ident,
Craig Topper0f723bb2015-10-22 05:00:01 +00001772 IdentPair.second, AtProtocolLoc,
Douglas Gregor05a1f4d2012-01-01 22:06:18 +00001773 PrevDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00001774
Douglas Gregor32c17572012-01-01 20:30:41 +00001775 PushOnScopeChains(PDecl, TUScope);
Douglas Gregorf6102672012-01-01 21:23:57 +00001776 CheckObjCDeclScope(PDecl);
Erich Keanec480f302018-07-12 21:09:05 +00001777
1778 ProcessDeclAttributeList(TUScope, PDecl, attrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001779 AddPragmaAttributes(TUScope, PDecl);
1780
Douglas Gregor32c17572012-01-01 20:30:41 +00001781 if (PrevDecl)
1782 mergeDeclAttributes(PDecl, PrevDecl);
1783
Douglas Gregorf6102672012-01-01 21:23:57 +00001784 DeclsInGroup.push_back(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001785 }
Mike Stump11289f42009-09-09 15:08:12 +00001786
Richard Smith3beb7c62017-01-12 02:27:38 +00001787 return BuildDeclaratorGroup(DeclsInGroup);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001788}
1789
Erich Keanec480f302018-07-12 21:09:05 +00001790Decl *Sema::ActOnStartCategoryInterface(
1791 SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
1792 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
1793 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
1794 Decl *const *ProtoRefs, unsigned NumProtoRefs,
1795 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
1796 const ParsedAttributesView &AttrList) {
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001797 ObjCCategoryDecl *CDecl;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001798 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
Ted Kremenek514ff702010-02-23 19:39:46 +00001799
1800 /// Check that class of this category is already completely declared.
Douglas Gregor4123a862011-11-14 22:10:01 +00001801
Fangrui Song6907ce22018-07-30 19:24:48 +00001802 if (!IDecl
Douglas Gregor4123a862011-11-14 22:10:01 +00001803 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001804 diag::err_category_forward_interface,
Craig Topperc3ec1492014-05-26 06:22:03 +00001805 CategoryName == nullptr)) {
Ted Kremenek514ff702010-02-23 19:39:46 +00001806 // Create an invalid ObjCCategoryDecl to serve as context for
1807 // the enclosing method declarations. We mark the decl invalid
1808 // to make it clear that this isn't a valid AST.
1809 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001810 ClassLoc, CategoryLoc, CategoryName,
1811 IDecl, typeParamList);
Ted Kremenek514ff702010-02-23 19:39:46 +00001812 CDecl->setInvalidDecl();
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00001813 CurContext->addDecl(CDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00001814
Douglas Gregor4123a862011-11-14 22:10:01 +00001815 if (!IDecl)
1816 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001817 return ActOnObjCContainerStartDefinition(CDecl);
Ted Kremenek514ff702010-02-23 19:39:46 +00001818 }
1819
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001820 if (!CategoryName && IDecl->getImplementation()) {
1821 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
Fangrui Song6907ce22018-07-30 19:24:48 +00001822 Diag(IDecl->getImplementation()->getLocation(),
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001823 diag::note_implementation_declared);
Ted Kremenek514ff702010-02-23 19:39:46 +00001824 }
1825
Fariborz Jahanian30a42922010-02-15 21:55:26 +00001826 if (CategoryName) {
1827 /// Check for duplicate interface declaration for this category
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001828 if (ObjCCategoryDecl *Previous
1829 = IDecl->FindCategoryDeclaration(CategoryName)) {
1830 // Class extensions can be declared multiple times, categories cannot.
1831 Diag(CategoryLoc, diag::warn_dup_category_def)
1832 << ClassName << CategoryName;
1833 Diag(Previous->getLocation(), diag::note_previous_definition);
Chris Lattner9018ca82009-02-16 21:26:43 +00001834 }
1835 }
Chris Lattner9018ca82009-02-16 21:26:43 +00001836
Douglas Gregor85f3f952015-07-07 03:57:15 +00001837 // If we have a type parameter list, check it.
1838 if (typeParamList) {
1839 if (auto prevTypeParamList = IDecl->getTypeParamList()) {
1840 if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList,
1841 CategoryName
1842 ? TypeParamListContext::Category
1843 : TypeParamListContext::Extension))
1844 typeParamList = nullptr;
1845 } else {
1846 Diag(typeParamList->getLAngleLoc(),
1847 diag::err_objc_parameterized_category_nonclass)
1848 << (CategoryName != nullptr)
1849 << ClassName
1850 << typeParamList->getSourceRange();
1851
1852 typeParamList = nullptr;
1853 }
1854 }
1855
Argyrios Kyrtzidis3a5094b2011-08-30 19:43:26 +00001856 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001857 ClassLoc, CategoryLoc, CategoryName, IDecl,
1858 typeParamList);
Argyrios Kyrtzidis3a5094b2011-08-30 19:43:26 +00001859 // FIXME: PushOnScopeChains?
1860 CurContext->addDecl(CDecl);
1861
Alex Lorenza9c966d2018-02-23 23:49:43 +00001862 // Process the attributes before looking at protocols to ensure that the
1863 // availability attribute is attached to the category to provide availability
1864 // checking for protocol uses.
Erich Keanec480f302018-07-12 21:09:05 +00001865 ProcessDeclAttributeList(TUScope, CDecl, AttrList);
Alex Lorenza9c966d2018-02-23 23:49:43 +00001866 AddPragmaAttributes(TUScope, CDecl);
1867
Chris Lattnerda463fe2007-12-12 07:09:47 +00001868 if (NumProtoRefs) {
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001869 diagnoseUseOfProtocols(*this, CDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1870 NumProtoRefs, ProtoLocs);
1871 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001872 ProtoLocs, Context);
Fariborz Jahanian092cd6e2009-10-05 20:41:32 +00001873 // Protocols in the class extension belong to the class.
Fariborz Jahanian30a42922010-02-15 21:55:26 +00001874 if (CDecl->IsClassExtension())
Fangrui Song6907ce22018-07-30 19:24:48 +00001875 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
1876 NumProtoRefs, Context);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001877 }
Mike Stump11289f42009-09-09 15:08:12 +00001878
Anders Carlssona6b508a2008-11-04 16:57:32 +00001879 CheckObjCDeclScope(CDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001880 return ActOnObjCContainerStartDefinition(CDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001881}
1882
1883/// ActOnStartCategoryImplementation - Perform semantic checks on the
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001884/// category implementation declaration and build an ObjCCategoryImplDecl
Chris Lattnerda463fe2007-12-12 07:09:47 +00001885/// object.
John McCall48871652010-08-21 09:40:31 +00001886Decl *Sema::ActOnStartCategoryImplementation(
Chris Lattnerda463fe2007-12-12 07:09:47 +00001887 SourceLocation AtCatImplLoc,
1888 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1889 IdentifierInfo *CatName, SourceLocation CatLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001890 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
Craig Topperc3ec1492014-05-26 06:22:03 +00001891 ObjCCategoryDecl *CatIDecl = nullptr;
Argyrios Kyrtzidis4af2cb32012-03-02 19:14:29 +00001892 if (IDecl && IDecl->hasDefinition()) {
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001893 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
1894 if (!CatIDecl) {
1895 // Category @implementation with no corresponding @interface.
1896 // Create and install one.
Argyrios Kyrtzidis41fc05c2011-11-23 20:27:26 +00001897 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
1898 ClassLoc, CatLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001899 CatName, IDecl,
1900 /*typeParamList=*/nullptr);
Argyrios Kyrtzidis41fc05c2011-11-23 20:27:26 +00001901 CatIDecl->setImplicit();
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001902 }
1903 }
1904
Mike Stump11289f42009-09-09 15:08:12 +00001905 ObjCCategoryImplDecl *CDecl =
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001906 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
Argyrios Kyrtzidis4996f5f2011-12-09 00:31:40 +00001907 ClassLoc, AtCatImplLoc, CatLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001908 /// Check that class of this category is already completely declared.
Douglas Gregor4123a862011-11-14 22:10:01 +00001909 if (!IDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001910 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
John McCalld2930c22011-07-22 02:45:48 +00001911 CDecl->setInvalidDecl();
Douglas Gregor4123a862011-11-14 22:10:01 +00001912 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1913 diag::err_undef_interface)) {
1914 CDecl->setInvalidDecl();
John McCalld2930c22011-07-22 02:45:48 +00001915 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001916
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001917 // FIXME: PushOnScopeChains?
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001918 CurContext->addDecl(CDecl);
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001919
Douglas Gregor24ae22c2016-04-01 23:23:52 +00001920 // If the interface has the objc_runtime_visible attribute, we
1921 // cannot implement a category for it.
1922 if (IDecl && IDecl->hasAttr<ObjCRuntimeVisibleAttr>()) {
1923 Diag(ClassLoc, diag::err_objc_runtime_visible_category)
1924 << IDecl->getDeclName();
1925 }
1926
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001927 /// Check that CatName, category name, is not used in another implementation.
1928 if (CatIDecl) {
1929 if (CatIDecl->getImplementation()) {
1930 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
1931 << CatName;
1932 Diag(CatIDecl->getImplementation()->getLocation(),
1933 diag::note_previous_definition);
Argyrios Kyrtzidis0f6d5ca2013-05-30 18:53:21 +00001934 CDecl->setInvalidDecl();
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001935 } else {
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001936 CatIDecl->setImplementation(CDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00001937 // Warn on implementating category of deprecated class under
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001938 // -Wdeprecated-implementations flag.
Alex Lorenzf81d97e2017-07-13 16:35:59 +00001939 DiagnoseObjCImplementedDeprecations(*this, CatIDecl,
1940 CDecl->getLocation());
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001941 }
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001942 }
Mike Stump11289f42009-09-09 15:08:12 +00001943
Anders Carlssona6b508a2008-11-04 16:57:32 +00001944 CheckObjCDeclScope(CDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001945 return ActOnObjCContainerStartDefinition(CDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001946}
1947
John McCall48871652010-08-21 09:40:31 +00001948Decl *Sema::ActOnStartClassImplementation(
Chris Lattnerda463fe2007-12-12 07:09:47 +00001949 SourceLocation AtClassImplLoc,
1950 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001951 IdentifierInfo *SuperClassname,
Chris Lattnerda463fe2007-12-12 07:09:47 +00001952 SourceLocation SuperClassLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001953 ObjCInterfaceDecl *IDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001954 // Check for another declaration kind with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00001955 NamedDecl *PrevDecl
Douglas Gregorb8eaf292010-04-15 23:40:53 +00001956 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00001957 forRedeclarationInCurContext());
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001958 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001959 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Chris Lattner0369c572008-11-23 23:12:31 +00001960 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor1c283312010-08-11 12:19:30 +00001961 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
Richard Smithdb0ac552015-12-18 22:40:25 +00001962 // FIXME: This will produce an error if the definition of the interface has
1963 // been imported from a module but is not visible.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00001964 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1965 diag::warn_undef_interface);
Douglas Gregor40f7a002010-01-04 17:27:12 +00001966 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001967 // We did not find anything with the name ClassName; try to correct for
Douglas Gregor40f7a002010-01-04 17:27:12 +00001968 // typos in the class name.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001969 TypoCorrection Corrected = CorrectTypo(
1970 DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope,
1971 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(), CTK_NonError);
Richard Smithf9b15102013-08-17 00:46:16 +00001972 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1973 // Suggest the (potentially) correct interface name. Don't provide a
1974 // code-modification hint or use the typo name for recovery, because
1975 // this is just a warning. The program may actually be correct.
1976 diagnoseTypo(Corrected,
1977 PDiag(diag::warn_undef_interface_suggest) << ClassName,
1978 /*ErrorRecovery*/false);
Douglas Gregor40f7a002010-01-04 17:27:12 +00001979 } else {
1980 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
1981 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001982 }
Mike Stump11289f42009-09-09 15:08:12 +00001983
Chris Lattnerda463fe2007-12-12 07:09:47 +00001984 // Check that super class name is valid class name
Craig Topperc3ec1492014-05-26 06:22:03 +00001985 ObjCInterfaceDecl *SDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001986 if (SuperClassname) {
1987 // Check if a different kind of symbol declared in this scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001988 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
1989 LookupOrdinaryName);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001990 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001991 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
1992 << SuperClassname;
Chris Lattner0369c572008-11-23 23:12:31 +00001993 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001994 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001995 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidis3b60cff2012-03-13 01:09:36 +00001996 if (SDecl && !SDecl->hasDefinition())
Craig Topperc3ec1492014-05-26 06:22:03 +00001997 SDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001998 if (!SDecl)
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001999 Diag(SuperClassLoc, diag::err_undef_superclass)
2000 << SuperClassname << ClassName;
Douglas Gregor0b144e12011-12-15 00:29:59 +00002001 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00002002 // This implementation and its interface do not have the same
2003 // super class.
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002004 Diag(SuperClassLoc, diag::err_conflicting_super_class)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002005 << SDecl->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002006 Diag(SDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002007 }
2008 }
2009 }
Mike Stump11289f42009-09-09 15:08:12 +00002010
Chris Lattnerda463fe2007-12-12 07:09:47 +00002011 if (!IDecl) {
2012 // Legacy case of @implementation with no corresponding @interface.
2013 // Build, chain & install the interface decl into the identifier.
Daniel Dunbar73a73f52008-08-20 18:02:42 +00002014
Mike Stump87c57ac2009-05-16 07:39:55 +00002015 // FIXME: Do we support attributes on the @implementation? If so we should
2016 // copy them over.
Mike Stump11289f42009-09-09 15:08:12 +00002017 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00002018 ClassName, /*typeParamList=*/nullptr,
2019 /*PrevDecl=*/nullptr, ClassLoc,
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002020 true);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002021 AddPragmaAttributes(TUScope, IDecl);
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002022 IDecl->startDefinition();
Douglas Gregor16408322011-12-15 22:34:59 +00002023 if (SDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00002024 IDecl->setSuperClass(Context.getTrivialTypeSourceInfo(
2025 Context.getObjCInterfaceType(SDecl),
2026 SuperClassLoc));
Douglas Gregor16408322011-12-15 22:34:59 +00002027 IDecl->setEndOfDefinitionLoc(SuperClassLoc);
2028 } else {
2029 IDecl->setEndOfDefinitionLoc(ClassLoc);
2030 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002031
Douglas Gregorac345a32009-04-24 00:16:12 +00002032 PushOnScopeChains(IDecl, TUScope);
Douglas Gregor1c283312010-08-11 12:19:30 +00002033 } else {
2034 // Mark the interface as being completed, even if it was just as
2035 // @class ....;
2036 // declaration; the user cannot reopen it.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002037 if (!IDecl->hasDefinition())
2038 IDecl->startDefinition();
Chris Lattnerda463fe2007-12-12 07:09:47 +00002039 }
Mike Stump11289f42009-09-09 15:08:12 +00002040
2041 ObjCImplementationDecl* IMPDecl =
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00002042 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
Argyrios Kyrtzidisfac31622013-05-03 18:05:44 +00002043 ClassLoc, AtClassImplLoc, SuperClassLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002044
Anders Carlssona6b508a2008-11-04 16:57:32 +00002045 if (CheckObjCDeclScope(IMPDecl))
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00002046 return ActOnObjCContainerStartDefinition(IMPDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002047
Chris Lattnerda463fe2007-12-12 07:09:47 +00002048 // Check that there is no duplicate implementation of this class.
Douglas Gregor1c283312010-08-11 12:19:30 +00002049 if (IDecl->getImplementation()) {
2050 // FIXME: Don't leak everything!
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002051 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
Argyrios Kyrtzidis43cee9352009-07-21 00:06:04 +00002052 Diag(IDecl->getImplementation()->getLocation(),
2053 diag::note_previous_definition);
Argyrios Kyrtzidis0f6d5ca2013-05-30 18:53:21 +00002054 IMPDecl->setInvalidDecl();
Douglas Gregor1c283312010-08-11 12:19:30 +00002055 } else { // add it to the list.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002056 IDecl->setImplementation(IMPDecl);
Douglas Gregor79947a22009-04-24 00:11:27 +00002057 PushOnScopeChains(IMPDecl, TUScope);
Fangrui Song6907ce22018-07-30 19:24:48 +00002058 // Warn on implementating deprecated class under
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00002059 // -Wdeprecated-implementations flag.
Alex Lorenzf81d97e2017-07-13 16:35:59 +00002060 DiagnoseObjCImplementedDeprecations(*this, IDecl, IMPDecl->getLocation());
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002061 }
Douglas Gregor24ae22c2016-04-01 23:23:52 +00002062
2063 // If the superclass has the objc_runtime_visible attribute, we
2064 // cannot implement a subclass of it.
2065 if (IDecl->getSuperClass() &&
2066 IDecl->getSuperClass()->hasAttr<ObjCRuntimeVisibleAttr>()) {
2067 Diag(ClassLoc, diag::err_objc_runtime_visible_subclass)
2068 << IDecl->getDeclName()
2069 << IDecl->getSuperClass()->getDeclName();
2070 }
2071
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00002072 return ActOnObjCContainerStartDefinition(IMPDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002073}
2074
Argyrios Kyrtzidis2e85c5f2012-02-23 21:11:20 +00002075Sema::DeclGroupPtrTy
2076Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
2077 SmallVector<Decl *, 64> DeclsInGroup;
2078 DeclsInGroup.reserve(Decls.size() + 1);
2079
2080 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
2081 Decl *Dcl = Decls[i];
2082 if (!Dcl)
2083 continue;
2084 if (Dcl->getDeclContext()->isFileContext())
2085 Dcl->setTopLevelDeclInObjCContainer();
2086 DeclsInGroup.push_back(Dcl);
2087 }
2088
2089 DeclsInGroup.push_back(ObjCImpDecl);
2090
Richard Smith3beb7c62017-01-12 02:27:38 +00002091 return BuildDeclaratorGroup(DeclsInGroup);
Argyrios Kyrtzidis2e85c5f2012-02-23 21:11:20 +00002092}
2093
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002094void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
2095 ObjCIvarDecl **ivars, unsigned numIvars,
Chris Lattnerda463fe2007-12-12 07:09:47 +00002096 SourceLocation RBrace) {
2097 assert(ImpDecl && "missing implementation decl");
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002098 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
Chris Lattnerda463fe2007-12-12 07:09:47 +00002099 if (!IDecl)
2100 return;
James Dennett634962f2012-06-14 21:40:34 +00002101 /// Check case of non-existing \@interface decl.
2102 /// (legacy objective-c \@implementation decl without an \@interface decl).
Chris Lattnerda463fe2007-12-12 07:09:47 +00002103 /// Add implementations's ivar to the synthesize class's ivar list.
Steve Naroffaac654a2009-04-20 20:09:33 +00002104 if (IDecl->isImplicitInterfaceDecl()) {
Douglas Gregor16408322011-12-15 22:34:59 +00002105 IDecl->setEndOfDefinitionLoc(RBrace);
Fariborz Jahanian20912d62010-02-17 17:00:07 +00002106 // Add ivar's to class's DeclContext.
2107 for (unsigned i = 0, e = numIvars; i != e; ++i) {
Fariborz Jahanianc0309cd2010-02-17 18:10:54 +00002108 ivars[i]->setLexicalDeclContext(ImpDecl);
Richard Smith05afe5e2012-03-13 03:12:56 +00002109 IDecl->makeDeclVisibleInContext(ivars[i]);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00002110 ImpDecl->addDecl(ivars[i]);
Fariborz Jahanian20912d62010-02-17 17:00:07 +00002111 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002112
Chris Lattnerda463fe2007-12-12 07:09:47 +00002113 return;
2114 }
2115 // If implementation has empty ivar list, just return.
2116 if (numIvars == 0)
2117 return;
Mike Stump11289f42009-09-09 15:08:12 +00002118
Chris Lattnerda463fe2007-12-12 07:09:47 +00002119 assert(ivars && "missing @implementation ivars");
John McCall5fb5df92012-06-20 06:18:46 +00002120 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002121 if (ImpDecl->getSuperClass())
2122 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
2123 for (unsigned i = 0; i < numIvars; i++) {
2124 ObjCIvarDecl* ImplIvar = ivars[i];
Fangrui Song6907ce22018-07-30 19:24:48 +00002125 if (const ObjCIvarDecl *ClsIvar =
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002126 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002127 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002128 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2129 continue;
2130 }
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00002131 // Check class extensions (unnamed categories) for duplicate ivars.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002132 for (const auto *CDecl : IDecl->visible_extensions()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002133 if (const ObjCIvarDecl *ClsExtIvar =
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00002134 CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002135 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00002136 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
2137 continue;
2138 }
2139 }
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002140 // Instance ivar to Implementation's DeclContext.
2141 ImplIvar->setLexicalDeclContext(ImpDecl);
Richard Smith05afe5e2012-03-13 03:12:56 +00002142 IDecl->makeDeclVisibleInContext(ImplIvar);
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002143 ImpDecl->addDecl(ImplIvar);
2144 }
2145 return;
2146 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002147 // Check interface's Ivar list against those in the implementation.
2148 // names and types must match.
2149 //
Chris Lattnerda463fe2007-12-12 07:09:47 +00002150 unsigned j = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002151 ObjCInterfaceDecl::ivar_iterator
Chris Lattner061227a2007-12-12 17:58:05 +00002152 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
2153 for (; numIvars > 0 && IVI != IVE; ++IVI) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002154 ObjCIvarDecl* ImplIvar = ivars[j++];
David Blaikie40ed2972012-06-06 20:45:41 +00002155 ObjCIvarDecl* ClsIvar = *IVI;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002156 assert (ImplIvar && "missing implementation ivar");
2157 assert (ClsIvar && "missing class ivar");
Mike Stump11289f42009-09-09 15:08:12 +00002158
Steve Naroff157599f2009-03-03 14:49:36 +00002159 // First, make sure the types match.
Richard Smithcaf33902011-10-10 18:28:20 +00002160 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
Chris Lattner3b054132008-11-19 05:08:23 +00002161 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002162 << ImplIvar->getIdentifier()
2163 << ImplIvar->getType() << ClsIvar->getType();
Chris Lattner0369c572008-11-23 23:12:31 +00002164 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
Richard Smithcaf33902011-10-10 18:28:20 +00002165 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
2166 ImplIvar->getBitWidthValue(Context) !=
2167 ClsIvar->getBitWidthValue(Context)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002168 Diag(ImplIvar->getBitWidth()->getBeginLoc(),
2169 diag::err_conflicting_ivar_bitwidth)
2170 << ImplIvar->getIdentifier();
2171 Diag(ClsIvar->getBitWidth()->getBeginLoc(),
Richard Smithcaf33902011-10-10 18:28:20 +00002172 diag::note_previous_definition);
Mike Stump11289f42009-09-09 15:08:12 +00002173 }
Steve Naroff157599f2009-03-03 14:49:36 +00002174 // Make sure the names are identical.
2175 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002176 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002177 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
Chris Lattner0369c572008-11-23 23:12:31 +00002178 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002179 }
2180 --numIvars;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002181 }
Mike Stump11289f42009-09-09 15:08:12 +00002182
Chris Lattner0f29d982007-12-12 18:11:49 +00002183 if (numIvars > 0)
Alp Tokerfff06742013-12-02 03:50:21 +00002184 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
Chris Lattner0f29d982007-12-12 18:11:49 +00002185 else if (IVI != IVE)
Alp Tokerfff06742013-12-02 03:50:21 +00002186 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002187}
2188
Ted Kremenekf87decd2013-12-13 05:58:44 +00002189static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
2190 ObjCMethodDecl *method,
2191 bool &IncompleteImpl,
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002192 unsigned DiagID,
Craig Topperc3ec1492014-05-26 06:22:03 +00002193 NamedDecl *NeededFor = nullptr) {
Fariborz Jahanian9fc39c42011-06-24 20:31:37 +00002194 // No point warning no definition of method which is 'unavailable'.
Erik Pilkingtonecce5c92018-07-07 01:50:20 +00002195 if (method->getAvailability() == AR_Unavailable)
Fariborz Jahanian9fc39c42011-06-24 20:31:37 +00002196 return;
Erik Pilkingtonecce5c92018-07-07 01:50:20 +00002197
Ted Kremenek65d63572013-03-27 00:02:21 +00002198 // FIXME: For now ignore 'IncompleteImpl'.
2199 // Previously we grouped all unimplemented methods under a single
2200 // warning, but some users strongly voiced that they would prefer
2201 // separate warnings. We will give that approach a try, as that
2202 // matches what we do with protocols.
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002203 {
2204 const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
2205 B << method;
2206 if (NeededFor)
2207 B << NeededFor;
2208 }
Ted Kremenek65d63572013-03-27 00:02:21 +00002209
2210 // Issue a note to the original declaration.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002211 SourceLocation MethodLoc = method->getBeginLoc();
Ted Kremenek65d63572013-03-27 00:02:21 +00002212 if (MethodLoc.isValid())
Ted Kremenekf87decd2013-12-13 05:58:44 +00002213 S.Diag(MethodLoc, diag::note_method_declared_at) << method;
Steve Naroff15833ed2008-02-10 21:38:56 +00002214}
2215
David Chisnallb62d15c2010-10-25 17:23:52 +00002216/// Determines if type B can be substituted for type A. Returns true if we can
Fangrui Song6907ce22018-07-30 19:24:48 +00002217/// guarantee that anything that the user will do to an object of type A can
2218/// also be done to an object of type B. This is trivially true if the two
David Chisnallb62d15c2010-10-25 17:23:52 +00002219/// types are the same, or if B is a subclass of A. It becomes more complex
2220/// in cases where protocols are involved.
2221///
2222/// Object types in Objective-C describe the minimum requirements for an
2223/// object, rather than providing a complete description of a type. For
2224/// example, if A is a subclass of B, then B* may refer to an instance of A.
2225/// The principle of substitutability means that we may use an instance of A
2226/// anywhere that we may use an instance of B - it will implement all of the
Fangrui Song6907ce22018-07-30 19:24:48 +00002227/// ivars of B and all of the methods of B.
David Chisnallb62d15c2010-10-25 17:23:52 +00002228///
Fangrui Song6907ce22018-07-30 19:24:48 +00002229/// This substitutability is important when type checking methods, because
David Chisnallb62d15c2010-10-25 17:23:52 +00002230/// the implementation may have stricter type definitions than the interface.
2231/// The interface specifies minimum requirements, but the implementation may
Fangrui Song6907ce22018-07-30 19:24:48 +00002232/// have more accurate ones. For example, a method may privately accept
David Chisnallb62d15c2010-10-25 17:23:52 +00002233/// instances of B, but only publish that it accepts instances of A. Any
2234/// object passed to it will be type checked against B, and so will implicitly
2235/// by a valid A*. Similarly, a method may return a subclass of the class that
2236/// it is declared as returning.
2237///
2238/// This is most important when considering subclassing. A method in a
2239/// subclass must accept any object as an argument that its superclass's
2240/// implementation accepts. It may, however, accept a more general type
2241/// without breaking substitutability (i.e. you can still use the subclass
2242/// anywhere that you can use the superclass, but not vice versa). The
2243/// converse requirement applies to return types: the return type for a
2244/// subclass method must be a valid object of the kind that the superclass
2245/// advertises, but it may be specified more accurately. This avoids the need
2246/// for explicit down-casting by callers.
2247///
Fangrui Song6907ce22018-07-30 19:24:48 +00002248/// Note: This is a stricter requirement than for assignment.
John McCall071df462010-10-28 02:34:38 +00002249static bool isObjCTypeSubstitutable(ASTContext &Context,
2250 const ObjCObjectPointerType *A,
2251 const ObjCObjectPointerType *B,
2252 bool rejectId) {
2253 // Reject a protocol-unqualified id.
2254 if (rejectId && B->isObjCIdType()) return false;
David Chisnallb62d15c2010-10-25 17:23:52 +00002255
2256 // If B is a qualified id, then A must also be a qualified id and it must
2257 // implement all of the protocols in B. It may not be a qualified class.
2258 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
2259 // stricter definition so it is not substitutable for id<A>.
2260 if (B->isObjCQualifiedIdType()) {
2261 return A->isObjCQualifiedIdType() &&
John McCall071df462010-10-28 02:34:38 +00002262 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
2263 QualType(B,0),
2264 false);
David Chisnallb62d15c2010-10-25 17:23:52 +00002265 }
2266
2267 /*
2268 // id is a special type that bypasses type checking completely. We want a
2269 // warning when it is used in one place but not another.
2270 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
2271
2272
2273 // If B is a qualified id, then A must also be a qualified id (which it isn't
2274 // if we've got this far)
2275 if (B->isObjCQualifiedIdType()) return false;
2276 */
2277
2278 // Now we know that A and B are (potentially-qualified) class types. The
2279 // normal rules for assignment apply.
John McCall071df462010-10-28 02:34:38 +00002280 return Context.canAssignObjCInterfaces(A, B);
David Chisnallb62d15c2010-10-25 17:23:52 +00002281}
2282
John McCall071df462010-10-28 02:34:38 +00002283static SourceRange getTypeRange(TypeSourceInfo *TSI) {
2284 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
2285}
2286
Douglas Gregor813a0662015-06-19 18:14:38 +00002287/// Determine whether two set of Objective-C declaration qualifiers conflict.
2288static bool objcModifiersConflict(Decl::ObjCDeclQualifier x,
2289 Decl::ObjCDeclQualifier y) {
2290 return (x & ~Decl::OBJC_TQ_CSNullability) !=
2291 (y & ~Decl::OBJC_TQ_CSNullability);
2292}
2293
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002294static bool CheckMethodOverrideReturn(Sema &S,
John McCall071df462010-10-28 02:34:38 +00002295 ObjCMethodDecl *MethodImpl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002296 ObjCMethodDecl *MethodDecl,
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002297 bool IsProtocolMethodDecl,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002298 bool IsOverridingMode,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002299 bool Warn) {
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002300 if (IsProtocolMethodDecl &&
Douglas Gregor813a0662015-06-19 18:14:38 +00002301 objcModifiersConflict(MethodDecl->getObjCDeclQualifier(),
2302 MethodImpl->getObjCDeclQualifier())) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002303 if (Warn) {
Alp Toker314cc812014-01-25 16:55:45 +00002304 S.Diag(MethodImpl->getLocation(),
2305 (IsOverridingMode
2306 ? diag::warn_conflicting_overriding_ret_type_modifiers
2307 : diag::warn_conflicting_ret_type_modifiers))
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002308 << MethodImpl->getDeclName()
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002309 << MethodImpl->getReturnTypeSourceRange();
Alp Toker314cc812014-01-25 16:55:45 +00002310 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002311 << MethodDecl->getReturnTypeSourceRange();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002312 }
2313 else
2314 return false;
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002315 }
Douglas Gregor813a0662015-06-19 18:14:38 +00002316 if (Warn && IsOverridingMode &&
2317 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2318 !S.Context.hasSameNullabilityTypeQualifier(MethodImpl->getReturnType(),
2319 MethodDecl->getReturnType(),
2320 false)) {
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002321 auto nullabilityMethodImpl =
2322 *MethodImpl->getReturnType()->getNullability(S.Context);
2323 auto nullabilityMethodDecl =
2324 *MethodDecl->getReturnType()->getNullability(S.Context);
Douglas Gregor813a0662015-06-19 18:14:38 +00002325 S.Diag(MethodImpl->getLocation(),
2326 diag::warn_conflicting_nullability_attr_overriding_ret_types)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002327 << DiagNullabilityKind(
2328 nullabilityMethodImpl,
2329 ((MethodImpl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2330 != 0))
2331 << DiagNullabilityKind(
2332 nullabilityMethodDecl,
2333 ((MethodDecl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2334 != 0));
Douglas Gregor813a0662015-06-19 18:14:38 +00002335 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2336 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002337
Alp Toker314cc812014-01-25 16:55:45 +00002338 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
2339 MethodDecl->getReturnType()))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002340 return true;
2341 if (!Warn)
2342 return false;
John McCall071df462010-10-28 02:34:38 +00002343
Fangrui Song6907ce22018-07-30 19:24:48 +00002344 unsigned DiagID =
2345 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002346 : diag::warn_conflicting_ret_types;
John McCall071df462010-10-28 02:34:38 +00002347
2348 // Mismatches between ObjC pointers go into a different warning
2349 // category, and sometimes they're even completely whitelisted.
2350 if (const ObjCObjectPointerType *ImplPtrTy =
Alp Toker314cc812014-01-25 16:55:45 +00002351 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
John McCall071df462010-10-28 02:34:38 +00002352 if (const ObjCObjectPointerType *IfacePtrTy =
Alp Toker314cc812014-01-25 16:55:45 +00002353 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
John McCall071df462010-10-28 02:34:38 +00002354 // Allow non-matching return types as long as they don't violate
2355 // the principle of substitutability. Specifically, we permit
2356 // return types that are subclasses of the declared return type,
2357 // or that are more-qualified versions of the declared type.
2358 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002359 return false;
John McCall071df462010-10-28 02:34:38 +00002360
Fangrui Song6907ce22018-07-30 19:24:48 +00002361 DiagID =
2362 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002363 : diag::warn_non_covariant_ret_types;
John McCall071df462010-10-28 02:34:38 +00002364 }
2365 }
2366
2367 S.Diag(MethodImpl->getLocation(), DiagID)
Alp Toker314cc812014-01-25 16:55:45 +00002368 << MethodImpl->getDeclName() << MethodDecl->getReturnType()
2369 << MethodImpl->getReturnType()
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002370 << MethodImpl->getReturnTypeSourceRange();
Alp Toker314cc812014-01-25 16:55:45 +00002371 S.Diag(MethodDecl->getLocation(), IsOverridingMode
2372 ? diag::note_previous_declaration
2373 : diag::note_previous_definition)
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002374 << MethodDecl->getReturnTypeSourceRange();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002375 return false;
John McCall071df462010-10-28 02:34:38 +00002376}
2377
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002378static bool CheckMethodOverrideParam(Sema &S,
John McCall071df462010-10-28 02:34:38 +00002379 ObjCMethodDecl *MethodImpl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002380 ObjCMethodDecl *MethodDecl,
John McCall071df462010-10-28 02:34:38 +00002381 ParmVarDecl *ImplVar,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002382 ParmVarDecl *IfaceVar,
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002383 bool IsProtocolMethodDecl,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002384 bool IsOverridingMode,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002385 bool Warn) {
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002386 if (IsProtocolMethodDecl &&
Douglas Gregor813a0662015-06-19 18:14:38 +00002387 objcModifiersConflict(ImplVar->getObjCDeclQualifier(),
2388 IfaceVar->getObjCDeclQualifier())) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002389 if (Warn) {
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002390 if (IsOverridingMode)
Fangrui Song6907ce22018-07-30 19:24:48 +00002391 S.Diag(ImplVar->getLocation(),
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002392 diag::warn_conflicting_overriding_param_modifiers)
2393 << getTypeRange(ImplVar->getTypeSourceInfo())
2394 << MethodImpl->getDeclName();
Fangrui Song6907ce22018-07-30 19:24:48 +00002395 else S.Diag(ImplVar->getLocation(),
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002396 diag::warn_conflicting_param_modifiers)
2397 << getTypeRange(ImplVar->getTypeSourceInfo())
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002398 << MethodImpl->getDeclName();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002399 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
Fangrui Song6907ce22018-07-30 19:24:48 +00002400 << getTypeRange(IfaceVar->getTypeSourceInfo());
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002401 }
2402 else
2403 return false;
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002404 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002405
John McCall071df462010-10-28 02:34:38 +00002406 QualType ImplTy = ImplVar->getType();
2407 QualType IfaceTy = IfaceVar->getType();
Douglas Gregor813a0662015-06-19 18:14:38 +00002408 if (Warn && IsOverridingMode &&
2409 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2410 !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) {
Douglas Gregor813a0662015-06-19 18:14:38 +00002411 S.Diag(ImplVar->getLocation(),
2412 diag::warn_conflicting_nullability_attr_overriding_param_types)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002413 << DiagNullabilityKind(
2414 *ImplTy->getNullability(S.Context),
2415 ((ImplVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2416 != 0))
2417 << DiagNullabilityKind(
2418 *IfaceTy->getNullability(S.Context),
2419 ((IfaceVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2420 != 0));
2421 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration);
Douglas Gregor813a0662015-06-19 18:14:38 +00002422 }
John McCall071df462010-10-28 02:34:38 +00002423 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002424 return true;
Manman Renc5705ba2016-09-13 17:41:05 +00002425
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002426 if (!Warn)
2427 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00002428 unsigned DiagID =
2429 IsOverridingMode ? diag::warn_conflicting_overriding_param_types
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002430 : diag::warn_conflicting_param_types;
John McCall071df462010-10-28 02:34:38 +00002431
2432 // Mismatches between ObjC pointers go into a different warning
2433 // category, and sometimes they're even completely whitelisted.
2434 if (const ObjCObjectPointerType *ImplPtrTy =
2435 ImplTy->getAs<ObjCObjectPointerType>()) {
2436 if (const ObjCObjectPointerType *IfacePtrTy =
2437 IfaceTy->getAs<ObjCObjectPointerType>()) {
2438 // Allow non-matching argument types as long as they don't
2439 // violate the principle of substitutability. Specifically, the
2440 // implementation must accept any objects that the superclass
2441 // accepts, however it may also accept others.
2442 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002443 return false;
John McCall071df462010-10-28 02:34:38 +00002444
Fangrui Song6907ce22018-07-30 19:24:48 +00002445 DiagID =
2446 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002447 : diag::warn_non_contravariant_param_types;
John McCall071df462010-10-28 02:34:38 +00002448 }
2449 }
2450
2451 S.Diag(ImplVar->getLocation(), DiagID)
2452 << getTypeRange(ImplVar->getTypeSourceInfo())
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002453 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
Fangrui Song6907ce22018-07-30 19:24:48 +00002454 S.Diag(IfaceVar->getLocation(),
2455 (IsOverridingMode ? diag::note_previous_declaration
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002456 : diag::note_previous_definition))
John McCall071df462010-10-28 02:34:38 +00002457 << getTypeRange(IfaceVar->getTypeSourceInfo());
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002458 return false;
John McCall071df462010-10-28 02:34:38 +00002459}
John McCall31168b02011-06-15 23:02:42 +00002460
2461/// In ARC, check whether the conventional meanings of the two methods
2462/// match. If they don't, it's a hard error.
2463static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
2464 ObjCMethodDecl *decl) {
2465 ObjCMethodFamily implFamily = impl->getMethodFamily();
2466 ObjCMethodFamily declFamily = decl->getMethodFamily();
2467 if (implFamily == declFamily) return false;
2468
2469 // Since conventions are sorted by selector, the only possibility is
2470 // that the types differ enough to cause one selector or the other
2471 // to fall out of the family.
2472 assert(implFamily == OMF_None || declFamily == OMF_None);
2473
2474 // No further diagnostics required on invalid declarations.
2475 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
2476
2477 const ObjCMethodDecl *unmatched = impl;
2478 ObjCMethodFamily family = declFamily;
2479 unsigned errorID = diag::err_arc_lost_method_convention;
2480 unsigned noteID = diag::note_arc_lost_method_convention;
2481 if (declFamily == OMF_None) {
2482 unmatched = decl;
2483 family = implFamily;
2484 errorID = diag::err_arc_gained_method_convention;
2485 noteID = diag::note_arc_gained_method_convention;
2486 }
2487
2488 // Indexes into a %select clause in the diagnostic.
2489 enum FamilySelector {
2490 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
2491 };
2492 FamilySelector familySelector = FamilySelector();
2493
2494 switch (family) {
2495 case OMF_None: llvm_unreachable("logic error, no method convention");
2496 case OMF_retain:
2497 case OMF_release:
2498 case OMF_autorelease:
2499 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +00002500 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002501 case OMF_retainCount:
2502 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002503 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002504 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00002505 // Mismatches for these methods don't change ownership
2506 // conventions, so we don't care.
2507 return false;
2508
2509 case OMF_init: familySelector = F_init; break;
2510 case OMF_alloc: familySelector = F_alloc; break;
2511 case OMF_copy: familySelector = F_copy; break;
2512 case OMF_mutableCopy: familySelector = F_mutableCopy; break;
2513 case OMF_new: familySelector = F_new; break;
2514 }
2515
2516 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
2517 ReasonSelector reasonSelector;
2518
2519 // The only reason these methods don't fall within their families is
2520 // due to unusual result types.
Alp Toker314cc812014-01-25 16:55:45 +00002521 if (unmatched->getReturnType()->isObjCObjectPointerType()) {
John McCall31168b02011-06-15 23:02:42 +00002522 reasonSelector = R_UnrelatedReturn;
2523 } else {
2524 reasonSelector = R_NonObjectReturn;
2525 }
2526
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00002527 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
2528 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
John McCall31168b02011-06-15 23:02:42 +00002529
2530 return true;
2531}
John McCall071df462010-10-28 02:34:38 +00002532
Fariborz Jahanian7988d7d2008-12-05 18:18:52 +00002533void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002534 ObjCMethodDecl *MethodDecl,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002535 bool IsProtocolMethodDecl) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002536 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002537 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
2538 return;
2539
Fangrui Song6907ce22018-07-30 19:24:48 +00002540 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2541 IsProtocolMethodDecl, false,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002542 true);
Mike Stump11289f42009-09-09 15:08:12 +00002543
Chris Lattner67f35b02009-04-11 19:58:42 +00002544 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002545 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2546 EF = MethodDecl->param_end();
2547 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002548 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002549 IsProtocolMethodDecl, false, true);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002550 }
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002551
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002552 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002553 Diag(ImpMethodDecl->getLocation(),
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002554 diag::warn_conflicting_variadic);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002555 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002556 }
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002557}
2558
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002559void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2560 ObjCMethodDecl *Overridden,
2561 bool IsProtocolMethodDecl) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002562
2563 CheckMethodOverrideReturn(*this, Method, Overridden,
2564 IsProtocolMethodDecl, true,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002565 true);
Fangrui Song6907ce22018-07-30 19:24:48 +00002566
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002567 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002568 IF = Overridden->param_begin(), EM = Method->param_end(),
2569 EF = Overridden->param_end();
2570 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002571 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
2572 IsProtocolMethodDecl, true, true);
2573 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002574
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002575 if (Method->isVariadic() != Overridden->isVariadic()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002576 Diag(Method->getLocation(),
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002577 diag::warn_conflicting_overriding_variadic);
2578 Diag(Overridden->getLocation(), diag::note_previous_declaration);
2579 }
2580}
2581
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002582/// WarnExactTypedMethods - This routine issues a warning if method
2583/// implementation declaration matches exactly that of its declaration.
2584void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2585 ObjCMethodDecl *MethodDecl,
2586 bool IsProtocolMethodDecl) {
2587 // don't issue warning when protocol method is optional because primary
2588 // class is not required to implement it and it is safe for protocol
2589 // to implement it.
2590 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
2591 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00002592 // don't issue warning when primary class's method is
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002593 // depecated/unavailable.
2594 if (MethodDecl->hasAttr<UnavailableAttr>() ||
2595 MethodDecl->hasAttr<DeprecatedAttr>())
2596 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00002597
2598 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002599 IsProtocolMethodDecl, false, false);
2600 if (match)
2601 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002602 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2603 EF = MethodDecl->param_end();
2604 IM != EM && IF != EF; ++IM, ++IF) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002605 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002606 *IM, *IF,
2607 IsProtocolMethodDecl, false, false);
2608 if (!match)
2609 break;
2610 }
2611 if (match)
2612 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
David Chisnall92918512011-08-08 17:32:19 +00002613 if (match)
2614 match = !(MethodDecl->isClassMethod() &&
2615 MethodDecl->getSelector() == GetNullarySelector("load", Context));
Fangrui Song6907ce22018-07-30 19:24:48 +00002616
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002617 if (match) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002618 Diag(ImpMethodDecl->getLocation(),
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002619 diag::warn_category_method_impl_match);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002620 Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
2621 << MethodDecl->getDeclName();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002622 }
2623}
2624
Mike Stump87c57ac2009-05-16 07:39:55 +00002625/// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
2626/// improve the efficiency of selector lookups and type checking by associating
2627/// with each protocol / interface / category the flattened instance tables. If
2628/// we used an immutable set to keep the table then it wouldn't add significant
2629/// memory cost and it would be handy for lookups.
Daniel Dunbar4684f372008-08-27 05:40:03 +00002630
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002631typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
Ahmed Charlesaf94d562014-03-09 11:34:25 +00002632typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002633
2634static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
2635 ProtocolNameSet &PNS) {
2636 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
2637 PNS.insert(PDecl->getIdentifier());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002638 for (const auto *PI : PDecl->protocols())
2639 findProtocolsWithExplicitImpls(PI, PNS);
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002640}
2641
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002642/// Recursively populates a set with all conformed protocols in a class
2643/// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
2644/// attribute.
2645static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
2646 ProtocolNameSet &PNS) {
2647 if (!Super)
2648 return;
2649
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002650 for (const auto *I : Super->all_referenced_protocols())
2651 findProtocolsWithExplicitImpls(I, PNS);
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002652
2653 findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002654}
2655
Steve Naroffa36992242008-02-08 22:06:17 +00002656/// CheckProtocolMethodDefs - This routine checks unimplemented methods
Chris Lattnerda463fe2007-12-12 07:09:47 +00002657/// Declared in protocol, and those referenced by it.
Ted Kremenek285ee852013-12-13 06:26:10 +00002658static void CheckProtocolMethodDefs(Sema &S,
2659 SourceLocation ImpLoc,
2660 ObjCProtocolDecl *PDecl,
2661 bool& IncompleteImpl,
2662 const Sema::SelectorSet &InsMap,
2663 const Sema::SelectorSet &ClsMap,
Ted Kremenek33e430f2013-12-13 06:26:14 +00002664 ObjCContainerDecl *CDecl,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002665 LazyProtocolNameSet &ProtocolsExplictImpl) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002666 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00002667 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002668 : dyn_cast<ObjCInterfaceDecl>(CDecl);
Fariborz Jahanian2e8074b2010-03-27 21:10:05 +00002669 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
Fangrui Song6907ce22018-07-30 19:24:48 +00002670
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002671 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
Craig Topperc3ec1492014-05-26 06:22:03 +00002672 ObjCInterfaceDecl *NSIDecl = nullptr;
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002673
2674 // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
2675 // then we should check if any class in the super class hierarchy also
2676 // conforms to this protocol, either directly or via protocol inheritance.
2677 // If so, we can skip checking this protocol completely because we
2678 // know that a parent class already satisfies this protocol.
2679 //
2680 // Note: we could generalize this logic for all protocols, and merely
2681 // add the limit on looking at the super class chain for just
2682 // specially marked protocols. This may be a good optimization. This
2683 // change is restricted to 'objc_protocol_requires_explicit_implementation'
2684 // protocols for now for controlled evaluation.
2685 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
Ahmed Charlesaf94d562014-03-09 11:34:25 +00002686 if (!ProtocolsExplictImpl) {
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002687 ProtocolsExplictImpl.reset(new ProtocolNameSet);
2688 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
2689 }
2690 if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
2691 ProtocolsExplictImpl->end())
2692 return;
2693
2694 // If no super class conforms to the protocol, we should not search
2695 // for methods in the super class to implicitly satisfy the protocol.
Craig Topperc3ec1492014-05-26 06:22:03 +00002696 Super = nullptr;
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002697 }
2698
Ted Kremenek285ee852013-12-13 06:26:10 +00002699 if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
Mike Stump11289f42009-09-09 15:08:12 +00002700 // check to see if class implements forwardInvocation method and objects
2701 // of this class are derived from 'NSProxy' so that to forward requests
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002702 // from one object to another.
Mike Stump11289f42009-09-09 15:08:12 +00002703 // Under such conditions, which means that every method possible is
2704 // implemented in the class, we should not issue "Method definition not
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002705 // found" warnings.
2706 // FIXME: Use a general GetUnarySelector method for this.
Ted Kremenek285ee852013-12-13 06:26:10 +00002707 IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
2708 Selector fISelector = S.Context.Selectors.getSelector(1, &II);
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002709 if (InsMap.count(fISelector))
2710 // Is IDecl derived from 'NSProxy'? If so, no instance methods
2711 // need be implemented in the implementation.
Ted Kremenek285ee852013-12-13 06:26:10 +00002712 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002713 }
Mike Stump11289f42009-09-09 15:08:12 +00002714
Fariborz Jahanianc41cf052013-01-07 19:21:03 +00002715 // If this is a forward protocol declaration, get its definition.
2716 if (!PDecl->isThisDeclarationADefinition() &&
2717 PDecl->getDefinition())
2718 PDecl = PDecl->getDefinition();
Fangrui Song6907ce22018-07-30 19:24:48 +00002719
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002720 // If a method lookup fails locally we still need to look and see if
2721 // the method was implemented by a base class or an inherited
2722 // protocol. This lookup is slow, but occurs rarely in correct code
2723 // and otherwise would terminate in a warning.
2724
Chris Lattnerda463fe2007-12-12 07:09:47 +00002725 // check unimplemented instance methods.
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002726 if (!NSIDecl)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002727 for (auto *method : PDecl->instance_methods()) {
Mike Stump11289f42009-09-09 15:08:12 +00002728 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
Jordan Rosed01e83a2012-10-10 16:42:25 +00002729 !method->isPropertyAccessor() &&
2730 !InsMap.count(method->getSelector()) &&
Ted Kremenek00781502013-11-23 01:01:29 +00002731 (!Super || !Super->lookupMethod(method->getSelector(),
2732 true /* instance */,
2733 false /* shallowCategory */,
Ted Kremenek28eace62013-11-23 01:01:34 +00002734 true /* followsSuper */,
Craig Topperc3ec1492014-05-26 06:22:03 +00002735 nullptr /* category */))) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002736 // If a method is not implemented in the category implementation but
2737 // has been declared in its primary class, superclass,
Fangrui Song6907ce22018-07-30 19:24:48 +00002738 // or in one of their protocols, no need to issue the warning.
2739 // This is because method will be implemented in the primary class
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002740 // or one of its super class implementation.
Fangrui Song6907ce22018-07-30 19:24:48 +00002741
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002742 // Ugly, but necessary. Method declared in protocol might have
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002743 // have been synthesized due to a property declared in the class which
2744 // uses the protocol.
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002745 if (ObjCMethodDecl *MethodInClass =
Ted Kremenek00781502013-11-23 01:01:29 +00002746 IDecl->lookupMethod(method->getSelector(),
2747 true /* instance */,
2748 true /* shallowCategoryLookup */,
2749 false /* followSuper */))
Jordan Rosed01e83a2012-10-10 16:42:25 +00002750 if (C || MethodInClass->isPropertyAccessor())
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002751 continue;
2752 unsigned DIAG = diag::warn_unimplemented_protocol_method;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002753 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
Ted Kremenek285ee852013-12-13 06:26:10 +00002754 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002755 PDecl);
Fariborz Jahanian97752f72010-03-27 19:02:17 +00002756 }
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002757 }
2758 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002759 // check unimplemented class methods
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002760 for (auto *method : PDecl->class_methods()) {
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002761 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
2762 !ClsMap.count(method->getSelector()) &&
Ted Kremenek00781502013-11-23 01:01:29 +00002763 (!Super || !Super->lookupMethod(method->getSelector(),
2764 false /* class method */,
2765 false /* shallowCategoryLookup */,
Ted Kremenek28eace62013-11-23 01:01:34 +00002766 true /* followSuper */,
Craig Topperc3ec1492014-05-26 06:22:03 +00002767 nullptr /* category */))) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002768 // See above comment for instance method lookups.
Ted Kremenek00781502013-11-23 01:01:29 +00002769 if (C && IDecl->lookupMethod(method->getSelector(),
2770 false /* class */,
2771 true /* shallowCategoryLookup */,
2772 false /* followSuper */))
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002773 continue;
Ted Kremenek00781502013-11-23 01:01:29 +00002774
Fariborz Jahanianc1fb8622010-03-31 18:23:33 +00002775 unsigned DIAG = diag::warn_unimplemented_protocol_method;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002776 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
Ted Kremenek285ee852013-12-13 06:26:10 +00002777 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
Fariborz Jahanianc1fb8622010-03-31 18:23:33 +00002778 }
Fariborz Jahanian97752f72010-03-27 19:02:17 +00002779 }
Steve Naroff3ce37a62007-12-14 23:37:57 +00002780 }
Chris Lattner390d39a2008-07-21 21:32:27 +00002781 // Check on this protocols's referenced protocols, recursively.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002782 for (auto *PI : PDecl->protocols())
2783 CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002784 CDecl, ProtocolsExplictImpl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002785}
2786
Fariborz Jahanianf9ae68a2011-07-16 00:08:33 +00002787/// MatchAllMethodDeclarations - Check methods declared in interface
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002788/// or protocol against those declared in their implementations.
2789///
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002790void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
2791 const SelectorSet &ClsMap,
2792 SelectorSet &InsMapSeen,
2793 SelectorSet &ClsMapSeen,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002794 ObjCImplDecl* IMPDecl,
2795 ObjCContainerDecl* CDecl,
2796 bool &IncompleteImpl,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002797 bool ImmediateClass,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002798 bool WarnCategoryMethodImpl) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002799 // Check and see if instance methods in class interface have been
2800 // implemented in the implementation class. If so, their types match.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002801 for (auto *I : CDecl->instance_methods()) {
David Blaikie82e95a32014-11-19 07:49:47 +00002802 if (!InsMapSeen.insert(I->getSelector()).second)
Benjamin Kramer9f8e2d72013-10-14 15:16:10 +00002803 continue;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002804 if (!I->isPropertyAccessor() &&
2805 !InsMap.count(I->getSelector())) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002806 if (ImmediateClass)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002807 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
Ted Kremenek65d63572013-03-27 00:02:21 +00002808 diag::warn_undef_method_impl);
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002809 continue;
Mike Stump12b8ce12009-08-04 21:02:39 +00002810 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002811 ObjCMethodDecl *ImpMethodDecl =
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002812 IMPDecl->getInstanceMethod(I->getSelector());
Manman Rena58f92f2016-10-11 21:18:20 +00002813 assert(CDecl->getInstanceMethod(I->getSelector(), true/*AllowHidden*/) &&
Argyrios Kyrtzidis342e08f2011-08-30 19:43:21 +00002814 "Expected to find the method through lookup as well");
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002815 // ImpMethodDecl may be null as in a @dynamic property.
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002816 if (ImpMethodDecl) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002817 if (!WarnCategoryMethodImpl)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002818 WarnConflictingTypedMethods(ImpMethodDecl, I,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002819 isa<ObjCProtocolDecl>(CDecl));
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002820 else if (!I->isPropertyAccessor())
2821 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002822 }
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002823 }
2824 }
Mike Stump11289f42009-09-09 15:08:12 +00002825
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002826 // Check and see if class methods in class interface have been
2827 // implemented in the implementation class. If so, their types match.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002828 for (auto *I : CDecl->class_methods()) {
David Blaikie82e95a32014-11-19 07:49:47 +00002829 if (!ClsMapSeen.insert(I->getSelector()).second)
Benjamin Kramer9f8e2d72013-10-14 15:16:10 +00002830 continue;
Manman Rend36f7d52016-01-27 20:10:32 +00002831 if (!I->isPropertyAccessor() &&
2832 !ClsMap.count(I->getSelector())) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002833 if (ImmediateClass)
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002834 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
Ted Kremenek65d63572013-03-27 00:02:21 +00002835 diag::warn_undef_method_impl);
Mike Stump12b8ce12009-08-04 21:02:39 +00002836 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002837 ObjCMethodDecl *ImpMethodDecl =
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002838 IMPDecl->getClassMethod(I->getSelector());
Manman Rena58f92f2016-10-11 21:18:20 +00002839 assert(CDecl->getClassMethod(I->getSelector(), true/*AllowHidden*/) &&
Argyrios Kyrtzidis342e08f2011-08-30 19:43:21 +00002840 "Expected to find the method through lookup as well");
Manman Rend36f7d52016-01-27 20:10:32 +00002841 // ImpMethodDecl may be null as in a @dynamic property.
2842 if (ImpMethodDecl) {
2843 if (!WarnCategoryMethodImpl)
2844 WarnConflictingTypedMethods(ImpMethodDecl, I,
2845 isa<ObjCProtocolDecl>(CDecl));
2846 else if (!I->isPropertyAccessor())
2847 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2848 }
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002849 }
2850 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002851
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002852 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
2853 // Also, check for methods declared in protocols inherited by
2854 // this protocol.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002855 for (auto *PI : PD->protocols())
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002856 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002857 IMPDecl, PI, IncompleteImpl, false,
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002858 WarnCategoryMethodImpl);
2859 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002860
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002861 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002862 // when checking that methods in implementation match their declaration,
2863 // i.e. when WarnCategoryMethodImpl is false, check declarations in class
2864 // extension; as well as those in categories.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002865 if (!WarnCategoryMethodImpl) {
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002866 for (auto *Cat : I->visible_categories())
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002867 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Argyrios Kyrtzidis3a437542015-10-13 23:27:34 +00002868 IMPDecl, Cat, IncompleteImpl,
2869 ImmediateClass && Cat->IsClassExtension(),
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002870 WarnCategoryMethodImpl);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002871 } else {
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002872 // Also methods in class extensions need be looked at next.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002873 for (auto *Ext : I->visible_extensions())
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002874 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002875 IMPDecl, Ext, IncompleteImpl, false,
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002876 WarnCategoryMethodImpl);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002877 }
2878
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002879 // Check for any implementation of a methods declared in protocol.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002880 for (auto *PI : I->all_referenced_protocols())
Mike Stump11289f42009-09-09 15:08:12 +00002881 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002882 IMPDecl, PI, IncompleteImpl, false,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002883 WarnCategoryMethodImpl);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002884
Fangrui Song6907ce22018-07-30 19:24:48 +00002885 // FIXME. For now, we are not checking for extact match of methods
2886 // in category implementation and its primary class's super class.
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002887 if (!WarnCategoryMethodImpl && I->getSuperClass())
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002888 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Mike Stump11289f42009-09-09 15:08:12 +00002889 IMPDecl,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002890 I->getSuperClass(), IncompleteImpl, false);
2891 }
2892}
2893
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002894/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2895/// category matches with those implemented in its primary class and
Fangrui Song6907ce22018-07-30 19:24:48 +00002896/// warns each time an exact match is found.
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002897void Sema::CheckCategoryVsClassMethodMatches(
2898 ObjCCategoryImplDecl *CatIMPDecl) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002899 // Get category's primary class.
2900 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
2901 if (!CatDecl)
2902 return;
2903 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
2904 if (!IDecl)
2905 return;
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002906 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
2907 SelectorSet InsMap, ClsMap;
Fangrui Song6907ce22018-07-30 19:24:48 +00002908
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002909 for (const auto *I : CatIMPDecl->instance_methods()) {
2910 Selector Sel = I->getSelector();
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002911 // When checking for methods implemented in the category, skip over
2912 // those declared in category class's super class. This is because
2913 // the super class must implement the method.
2914 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
2915 continue;
2916 InsMap.insert(Sel);
2917 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002918
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002919 for (const auto *I : CatIMPDecl->class_methods()) {
2920 Selector Sel = I->getSelector();
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002921 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
2922 continue;
2923 ClsMap.insert(Sel);
2924 }
2925 if (InsMap.empty() && ClsMap.empty())
2926 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00002927
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002928 SelectorSet InsMapSeen, ClsMapSeen;
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002929 bool IncompleteImpl = false;
2930 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2931 CatIMPDecl, IDecl,
Fangrui Song6907ce22018-07-30 19:24:48 +00002932 IncompleteImpl, false,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002933 true /*WarnCategoryMethodImpl*/);
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002934}
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002935
Fariborz Jahanian25491a22010-05-05 21:52:17 +00002936void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002937 ObjCContainerDecl* CDecl,
Chris Lattner9ef10f42009-03-01 00:56:52 +00002938 bool IncompleteImpl) {
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002939 SelectorSet InsMap;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002940 // Check and see if instance methods in class interface have been
2941 // implemented in the implementation class.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002942 for (const auto *I : IMPDecl->instance_methods())
2943 InsMap.insert(I->getSelector());
Mike Stump11289f42009-09-09 15:08:12 +00002944
Douglas Gregoracf4fd32015-11-03 01:15:46 +00002945 // Add the selectors for getters/setters of @dynamic properties.
2946 for (const auto *PImpl : IMPDecl->property_impls()) {
2947 // We only care about @dynamic implementations.
2948 if (PImpl->getPropertyImplementation() != ObjCPropertyImplDecl::Dynamic)
2949 continue;
2950
2951 const auto *P = PImpl->getPropertyDecl();
2952 if (!P) continue;
2953
2954 InsMap.insert(P->getGetterName());
2955 if (!P->getSetterName().isNull())
2956 InsMap.insert(P->getSetterName());
2957 }
2958
Fariborz Jahanian6c6aea92009-04-14 23:15:21 +00002959 // Check and see if properties declared in the interface have either 1)
2960 // an implementation or 2) there is a @synthesize/@dynamic implementation
2961 // of the property in the @implementation.
Ted Kremenek348e88c2014-02-21 19:41:34 +00002962 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2963 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
2964 LangOpts.ObjCRuntime.isNonFragile() &&
2965 !IDecl->isObjCRequiresPropertyDefs();
2966 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
2967 }
2968
Douglas Gregor849ebc22015-06-19 18:14:46 +00002969 // Diagnose null-resettable synthesized setters.
2970 diagnoseNullResettableSynthesizedSetters(IMPDecl);
2971
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002972 SelectorSet ClsMap;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002973 for (const auto *I : IMPDecl->class_methods())
2974 ClsMap.insert(I->getSelector());
Mike Stump11289f42009-09-09 15:08:12 +00002975
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002976 // Check for type conflict of methods declared in a class/protocol and
2977 // its implementation; if any.
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002978 SelectorSet InsMapSeen, ClsMapSeen;
Mike Stump11289f42009-09-09 15:08:12 +00002979 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2980 IMPDecl, CDecl,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002981 IncompleteImpl, true);
Fangrui Song6907ce22018-07-30 19:24:48 +00002982
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002983 // check all methods implemented in category against those declared
2984 // in its primary class.
Fangrui Song6907ce22018-07-30 19:24:48 +00002985 if (ObjCCategoryImplDecl *CatDecl =
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002986 dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
2987 CheckCategoryVsClassMethodMatches(CatDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002988
Chris Lattnerda463fe2007-12-12 07:09:47 +00002989 // Check the protocol list for unimplemented methods in the @implementation
2990 // class.
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002991 // Check and see if class methods in class interface have been
2992 // implemented in the implementation class.
Mike Stump11289f42009-09-09 15:08:12 +00002993
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002994 LazyProtocolNameSet ExplicitImplProtocols;
2995
Chris Lattner9ef10f42009-03-01 00:56:52 +00002996 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002997 for (auto *PI : I->all_referenced_protocols())
2998 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl,
2999 InsMap, ClsMap, I, ExplicitImplProtocols);
Chris Lattner9ef10f42009-03-01 00:56:52 +00003000 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahanian8764c742009-10-05 21:32:49 +00003001 // For extended class, unimplemented methods in its protocols will
3002 // be reported in the primary class.
Fariborz Jahanian30a42922010-02-15 21:55:26 +00003003 if (!C->IsClassExtension()) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003004 for (auto *P : C->protocols())
3005 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00003006 IncompleteImpl, InsMap, ClsMap, CDecl,
3007 ExplicitImplProtocols);
Ted Kremenek348e88c2014-02-21 19:41:34 +00003008 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
Nico Weber2e0c8f72014-12-27 03:58:08 +00003009 /*SynthesizeProperties=*/false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003010 }
Chris Lattner9ef10f42009-03-01 00:56:52 +00003011 } else
David Blaikie83d382b2011-09-23 05:06:16 +00003012 llvm_unreachable("invalid ObjCContainerDecl type.");
Chris Lattnerda463fe2007-12-12 07:09:47 +00003013}
3014
Fariborz Jahanian3a039e32011-08-27 20:50:59 +00003015Sema::DeclGroupPtrTy
Chris Lattnerda463fe2007-12-12 07:09:47 +00003016Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
Chris Lattner99a83312009-02-16 19:25:52 +00003017 IdentifierInfo **IdentList,
Ted Kremeneka26da852009-11-17 23:12:20 +00003018 SourceLocation *IdentLocs,
Douglas Gregor85f3f952015-07-07 03:57:15 +00003019 ArrayRef<ObjCTypeParamList *> TypeParamLists,
Chris Lattner99a83312009-02-16 19:25:52 +00003020 unsigned NumElts) {
Fariborz Jahanian3a039e32011-08-27 20:50:59 +00003021 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003022 for (unsigned i = 0; i != NumElts; ++i) {
3023 // Check for another declaration kind with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00003024 NamedDecl *PrevDecl
Fangrui Song6907ce22018-07-30 19:24:48 +00003025 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
Richard Smithbecb92d2017-10-10 22:33:17 +00003026 LookupOrdinaryName, forRedeclarationInCurContext());
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003027 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Steve Naroff946166f2008-06-05 22:57:10 +00003028 // GCC apparently allows the following idiom:
3029 //
3030 // typedef NSObject < XCElementTogglerP > XCElementToggler;
3031 // @class XCElementToggler;
3032 //
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003033 // Here we have chosen to ignore the forward class declaration
3034 // with a warning. Since this is the implied behavior.
Richard Smithdda56e42011-04-15 14:24:37 +00003035 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
John McCall8b07ec22010-05-15 11:32:37 +00003036 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003037 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
Chris Lattner0369c572008-11-23 23:12:31 +00003038 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall8b07ec22010-05-15 11:32:37 +00003039 } else {
Mike Stump12b8ce12009-08-04 21:02:39 +00003040 // a forward class declaration matching a typedef name of a class refers
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003041 // to the underlying class. Just ignore the forward class with a warning
Nico Weber2e0c8f72014-12-27 03:58:08 +00003042 // as this will force the intended behavior which is to lookup the
3043 // typedef name.
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003044 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003045 Diag(AtClassLoc, diag::warn_forward_class_redefinition)
3046 << IdentList[i];
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003047 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3048 continue;
3049 }
Fariborz Jahanian0d451812009-05-07 21:49:26 +00003050 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003051 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003052
Douglas Gregordc9166c2011-12-15 20:29:51 +00003053 // Create a declaration to describe this forward declaration.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003054 ObjCInterfaceDecl *PrevIDecl
3055 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidisdd710632013-06-18 21:26:33 +00003056
3057 IdentifierInfo *ClassName = IdentList[i];
3058 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
3059 // A previous decl with a different name is because of
3060 // @compatibility_alias, for example:
3061 // \code
3062 // @class NewImage;
3063 // @compatibility_alias OldImage NewImage;
3064 // \endcode
3065 // A lookup for 'OldImage' will return the 'NewImage' decl.
3066 //
3067 // In such a case use the real declaration name, instead of the alias one,
3068 // otherwise we will break IdentifierResolver and redecls-chain invariants.
3069 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
3070 // has been aliased.
3071 ClassName = PrevIDecl->getIdentifier();
3072 }
3073
Douglas Gregor85f3f952015-07-07 03:57:15 +00003074 // If this forward declaration has type parameters, compare them with the
3075 // type parameters of the previous declaration.
3076 ObjCTypeParamList *TypeParams = TypeParamLists[i];
3077 if (PrevIDecl && TypeParams) {
3078 if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) {
3079 // Check for consistency with the previous declaration.
3080 if (checkTypeParamListConsistency(
3081 *this, PrevTypeParams, TypeParams,
3082 TypeParamListContext::ForwardDeclaration)) {
3083 TypeParams = nullptr;
3084 }
3085 } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
3086 // The @interface does not have type parameters. Complain.
3087 Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class)
3088 << ClassName
3089 << TypeParams->getSourceRange();
3090 Diag(Def->getLocation(), diag::note_defined_here)
3091 << ClassName;
3092
3093 TypeParams = nullptr;
3094 }
3095 }
3096
Douglas Gregordc9166c2011-12-15 20:29:51 +00003097 ObjCInterfaceDecl *IDecl
3098 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00003099 ClassName, TypeParams, PrevIDecl,
3100 IdentLocs[i]);
Douglas Gregordc9166c2011-12-15 20:29:51 +00003101 IDecl->setAtEndRange(IdentLocs[i]);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003102
Douglas Gregordc9166c2011-12-15 20:29:51 +00003103 PushOnScopeChains(IDecl, TUScope);
Douglas Gregordeafd0b2011-12-27 22:43:10 +00003104 CheckObjCDeclScope(IDecl);
3105 DeclsInGroup.push_back(IDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003106 }
Rafael Espindolaab417692013-07-09 12:05:01 +00003107
Richard Smith3beb7c62017-01-12 02:27:38 +00003108 return BuildDeclaratorGroup(DeclsInGroup);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003109}
3110
John McCall54507ab2011-06-16 01:15:19 +00003111static bool tryMatchRecordTypes(ASTContext &Context,
3112 Sema::MethodMatchStrategy strategy,
3113 const Type *left, const Type *right);
3114
John McCall31168b02011-06-15 23:02:42 +00003115static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
3116 QualType leftQT, QualType rightQT) {
3117 const Type *left =
3118 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
3119 const Type *right =
3120 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
3121
3122 if (left == right) return true;
3123
3124 // If we're doing a strict match, the types have to match exactly.
3125 if (strategy == Sema::MMS_strict) return false;
3126
3127 if (left->isIncompleteType() || right->isIncompleteType()) return false;
3128
3129 // Otherwise, use this absurdly complicated algorithm to try to
3130 // validate the basic, low-level compatibility of the two types.
3131
3132 // As a minimum, require the sizes and alignments to match.
David Majnemer34b57492014-07-30 01:30:47 +00003133 TypeInfo LeftTI = Context.getTypeInfo(left);
3134 TypeInfo RightTI = Context.getTypeInfo(right);
3135 if (LeftTI.Width != RightTI.Width)
3136 return false;
3137
3138 if (LeftTI.Align != RightTI.Align)
John McCall31168b02011-06-15 23:02:42 +00003139 return false;
3140
3141 // Consider all the kinds of non-dependent canonical types:
3142 // - functions and arrays aren't possible as return and parameter types
Fangrui Song6907ce22018-07-30 19:24:48 +00003143
John McCall31168b02011-06-15 23:02:42 +00003144 // - vector types of equal size can be arbitrarily mixed
3145 if (isa<VectorType>(left)) return isa<VectorType>(right);
3146 if (isa<VectorType>(right)) return false;
3147
3148 // - references should only match references of identical type
John McCall54507ab2011-06-16 01:15:19 +00003149 // - structs, unions, and Objective-C objects must match more-or-less
3150 // exactly
John McCall31168b02011-06-15 23:02:42 +00003151 // - everything else should be a scalar
3152 if (!left->isScalarType() || !right->isScalarType())
John McCall54507ab2011-06-16 01:15:19 +00003153 return tryMatchRecordTypes(Context, strategy, left, right);
John McCall31168b02011-06-15 23:02:42 +00003154
John McCall9320b872011-09-09 05:25:32 +00003155 // Make scalars agree in kind, except count bools as chars, and group
3156 // all non-member pointers together.
John McCall31168b02011-06-15 23:02:42 +00003157 Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
3158 Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
3159 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
3160 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
John McCall9320b872011-09-09 05:25:32 +00003161 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
3162 leftSK = Type::STK_ObjCObjectPointer;
3163 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
3164 rightSK = Type::STK_ObjCObjectPointer;
John McCall31168b02011-06-15 23:02:42 +00003165
3166 // Note that data member pointers and function member pointers don't
3167 // intermix because of the size differences.
3168
3169 return (leftSK == rightSK);
3170}
Chris Lattnerda463fe2007-12-12 07:09:47 +00003171
John McCall54507ab2011-06-16 01:15:19 +00003172static bool tryMatchRecordTypes(ASTContext &Context,
3173 Sema::MethodMatchStrategy strategy,
3174 const Type *lt, const Type *rt) {
3175 assert(lt && rt && lt != rt);
3176
3177 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
3178 RecordDecl *left = cast<RecordType>(lt)->getDecl();
3179 RecordDecl *right = cast<RecordType>(rt)->getDecl();
3180
3181 // Require union-hood to match.
3182 if (left->isUnion() != right->isUnion()) return false;
3183
3184 // Require an exact match if either is non-POD.
3185 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
3186 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
3187 return false;
3188
3189 // Require size and alignment to match.
David Majnemer34b57492014-07-30 01:30:47 +00003190 TypeInfo LeftTI = Context.getTypeInfo(lt);
3191 TypeInfo RightTI = Context.getTypeInfo(rt);
3192 if (LeftTI.Width != RightTI.Width)
3193 return false;
3194
3195 if (LeftTI.Align != RightTI.Align)
3196 return false;
John McCall54507ab2011-06-16 01:15:19 +00003197
3198 // Require fields to match.
3199 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
3200 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
3201 for (; li != le && ri != re; ++li, ++ri) {
3202 if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
3203 return false;
3204 }
3205 return (li == le && ri == re);
3206}
3207
Chris Lattnerda463fe2007-12-12 07:09:47 +00003208/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
3209/// returns true, or false, accordingly.
3210/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
John McCall31168b02011-06-15 23:02:42 +00003211bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
3212 const ObjCMethodDecl *right,
3213 MethodMatchStrategy strategy) {
Alp Toker314cc812014-01-25 16:55:45 +00003214 if (!matchTypes(Context, strategy, left->getReturnType(),
3215 right->getReturnType()))
John McCall31168b02011-06-15 23:02:42 +00003216 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003217
Douglas Gregor560b7fa2013-02-07 19:13:24 +00003218 // If either is hidden, it is not considered to match.
3219 if (left->isHidden() || right->isHidden())
3220 return false;
3221
David Blaikiebbafb8a2012-03-11 07:00:24 +00003222 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003223 (left->hasAttr<NSReturnsRetainedAttr>()
3224 != right->hasAttr<NSReturnsRetainedAttr>() ||
3225 left->hasAttr<NSConsumesSelfAttr>()
3226 != right->hasAttr<NSConsumesSelfAttr>()))
3227 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003228
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00003229 ObjCMethodDecl::param_const_iterator
Douglas Gregor0bf70f42012-05-17 23:13:29 +00003230 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
3231 re = right->param_end();
Mike Stump11289f42009-09-09 15:08:12 +00003232
Douglas Gregor0bf70f42012-05-17 23:13:29 +00003233 for (; li != le && ri != re; ++li, ++ri) {
John McCall31168b02011-06-15 23:02:42 +00003234 assert(ri != right->param_end() && "Param mismatch");
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00003235 const ParmVarDecl *lparm = *li, *rparm = *ri;
John McCall31168b02011-06-15 23:02:42 +00003236
3237 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
3238 return false;
3239
David Blaikiebbafb8a2012-03-11 07:00:24 +00003240 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003241 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
3242 return false;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003243 }
3244 return true;
3245}
3246
Manman Ren71224532016-04-09 18:59:48 +00003247static bool isMethodContextSameForKindofLookup(ObjCMethodDecl *Method,
3248 ObjCMethodDecl *MethodInList) {
3249 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3250 auto *MethodInListProtocol =
3251 dyn_cast<ObjCProtocolDecl>(MethodInList->getDeclContext());
3252 // If this method belongs to a protocol but the method in list does not, or
3253 // vice versa, we say the context is not the same.
3254 if ((MethodProtocol && !MethodInListProtocol) ||
3255 (!MethodProtocol && MethodInListProtocol))
3256 return false;
3257
3258 if (MethodProtocol && MethodInListProtocol)
3259 return true;
3260
3261 ObjCInterfaceDecl *MethodInterface = Method->getClassInterface();
3262 ObjCInterfaceDecl *MethodInListInterface =
3263 MethodInList->getClassInterface();
3264 return MethodInterface == MethodInListInterface;
3265}
3266
Nico Weber2e0c8f72014-12-27 03:58:08 +00003267void Sema::addMethodToGlobalList(ObjCMethodList *List,
3268 ObjCMethodDecl *Method) {
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003269 // Record at the head of the list whether there were 0, 1, or >= 2 methods
3270 // inside categories.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003271 if (ObjCCategoryDecl *CD =
3272 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
Argyrios Kyrtzidis04703a62013-04-27 00:10:12 +00003273 if (!CD->IsClassExtension() && List->getBits() < 2)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003274 List->setBits(List->getBits() + 1);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003275
Douglas Gregorc454afe2012-01-25 00:19:56 +00003276 // If the list is empty, make it a singleton list.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003277 if (List->getMethod() == nullptr) {
3278 List->setMethod(Method);
Craig Topperc3ec1492014-05-26 06:22:03 +00003279 List->setNext(nullptr);
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003280 return;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003281 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003282
Douglas Gregorc454afe2012-01-25 00:19:56 +00003283 // We've seen a method with this name, see if we have already seen this type
3284 // signature.
3285 ObjCMethodList *Previous = List;
Manman Ren051d0b62016-04-13 23:43:56 +00003286 ObjCMethodList *ListWithSameDeclaration = nullptr;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003287 for (; List; Previous = List, List = List->getNext()) {
Douglas Gregor600a2f52013-06-21 00:20:25 +00003288 // If we are building a module, keep all of the methods.
Richard Smithbbcc9f02016-08-26 00:14:38 +00003289 if (getLangOpts().isCompilingModule())
Douglas Gregor600a2f52013-06-21 00:20:25 +00003290 continue;
3291
Manman Ren051d0b62016-04-13 23:43:56 +00003292 bool SameDeclaration = MatchTwoMethodDeclarations(Method,
3293 List->getMethod());
Manman Ren71224532016-04-09 18:59:48 +00003294 // Looking for method with a type bound requires the correct context exists.
Manman Ren051d0b62016-04-13 23:43:56 +00003295 // We need to insert a method into the list if the context is different.
3296 // If the method's declaration matches the list
3297 // a> the method belongs to a different context: we need to insert it, in
3298 // order to emit the availability message, we need to prioritize over
3299 // availability among the methods with the same declaration.
3300 // b> the method belongs to the same context: there is no need to insert a
3301 // new entry.
3302 // If the method's declaration does not match the list, we insert it to the
3303 // end.
3304 if (!SameDeclaration ||
Manman Ren71224532016-04-09 18:59:48 +00003305 !isMethodContextSameForKindofLookup(Method, List->getMethod())) {
Fariborz Jahaniand436b2a2015-04-07 16:56:27 +00003306 // Even if two method types do not match, we would like to say
3307 // there is more than one declaration so unavailability/deprecated
3308 // warning is not too noisy.
3309 if (!Method->isDefined())
3310 List->setHasMoreThanOneDecl(true);
Manman Ren051d0b62016-04-13 23:43:56 +00003311
3312 // For methods with the same declaration, the one that is deprecated
3313 // should be put in the front for better diagnostics.
3314 if (Method->isDeprecated() && SameDeclaration &&
3315 !ListWithSameDeclaration && !List->getMethod()->isDeprecated())
3316 ListWithSameDeclaration = List;
3317
3318 if (Method->isUnavailable() && SameDeclaration &&
3319 !ListWithSameDeclaration &&
3320 List->getMethod()->getAvailability() < AR_Deprecated)
3321 ListWithSameDeclaration = List;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003322 continue;
Fariborz Jahaniand436b2a2015-04-07 16:56:27 +00003323 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003324
3325 ObjCMethodDecl *PrevObjCMethod = List->getMethod();
Douglas Gregorc454afe2012-01-25 00:19:56 +00003326
3327 // Propagate the 'defined' bit.
3328 if (Method->isDefined())
3329 PrevObjCMethod->setDefined(true);
Nico Webere3b11042014-12-27 07:09:37 +00003330 else {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003331 // Objective-C doesn't allow an @interface for a class after its
3332 // @implementation. So if Method is not defined and there already is
3333 // an entry for this type signature, Method has to be for a different
3334 // class than PrevObjCMethod.
3335 List->setHasMoreThanOneDecl(true);
3336 }
3337
Douglas Gregorc454afe2012-01-25 00:19:56 +00003338 // If a method is deprecated, push it in the global pool.
3339 // This is used for better diagnostics.
3340 if (Method->isDeprecated()) {
3341 if (!PrevObjCMethod->isDeprecated())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003342 List->setMethod(Method);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003343 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003344 // If the new method is unavailable, push it into global pool
Douglas Gregorc454afe2012-01-25 00:19:56 +00003345 // unless previous one is deprecated.
3346 if (Method->isUnavailable()) {
3347 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003348 List->setMethod(Method);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003349 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003350
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003351 return;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003352 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003353
Douglas Gregorc454afe2012-01-25 00:19:56 +00003354 // We have a new signature for an existing method - add it.
3355 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
Douglas Gregore1716012012-01-25 00:49:42 +00003356 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
Manman Ren71224532016-04-09 18:59:48 +00003357
Manman Ren051d0b62016-04-13 23:43:56 +00003358 // We insert it right before ListWithSameDeclaration.
3359 if (ListWithSameDeclaration) {
3360 auto *List = new (Mem) ObjCMethodList(*ListWithSameDeclaration);
3361 // FIXME: should we clear the other bits in ListWithSameDeclaration?
3362 ListWithSameDeclaration->setMethod(Method);
3363 ListWithSameDeclaration->setNext(List);
Manman Ren71224532016-04-09 18:59:48 +00003364 return;
3365 }
3366
Nico Weber2e0c8f72014-12-27 03:58:08 +00003367 Previous->setNext(new (Mem) ObjCMethodList(Method));
Douglas Gregorc454afe2012-01-25 00:19:56 +00003368}
3369
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003370/// Read the contents of the method pool for a given selector from
Sebastian Redl75d8a322010-08-02 23:18:59 +00003371/// external storage.
Douglas Gregore1716012012-01-25 00:49:42 +00003372void Sema::ReadMethodPool(Selector Sel) {
Douglas Gregorc78d3462009-04-24 21:10:55 +00003373 assert(ExternalSource && "We need an external AST source");
Douglas Gregore1716012012-01-25 00:49:42 +00003374 ExternalSource->ReadMethodPool(Sel);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003375}
3376
Manman Rena0f31a02016-04-29 19:04:05 +00003377void Sema::updateOutOfDateSelector(Selector Sel) {
3378 if (!ExternalSource)
3379 return;
3380 ExternalSource->updateOutOfDateSelector(Sel);
3381}
3382
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003383void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
Sebastian Redl75d8a322010-08-02 23:18:59 +00003384 bool instance) {
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00003385 // Ignore methods of invalid containers.
3386 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003387 return;
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00003388
Douglas Gregor70f449b2012-01-25 00:59:09 +00003389 if (ExternalSource)
3390 ReadMethodPool(Method->getSelector());
Fangrui Song6907ce22018-07-30 19:24:48 +00003391
Sebastian Redl75d8a322010-08-02 23:18:59 +00003392 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
Douglas Gregor70f449b2012-01-25 00:59:09 +00003393 if (Pos == MethodPool.end())
3394 Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
3395 GlobalMethods())).first;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003396
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003397 Method->setDefined(impl);
Fangrui Song6907ce22018-07-30 19:24:48 +00003398
Sebastian Redl75d8a322010-08-02 23:18:59 +00003399 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003400 addMethodToGlobalList(&Entry, Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003401}
3402
John McCall31168b02011-06-15 23:02:42 +00003403/// Determines if this is an "acceptable" loose mismatch in the global
3404/// method pool. This exists mostly as a hack to get around certain
3405/// global mismatches which we can't afford to make warnings / errors.
3406/// Really, what we want is a way to take a method out of the global
3407/// method pool.
3408static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
3409 ObjCMethodDecl *other) {
3410 if (!chosen->isInstanceMethod())
3411 return false;
3412
3413 Selector sel = chosen->getSelector();
3414 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
3415 return false;
3416
3417 // Don't complain about mismatches for -length if the method we
3418 // chose has an integral result type.
Alp Toker314cc812014-01-25 16:55:45 +00003419 return (chosen->getReturnType()->isIntegerType());
John McCall31168b02011-06-15 23:02:42 +00003420}
3421
Manman Ren7ed4f982016-04-07 19:32:24 +00003422/// Return true if the given method is wthin the type bound.
3423static bool FilterMethodsByTypeBound(ObjCMethodDecl *Method,
3424 const ObjCObjectType *TypeBound) {
3425 if (!TypeBound)
3426 return true;
3427
3428 if (TypeBound->isObjCId())
3429 // FIXME: should we handle the case of bounding to id<A, B> differently?
3430 return true;
3431
3432 auto *BoundInterface = TypeBound->getInterface();
3433 assert(BoundInterface && "unexpected object type!");
3434
3435 // Check if the Method belongs to a protocol. We should allow any method
3436 // defined in any protocol, because any subclass could adopt the protocol.
3437 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3438 if (MethodProtocol) {
3439 return true;
3440 }
3441
3442 // If the Method belongs to a class, check if it belongs to the class
3443 // hierarchy of the class bound.
3444 if (ObjCInterfaceDecl *MethodInterface = Method->getClassInterface()) {
3445 // We allow methods declared within classes that are part of the hierarchy
3446 // of the class bound (superclass of, subclass of, or the same as the class
3447 // bound).
3448 return MethodInterface == BoundInterface ||
3449 MethodInterface->isSuperClassOf(BoundInterface) ||
3450 BoundInterface->isSuperClassOf(MethodInterface);
3451 }
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003452 llvm_unreachable("unknown method context");
Manman Ren7ed4f982016-04-07 19:32:24 +00003453}
3454
Manman Rend2a3cd72016-04-07 19:30:20 +00003455/// We first select the type of the method: Instance or Factory, then collect
3456/// all methods with that type.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003457bool Sema::CollectMultipleMethodsInGlobalPool(
Manman Rend2a3cd72016-04-07 19:30:20 +00003458 Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods,
Manman Ren7ed4f982016-04-07 19:32:24 +00003459 bool InstanceFirst, bool CheckTheOther,
3460 const ObjCObjectType *TypeBound) {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003461 if (ExternalSource)
3462 ReadMethodPool(Sel);
3463
3464 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3465 if (Pos == MethodPool.end())
3466 return false;
Manman Rend2a3cd72016-04-07 19:30:20 +00003467
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003468 // Gather the non-hidden methods.
Manman Rend2a3cd72016-04-07 19:30:20 +00003469 ObjCMethodList &MethList = InstanceFirst ? Pos->second.first :
3470 Pos->second.second;
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003471 for (ObjCMethodList *M = &MethList; M; M = M->getNext())
Manman Ren7ed4f982016-04-07 19:32:24 +00003472 if (M->getMethod() && !M->getMethod()->isHidden()) {
3473 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3474 Methods.push_back(M->getMethod());
3475 }
Manman Rend2a3cd72016-04-07 19:30:20 +00003476
3477 // Return if we find any method with the desired kind.
3478 if (!Methods.empty())
3479 return Methods.size() > 1;
3480
3481 if (!CheckTheOther)
3482 return false;
3483
3484 // Gather the other kind.
3485 ObjCMethodList &MethList2 = InstanceFirst ? Pos->second.second :
3486 Pos->second.first;
3487 for (ObjCMethodList *M = &MethList2; M; M = M->getNext())
Manman Ren7ed4f982016-04-07 19:32:24 +00003488 if (M->getMethod() && !M->getMethod()->isHidden()) {
3489 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3490 Methods.push_back(M->getMethod());
3491 }
Manman Rend2a3cd72016-04-07 19:30:20 +00003492
Nico Weber2e0c8f72014-12-27 03:58:08 +00003493 return Methods.size() > 1;
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003494}
3495
Manman Rend2a3cd72016-04-07 19:30:20 +00003496bool Sema::AreMultipleMethodsInGlobalPool(
3497 Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R,
3498 bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl *> &Methods) {
3499 // Diagnose finding more than one method in global pool.
3500 SmallVector<ObjCMethodDecl *, 4> FilteredMethods;
3501 FilteredMethods.push_back(BestMethod);
3502
3503 for (auto *M : Methods)
3504 if (M != BestMethod && !M->hasAttr<UnavailableAttr>())
3505 FilteredMethods.push_back(M);
3506
3507 if (FilteredMethods.size() > 1)
3508 DiagnoseMultipleMethodInGlobalPool(FilteredMethods, Sel, R,
3509 receiverIdOrClass);
3510
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003511 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
Nico Weber2e0c8f72014-12-27 03:58:08 +00003512 // Test for no method in the pool which should not trigger any warning by
3513 // caller.
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003514 if (Pos == MethodPool.end())
3515 return true;
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003516 ObjCMethodList &MethList =
3517 BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003518 return MethList.hasMoreThanOneDecl();
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003519}
3520
Sebastian Redl75d8a322010-08-02 23:18:59 +00003521ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00003522 bool receiverIdOrClass,
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003523 bool instance) {
Douglas Gregor70f449b2012-01-25 00:59:09 +00003524 if (ExternalSource)
3525 ReadMethodPool(Sel);
Fangrui Song6907ce22018-07-30 19:24:48 +00003526
Sebastian Redl75d8a322010-08-02 23:18:59 +00003527 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
Douglas Gregor70f449b2012-01-25 00:59:09 +00003528 if (Pos == MethodPool.end())
Craig Topperc3ec1492014-05-26 06:22:03 +00003529 return nullptr;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003530
Douglas Gregor77f49a42013-01-16 18:47:38 +00003531 // Gather the non-hidden methods.
Sebastian Redl75d8a322010-08-02 23:18:59 +00003532 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00003533 SmallVector<ObjCMethodDecl *, 4> Methods;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003534 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003535 if (M->getMethod() && !M->getMethod()->isHidden())
3536 return M->getMethod();
Douglas Gregorc78d3462009-04-24 21:10:55 +00003537 }
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003538 return nullptr;
3539}
Douglas Gregor77f49a42013-01-16 18:47:38 +00003540
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003541void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3542 Selector Sel, SourceRange R,
3543 bool receiverIdOrClass) {
Douglas Gregor77f49a42013-01-16 18:47:38 +00003544 // We found multiple methods, so we may have to complain.
3545 bool issueDiagnostic = false, issueError = false;
Jonathan Roelofs74411362015-04-28 18:04:44 +00003546
Douglas Gregor77f49a42013-01-16 18:47:38 +00003547 // We support a warning which complains about *any* difference in
3548 // method signature.
3549 bool strictSelectorMatch =
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003550 receiverIdOrClass &&
3551 !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
Douglas Gregor77f49a42013-01-16 18:47:38 +00003552 if (strictSelectorMatch) {
3553 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3554 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
3555 issueDiagnostic = true;
3556 break;
3557 }
3558 }
3559 }
Jonathan Roelofs74411362015-04-28 18:04:44 +00003560
Douglas Gregor77f49a42013-01-16 18:47:38 +00003561 // If we didn't see any strict differences, we won't see any loose
3562 // differences. In ARC, however, we also need to check for loose
3563 // mismatches, because most of them are errors.
3564 if (!strictSelectorMatch ||
3565 (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
3566 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3567 // This checks if the methods differ in type mismatch.
3568 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
3569 !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
3570 issueDiagnostic = true;
3571 if (getLangOpts().ObjCAutoRefCount)
3572 issueError = true;
3573 break;
3574 }
3575 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003576
Douglas Gregor77f49a42013-01-16 18:47:38 +00003577 if (issueDiagnostic) {
3578 if (issueError)
3579 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
3580 else if (strictSelectorMatch)
3581 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
3582 else
3583 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
Fangrui Song6907ce22018-07-30 19:24:48 +00003584
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003585 Diag(Methods[0]->getBeginLoc(),
Douglas Gregor77f49a42013-01-16 18:47:38 +00003586 issueError ? diag::note_possibility : diag::note_using)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003587 << Methods[0]->getSourceRange();
Douglas Gregor77f49a42013-01-16 18:47:38 +00003588 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003589 Diag(Methods[I]->getBeginLoc(), diag::note_also_found)
3590 << Methods[I]->getSourceRange();
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003591 }
Douglas Gregor77f49a42013-01-16 18:47:38 +00003592 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003593}
3594
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003595ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
Sebastian Redl75d8a322010-08-02 23:18:59 +00003596 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3597 if (Pos == MethodPool.end())
Craig Topperc3ec1492014-05-26 06:22:03 +00003598 return nullptr;
Sebastian Redl75d8a322010-08-02 23:18:59 +00003599
3600 GlobalMethods &Methods = Pos->second;
Fariborz Jahanianec762bd2014-03-26 20:59:26 +00003601 for (const ObjCMethodList *Method = &Methods.first; Method;
3602 Method = Method->getNext())
Fariborz Jahanian4019c7f2015-02-19 21:52:41 +00003603 if (Method->getMethod() &&
3604 (Method->getMethod()->isDefined() ||
3605 Method->getMethod()->isPropertyAccessor()))
Nico Weber2e0c8f72014-12-27 03:58:08 +00003606 return Method->getMethod();
Fangrui Song6907ce22018-07-30 19:24:48 +00003607
Fariborz Jahanianec762bd2014-03-26 20:59:26 +00003608 for (const ObjCMethodList *Method = &Methods.second; Method;
3609 Method = Method->getNext())
Fariborz Jahanian4019c7f2015-02-19 21:52:41 +00003610 if (Method->getMethod() &&
3611 (Method->getMethod()->isDefined() ||
3612 Method->getMethod()->isPropertyAccessor()))
Nico Weber2e0c8f72014-12-27 03:58:08 +00003613 return Method->getMethod();
Craig Topperc3ec1492014-05-26 06:22:03 +00003614 return nullptr;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003615}
3616
Fariborz Jahanian42f89382013-05-30 21:48:58 +00003617static void
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003618HelperSelectorsForTypoCorrection(
3619 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
3620 StringRef Typo, const ObjCMethodDecl * Method) {
3621 const unsigned MaxEditDistance = 1;
3622 unsigned BestEditDistance = MaxEditDistance + 1;
Richard Trieuea8d3702013-06-06 02:22:29 +00003623 std::string MethodName = Method->getSelector().getAsString();
Fangrui Song6907ce22018-07-30 19:24:48 +00003624
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003625 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
3626 if (MinPossibleEditDistance > 0 &&
3627 Typo.size() / MinPossibleEditDistance < 1)
3628 return;
3629 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
3630 if (EditDistance > MaxEditDistance)
3631 return;
3632 if (EditDistance == BestEditDistance)
3633 BestMethod.push_back(Method);
3634 else if (EditDistance < BestEditDistance) {
3635 BestMethod.clear();
3636 BestMethod.push_back(Method);
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003637 }
3638}
3639
Fariborz Jahanian75481672013-06-17 17:10:54 +00003640static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
3641 QualType ObjectType) {
3642 if (ObjectType.isNull())
3643 return true;
3644 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
3645 return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003646 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
3647 nullptr;
Fariborz Jahanian75481672013-06-17 17:10:54 +00003648}
3649
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003650const ObjCMethodDecl *
Fariborz Jahanian75481672013-06-17 17:10:54 +00003651Sema::SelectorsForTypoCorrection(Selector Sel,
3652 QualType ObjectType) {
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003653 unsigned NumArgs = Sel.getNumArgs();
3654 SmallVector<const ObjCMethodDecl *, 8> Methods;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003655 bool ObjectIsId = true, ObjectIsClass = true;
3656 if (ObjectType.isNull())
3657 ObjectIsId = ObjectIsClass = false;
3658 else if (!ObjectType->isObjCObjectPointerType())
Craig Topperc3ec1492014-05-26 06:22:03 +00003659 return nullptr;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003660 else if (const ObjCObjectPointerType *ObjCPtr =
3661 ObjectType->getAsObjCInterfacePointerType()) {
3662 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
3663 ObjectIsId = ObjectIsClass = false;
3664 }
3665 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
3666 ObjectIsClass = false;
3667 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
3668 ObjectIsId = false;
3669 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003670 return nullptr;
3671
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003672 for (GlobalMethodPool::iterator b = MethodPool.begin(),
3673 e = MethodPool.end(); b != e; b++) {
3674 // instance methods
3675 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003676 if (M->getMethod() &&
3677 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3678 (M->getMethod()->getSelector() != Sel)) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003679 if (ObjectIsId)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003680 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003681 else if (!ObjectIsClass &&
Nico Weber2e0c8f72014-12-27 03:58:08 +00003682 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3683 ObjectType))
3684 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003685 }
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003686 // class methods
3687 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003688 if (M->getMethod() &&
3689 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3690 (M->getMethod()->getSelector() != Sel)) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003691 if (ObjectIsClass)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003692 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003693 else if (!ObjectIsId &&
Nico Weber2e0c8f72014-12-27 03:58:08 +00003694 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3695 ObjectType))
3696 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003697 }
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003698 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003699
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003700 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
3701 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
3702 HelperSelectorsForTypoCorrection(SelectedMethods,
3703 Sel.getAsString(), Methods[i]);
3704 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003705 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003706}
3707
Fariborz Jahanian42f89382013-05-30 21:48:58 +00003708/// DiagnoseDuplicateIvars -
Fangrui Song6907ce22018-07-30 19:24:48 +00003709/// Check for duplicate ivars in the entire class at the start of
James Dennett634962f2012-06-14 21:40:34 +00003710/// \@implementation. This becomes necesssary because class extension can
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003711/// add ivars to a class in random order which will not be known until
James Dennett634962f2012-06-14 21:40:34 +00003712/// class's \@implementation is seen.
Fangrui Song6907ce22018-07-30 19:24:48 +00003713void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003714 ObjCInterfaceDecl *SID) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00003715 for (auto *Ivar : ID->ivars()) {
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003716 if (Ivar->isInvalidDecl())
3717 continue;
3718 if (IdentifierInfo *II = Ivar->getIdentifier()) {
3719 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
3720 if (prevIvar) {
3721 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3722 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
3723 Ivar->setInvalidDecl();
3724 }
3725 }
3726 }
3727}
3728
John McCallb61e14e2015-10-27 04:54:50 +00003729/// Diagnose attempts to define ARC-__weak ivars when __weak is disabled.
3730static void DiagnoseWeakIvars(Sema &S, ObjCImplementationDecl *ID) {
3731 if (S.getLangOpts().ObjCWeak) return;
3732
3733 for (auto ivar = ID->getClassInterface()->all_declared_ivar_begin();
3734 ivar; ivar = ivar->getNextIvar()) {
3735 if (ivar->isInvalidDecl()) continue;
3736 if (ivar->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
3737 if (S.getLangOpts().ObjCWeakRuntime) {
3738 S.Diag(ivar->getLocation(), diag::err_arc_weak_disabled);
3739 } else {
3740 S.Diag(ivar->getLocation(), diag::err_arc_weak_no_runtime);
3741 }
3742 }
3743 }
3744}
3745
Volodymyr Sapsai30680e92017-10-23 22:01:41 +00003746/// Diagnose attempts to use flexible array member with retainable object type.
3747static void DiagnoseRetainableFlexibleArrayMember(Sema &S,
3748 ObjCInterfaceDecl *ID) {
3749 if (!S.getLangOpts().ObjCAutoRefCount)
3750 return;
3751
3752 for (auto ivar = ID->all_declared_ivar_begin(); ivar;
3753 ivar = ivar->getNextIvar()) {
3754 if (ivar->isInvalidDecl())
3755 continue;
3756 QualType IvarTy = ivar->getType();
3757 if (IvarTy->isIncompleteArrayType() &&
3758 (IvarTy.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) &&
3759 IvarTy->isObjCLifetimeType()) {
3760 S.Diag(ivar->getLocation(), diag::err_flexible_array_arc_retainable);
3761 ivar->setInvalidDecl();
3762 }
3763 }
3764}
3765
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003766Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
3767 switch (CurContext->getDeclKind()) {
3768 case Decl::ObjCInterface:
3769 return Sema::OCK_Interface;
3770 case Decl::ObjCProtocol:
3771 return Sema::OCK_Protocol;
3772 case Decl::ObjCCategory:
Benjamin Kramera008d3a2015-04-10 11:37:55 +00003773 if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003774 return Sema::OCK_ClassExtension;
Benjamin Kramera008d3a2015-04-10 11:37:55 +00003775 return Sema::OCK_Category;
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003776 case Decl::ObjCImplementation:
3777 return Sema::OCK_Implementation;
3778 case Decl::ObjCCategoryImpl:
3779 return Sema::OCK_CategoryImplementation;
3780
3781 default:
3782 return Sema::OCK_None;
3783 }
3784}
3785
Volodymyr Sapsai30680e92017-10-23 22:01:41 +00003786static bool IsVariableSizedType(QualType T) {
3787 if (T->isIncompleteArrayType())
3788 return true;
3789 const auto *RecordTy = T->getAs<RecordType>();
3790 return (RecordTy && RecordTy->getDecl()->hasFlexibleArrayMember());
3791}
3792
3793static void DiagnoseVariableSizedIvars(Sema &S, ObjCContainerDecl *OCD) {
3794 ObjCInterfaceDecl *IntfDecl = nullptr;
3795 ObjCInterfaceDecl::ivar_range Ivars = llvm::make_range(
3796 ObjCInterfaceDecl::ivar_iterator(), ObjCInterfaceDecl::ivar_iterator());
3797 if ((IntfDecl = dyn_cast<ObjCInterfaceDecl>(OCD))) {
3798 Ivars = IntfDecl->ivars();
3799 } else if (auto *ImplDecl = dyn_cast<ObjCImplementationDecl>(OCD)) {
3800 IntfDecl = ImplDecl->getClassInterface();
3801 Ivars = ImplDecl->ivars();
3802 } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(OCD)) {
3803 if (CategoryDecl->IsClassExtension()) {
3804 IntfDecl = CategoryDecl->getClassInterface();
3805 Ivars = CategoryDecl->ivars();
3806 }
3807 }
3808
3809 // Check if variable sized ivar is in interface and visible to subclasses.
3810 if (!isa<ObjCInterfaceDecl>(OCD)) {
3811 for (auto ivar : Ivars) {
3812 if (!ivar->isInvalidDecl() && IsVariableSizedType(ivar->getType())) {
3813 S.Diag(ivar->getLocation(), diag::warn_variable_sized_ivar_visibility)
3814 << ivar->getDeclName() << ivar->getType();
3815 }
3816 }
3817 }
3818
3819 // Subsequent checks require interface decl.
3820 if (!IntfDecl)
3821 return;
3822
3823 // Check if variable sized ivar is followed by another ivar.
3824 for (ObjCIvarDecl *ivar = IntfDecl->all_declared_ivar_begin(); ivar;
3825 ivar = ivar->getNextIvar()) {
3826 if (ivar->isInvalidDecl() || !ivar->getNextIvar())
3827 continue;
3828 QualType IvarTy = ivar->getType();
3829 bool IsInvalidIvar = false;
3830 if (IvarTy->isIncompleteArrayType()) {
3831 S.Diag(ivar->getLocation(), diag::err_flexible_array_not_at_end)
3832 << ivar->getDeclName() << IvarTy
3833 << TTK_Class; // Use "class" for Obj-C.
3834 IsInvalidIvar = true;
3835 } else if (const RecordType *RecordTy = IvarTy->getAs<RecordType>()) {
3836 if (RecordTy->getDecl()->hasFlexibleArrayMember()) {
3837 S.Diag(ivar->getLocation(),
3838 diag::err_objc_variable_sized_type_not_at_end)
3839 << ivar->getDeclName() << IvarTy;
3840 IsInvalidIvar = true;
3841 }
3842 }
3843 if (IsInvalidIvar) {
3844 S.Diag(ivar->getNextIvar()->getLocation(),
3845 diag::note_next_ivar_declaration)
3846 << ivar->getNextIvar()->getSynthesize();
3847 ivar->setInvalidDecl();
3848 }
3849 }
3850
3851 // Check if ObjC container adds ivars after variable sized ivar in superclass.
3852 // Perform the check only if OCD is the first container to declare ivars to
3853 // avoid multiple warnings for the same ivar.
3854 ObjCIvarDecl *FirstIvar =
3855 (Ivars.begin() == Ivars.end()) ? nullptr : *Ivars.begin();
3856 if (FirstIvar && (FirstIvar == IntfDecl->all_declared_ivar_begin())) {
3857 const ObjCInterfaceDecl *SuperClass = IntfDecl->getSuperClass();
3858 while (SuperClass && SuperClass->ivar_empty())
3859 SuperClass = SuperClass->getSuperClass();
3860 if (SuperClass) {
3861 auto IvarIter = SuperClass->ivar_begin();
3862 std::advance(IvarIter, SuperClass->ivar_size() - 1);
3863 const ObjCIvarDecl *LastIvar = *IvarIter;
3864 if (IsVariableSizedType(LastIvar->getType())) {
3865 S.Diag(FirstIvar->getLocation(),
3866 diag::warn_superclass_variable_sized_type_not_at_end)
3867 << FirstIvar->getDeclName() << LastIvar->getDeclName()
3868 << LastIvar->getType() << SuperClass->getDeclName();
3869 S.Diag(LastIvar->getLocation(), diag::note_entity_declared_at)
3870 << LastIvar->getDeclName();
3871 }
3872 }
3873 }
3874}
3875
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003876// Note: For class/category implementations, allMethods is always null.
Robert Wilhelm57c67112013-07-17 21:14:35 +00003877Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
Fariborz Jahaniandfb76872013-07-17 00:05:08 +00003878 ArrayRef<DeclGroupPtrTy> allTUVars) {
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003879 if (getObjCContainerKind() == Sema::OCK_None)
Craig Topperc3ec1492014-05-26 06:22:03 +00003880 return nullptr;
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003881
3882 assert(AtEnd.isValid() && "Invalid location for '@end'");
3883
George Burgess IV00f70bd2018-03-01 05:43:23 +00003884 auto *OCD = cast<ObjCContainerDecl>(CurContext);
3885 Decl *ClassDecl = OCD;
3886
Mike Stump11289f42009-09-09 15:08:12 +00003887 bool isInterfaceDeclKind =
Chris Lattner219b3e92008-03-16 21:17:37 +00003888 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
3889 || isa<ObjCProtocolDecl>(ClassDecl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003890 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
Steve Naroffb3a87982009-01-09 15:36:25 +00003891
Steve Naroff35c62ae2009-01-08 17:28:14 +00003892 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
3893 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
3894 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
3895
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003896 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003897 ObjCMethodDecl *Method =
John McCall48871652010-08-21 09:40:31 +00003898 cast_or_null<ObjCMethodDecl>(allMethods[i]);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003899
3900 if (!Method) continue; // Already issued a diagnostic.
Douglas Gregorffca3a22009-01-09 17:18:27 +00003901 if (Method->isInstanceMethod()) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00003902 /// Check for instance method of the same name with incompatible types
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003903 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
Mike Stump11289f42009-09-09 15:08:12 +00003904 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
Chris Lattnerda463fe2007-12-12 07:09:47 +00003905 : false;
Mike Stump11289f42009-09-09 15:08:12 +00003906 if ((isInterfaceDeclKind && PrevMethod && !match)
Eli Friedman42b1e9e2008-12-16 20:15:50 +00003907 || (checkIdenticalMethods && match)) {
Chris Lattner0369c572008-11-23 23:12:31 +00003908 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00003909 << Method->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003910 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Douglas Gregor87e92752010-12-21 17:34:17 +00003911 Method->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00003912 } else {
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003913 if (PrevMethod) {
Argyrios Kyrtzidisdcaaa212011-10-14 08:02:31 +00003914 Method->setAsRedeclaration(PrevMethod);
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003915 if (!Context.getSourceManager().isInSystemHeader(
3916 Method->getLocation()))
3917 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3918 << Method->getDeclName();
3919 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3920 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003921 InsMap[Method->getSelector()] = Method;
3922 /// The following allows us to typecheck messages to "id".
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003923 AddInstanceMethodToGlobalPool(Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003924 }
Mike Stump12b8ce12009-08-04 21:02:39 +00003925 } else {
Chris Lattnerda463fe2007-12-12 07:09:47 +00003926 /// Check for class method of the same name with incompatible types
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003927 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
Mike Stump11289f42009-09-09 15:08:12 +00003928 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
Chris Lattnerda463fe2007-12-12 07:09:47 +00003929 : false;
Mike Stump11289f42009-09-09 15:08:12 +00003930 if ((isInterfaceDeclKind && PrevMethod && !match)
Eli Friedman42b1e9e2008-12-16 20:15:50 +00003931 || (checkIdenticalMethods && match)) {
Chris Lattner0369c572008-11-23 23:12:31 +00003932 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00003933 << Method->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003934 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Douglas Gregor87e92752010-12-21 17:34:17 +00003935 Method->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00003936 } else {
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003937 if (PrevMethod) {
Argyrios Kyrtzidisdcaaa212011-10-14 08:02:31 +00003938 Method->setAsRedeclaration(PrevMethod);
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003939 if (!Context.getSourceManager().isInSystemHeader(
3940 Method->getLocation()))
3941 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3942 << Method->getDeclName();
3943 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3944 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003945 ClsMap[Method->getSelector()] = Method;
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003946 AddFactoryMethodToGlobalPool(Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003947 }
3948 }
3949 }
Douglas Gregorb8982092013-01-21 19:42:21 +00003950 if (isa<ObjCInterfaceDecl>(ClassDecl)) {
3951 // Nothing to do here.
Steve Naroffb3a87982009-01-09 15:36:25 +00003952 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
Fariborz Jahanian62293f42008-12-06 19:59:02 +00003953 // Categories are used to extend the class by declaring new methods.
Mike Stump11289f42009-09-09 15:08:12 +00003954 // By the same token, they are also used to add new properties. No
Fariborz Jahanian62293f42008-12-06 19:59:02 +00003955 // need to compare the added property to those in the class.
Daniel Dunbar4684f372008-08-27 05:40:03 +00003956
Fariborz Jahanianc21f5432010-12-10 23:36:33 +00003957 if (C->IsClassExtension()) {
3958 ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
3959 DiagnoseClassExtensionDupMethods(C, CCPrimary);
Fariborz Jahanianc21f5432010-12-10 23:36:33 +00003960 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003961 }
Steve Naroffb3a87982009-01-09 15:36:25 +00003962 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
Fariborz Jahanian30a42922010-02-15 21:55:26 +00003963 if (CDecl->getIdentifier())
3964 // ProcessPropertyDecl is responsible for diagnosing conflicts with any
3965 // user-defined setter/getter. It also synthesizes setter/getter methods
3966 // and adds them to the DeclContext and global method pools.
Manman Renefe1bac2016-01-27 20:00:32 +00003967 for (auto *I : CDecl->properties())
Douglas Gregore17765e2015-11-03 17:02:34 +00003968 ProcessPropertyDecl(I);
Ted Kremenekc7c64312010-01-07 01:20:12 +00003969 CDecl->setAtEndRange(AtEnd);
Steve Naroffb3a87982009-01-09 15:36:25 +00003970 }
3971 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
Ted Kremenekc7c64312010-01-07 01:20:12 +00003972 IC->setAtEndRange(AtEnd);
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00003973 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003974 // Any property declared in a class extension might have user
3975 // declared setter or getter in current class extension or one
3976 // of the other class extensions. Mark them as synthesized as
3977 // property will be synthesized when property with same name is
3978 // seen in the @implementation.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00003979 for (const auto *Ext : IDecl->visible_extensions()) {
Manman Rena7a8b1f2016-01-26 18:05:23 +00003980 for (const auto *Property : Ext->instance_properties()) {
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003981 // Skip over properties declared @dynamic
3982 if (const ObjCPropertyImplDecl *PIDecl
Manman Ren5b786402016-01-28 18:49:28 +00003983 = IC->FindPropertyImplDecl(Property->getIdentifier(),
3984 Property->getQueryKind()))
Fangrui Song6907ce22018-07-30 19:24:48 +00003985 if (PIDecl->getPropertyImplementation()
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003986 == ObjCPropertyImplDecl::Dynamic)
3987 continue;
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003988
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00003989 for (const auto *Ext : IDecl->visible_extensions()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003990 if (ObjCMethodDecl *GetterMethod
3991 = Ext->getInstanceMethod(Property->getGetterName()))
Jordan Rosed01e83a2012-10-10 16:42:25 +00003992 GetterMethod->setPropertyAccessor(true);
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003993 if (!Property->isReadOnly())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003994 if (ObjCMethodDecl *SetterMethod
3995 = Ext->getInstanceMethod(Property->getSetterName()))
Jordan Rosed01e83a2012-10-10 16:42:25 +00003996 SetterMethod->setPropertyAccessor(true);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003997 }
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003998 }
3999 }
Fariborz Jahanian25491a22010-05-05 21:52:17 +00004000 ImplMethodsVsClassMethods(S, IC, IDecl);
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00004001 AtomicPropertySetterGetterRules(IC, IDecl);
John McCall31168b02011-06-15 23:02:42 +00004002 DiagnoseOwningPropertyGetterSynthesis(IC);
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004003 DiagnoseUnusedBackingIvarInAccessor(S, IC);
Fariborz Jahanian20cfff32015-03-11 16:59:48 +00004004 if (IDecl->hasDesignatedInitializers())
4005 DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
John McCallb61e14e2015-10-27 04:54:50 +00004006 DiagnoseWeakIvars(*this, IC);
Volodymyr Sapsai30680e92017-10-23 22:01:41 +00004007 DiagnoseRetainableFlexibleArrayMember(*this, IDecl);
Argyrios Kyrtzidisdb5ce0f2013-12-03 21:11:54 +00004008
Patrick Beardacfbe9e2012-04-06 18:12:22 +00004009 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
Craig Topperc3ec1492014-05-26 06:22:03 +00004010 if (IDecl->getSuperClass() == nullptr) {
Patrick Beardacfbe9e2012-04-06 18:12:22 +00004011 // This class has no superclass, so check that it has been marked with
4012 // __attribute((objc_root_class)).
4013 if (!HasRootClassAttr) {
4014 SourceLocation DeclLoc(IDecl->getLocation());
Alp Tokerb6cc5922014-05-03 03:45:55 +00004015 SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
Patrick Beardacfbe9e2012-04-06 18:12:22 +00004016 Diag(DeclLoc, diag::warn_objc_root_class_missing)
4017 << IDecl->getIdentifier();
4018 // See if NSObject is in the current scope, and if it is, suggest
4019 // adding " : NSObject " to the class declaration.
4020 NamedDecl *IF = LookupSingleName(TUScope,
4021 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
4022 DeclLoc, LookupOrdinaryName);
4023 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
4024 if (NSObjectDecl && NSObjectDecl->getDefinition()) {
4025 Diag(SuperClassLoc, diag::note_objc_needs_superclass)
4026 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
4027 } else {
4028 Diag(SuperClassLoc, diag::note_objc_needs_superclass);
4029 }
4030 }
4031 } else if (HasRootClassAttr) {
4032 // Complain that only root classes may have this attribute.
4033 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
4034 }
4035
Alex Lorenza8c44ba2016-10-28 10:25:10 +00004036 if (const ObjCInterfaceDecl *Super = IDecl->getSuperClass()) {
4037 // An interface can subclass another interface with a
4038 // objc_subclassing_restricted attribute when it has that attribute as
4039 // well (because of interfaces imported from Swift). Therefore we have
4040 // to check if we can subclass in the implementation as well.
4041 if (IDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
4042 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
4043 Diag(IC->getLocation(), diag::err_restricted_superclass_mismatch);
4044 Diag(Super->getLocation(), diag::note_class_declared);
4045 }
4046 }
4047
John McCall5fb5df92012-06-20 06:18:46 +00004048 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian545643c2010-02-23 23:41:11 +00004049 while (IDecl->getSuperClass()) {
4050 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
4051 IDecl = IDecl->getSuperClass();
4052 }
Patrick Beardacfbe9e2012-04-06 18:12:22 +00004053 }
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00004054 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004055 SetIvarInitializers(IC);
Mike Stump11289f42009-09-09 15:08:12 +00004056 } else if (ObjCCategoryImplDecl* CatImplClass =
Steve Naroffb3a87982009-01-09 15:36:25 +00004057 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
Ted Kremenekc7c64312010-01-07 01:20:12 +00004058 CatImplClass->setAtEndRange(AtEnd);
Mike Stump11289f42009-09-09 15:08:12 +00004059
Chris Lattnerda463fe2007-12-12 07:09:47 +00004060 // Find category interface decl and then check that all methods declared
Daniel Dunbar4684f372008-08-27 05:40:03 +00004061 // in this interface are implemented in the category @implementation.
Chris Lattner41fd42e2009-02-16 18:32:47 +00004062 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00004063 if (ObjCCategoryDecl *Cat
4064 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
4065 ImplMethodsVsClassMethods(S, CatImplClass, Cat);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004066 }
4067 }
Alex Lorenza8c44ba2016-10-28 10:25:10 +00004068 } else if (const auto *IntfDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
4069 if (const ObjCInterfaceDecl *Super = IntfDecl->getSuperClass()) {
4070 if (!IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
4071 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
4072 Diag(IntfDecl->getLocation(), diag::err_restricted_superclass_mismatch);
4073 Diag(Super->getLocation(), diag::note_class_declared);
4074 }
4075 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00004076 }
Volodymyr Sapsai30680e92017-10-23 22:01:41 +00004077 DiagnoseVariableSizedIvars(*this, OCD);
Chris Lattner5bbb3c82009-03-29 16:50:03 +00004078 if (isInterfaceDeclKind) {
4079 // Reject invalid vardecls.
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00004080 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00004081 DeclGroupRef DG = allTUVars[i].get();
Chris Lattner5bbb3c82009-03-29 16:50:03 +00004082 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
4083 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
Daniel Dunbar0ca16602009-04-14 02:25:56 +00004084 if (!VDecl->hasExternalStorage())
Steve Naroff42959b22009-04-13 17:58:46 +00004085 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
Fariborz Jahanian629aed92009-03-21 18:06:45 +00004086 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00004087 }
Fariborz Jahanian3654e652009-03-18 22:33:24 +00004088 }
Fariborz Jahanian4327b322011-08-29 17:33:12 +00004089 ActOnObjCContainerFinishDefinition();
Argyrios Kyrtzidisbd8b1502011-10-17 19:48:13 +00004090
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00004091 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00004092 DeclGroupRef DG = allTUVars[i].get();
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004093 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
4094 (*I)->setTopLevelDeclInObjCContainer();
Argyrios Kyrtzidisbd8b1502011-10-17 19:48:13 +00004095 Consumer.HandleTopLevelDeclInObjCContainer(DG);
4096 }
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00004097
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +00004098 ActOnDocumentableDecl(ClassDecl);
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00004099 return ClassDecl;
Chris Lattnerda463fe2007-12-12 07:09:47 +00004100}
4101
Chris Lattnerda463fe2007-12-12 07:09:47 +00004102/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
4103/// objective-c's type qualifier from the parser version of the same info.
Mike Stump11289f42009-09-09 15:08:12 +00004104static Decl::ObjCDeclQualifier
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004105CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
John McCallca872902011-05-01 03:04:29 +00004106 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
Chris Lattnerda463fe2007-12-12 07:09:47 +00004107}
4108
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004109/// Check whether the declared result type of the given Objective-C
Douglas Gregor33823722011-06-11 01:09:30 +00004110/// method declaration is compatible with the method's class.
4111///
Fangrui Song6907ce22018-07-30 19:24:48 +00004112static Sema::ResultTypeCompatibilityKind
Douglas Gregor33823722011-06-11 01:09:30 +00004113CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
4114 ObjCInterfaceDecl *CurrentClass) {
Alp Toker314cc812014-01-25 16:55:45 +00004115 QualType ResultType = Method->getReturnType();
4116
Fangrui Song6907ce22018-07-30 19:24:48 +00004117 // If an Objective-C method inherits its related result type, then its
Douglas Gregor33823722011-06-11 01:09:30 +00004118 // declared result type must be compatible with its own class type. The
4119 // declared result type is compatible if:
4120 if (const ObjCObjectPointerType *ResultObjectType
4121 = ResultType->getAs<ObjCObjectPointerType>()) {
4122 // - it is id or qualified id, or
4123 if (ResultObjectType->isObjCIdType() ||
4124 ResultObjectType->isObjCQualifiedIdType())
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004125 return Sema::RTC_Compatible;
Fangrui Song6907ce22018-07-30 19:24:48 +00004126
Douglas Gregor33823722011-06-11 01:09:30 +00004127 if (CurrentClass) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004128 if (ObjCInterfaceDecl *ResultClass
Douglas Gregor33823722011-06-11 01:09:30 +00004129 = ResultObjectType->getInterfaceDecl()) {
4130 // - it is the same as the method's class type, or
Douglas Gregor0b144e12011-12-15 00:29:59 +00004131 if (declaresSameEntity(CurrentClass, ResultClass))
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004132 return Sema::RTC_Compatible;
Fangrui Song6907ce22018-07-30 19:24:48 +00004133
Douglas Gregor33823722011-06-11 01:09:30 +00004134 // - it is a superclass of the method's class type
4135 if (ResultClass->isSuperClassOf(CurrentClass))
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004136 return Sema::RTC_Compatible;
Fangrui Song6907ce22018-07-30 19:24:48 +00004137 }
Douglas Gregorbab8a962011-09-08 01:46:34 +00004138 } else {
4139 // Any Objective-C pointer type might be acceptable for a protocol
4140 // method; we just don't know.
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004141 return Sema::RTC_Unknown;
Douglas Gregor33823722011-06-11 01:09:30 +00004142 }
4143 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004144
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004145 return Sema::RTC_Incompatible;
Douglas Gregor33823722011-06-11 01:09:30 +00004146}
4147
John McCalld2930c22011-07-22 02:45:48 +00004148namespace {
4149/// A helper class for searching for methods which a particular method
4150/// overrides.
4151class OverrideSearch {
Daniel Dunbard6d74c32012-02-29 03:04:05 +00004152public:
John McCalld2930c22011-07-22 02:45:48 +00004153 Sema &S;
4154 ObjCMethodDecl *Method;
Akira Hatanaka4c687f32018-02-06 23:44:40 +00004155 llvm::SmallSetVector<ObjCMethodDecl*, 4> Overridden;
John McCalld2930c22011-07-22 02:45:48 +00004156 bool Recursive;
4157
4158public:
4159 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
4160 Selector selector = method->getSelector();
4161
4162 // Bypass this search if we've never seen an instance/class method
4163 // with this selector before.
4164 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
4165 if (it == S.MethodPool.end()) {
Axel Naumanndd433f02012-10-18 19:05:02 +00004166 if (!S.getExternalSource()) return;
Douglas Gregore1716012012-01-25 00:49:42 +00004167 S.ReadMethodPool(selector);
Fangrui Song6907ce22018-07-30 19:24:48 +00004168
Douglas Gregore1716012012-01-25 00:49:42 +00004169 it = S.MethodPool.find(selector);
4170 if (it == S.MethodPool.end())
4171 return;
John McCalld2930c22011-07-22 02:45:48 +00004172 }
4173 ObjCMethodList &list =
4174 method->isInstanceMethod() ? it->second.first : it->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00004175 if (!list.getMethod()) return;
John McCalld2930c22011-07-22 02:45:48 +00004176
4177 ObjCContainerDecl *container
4178 = cast<ObjCContainerDecl>(method->getDeclContext());
4179
4180 // Prevent the search from reaching this container again. This is
4181 // important with categories, which override methods from the
4182 // interface and each other.
Douglas Gregorcf4ac442012-05-03 21:25:24 +00004183 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) {
4184 searchFromContainer(container);
Douglas Gregorc5928af2012-05-17 22:39:14 +00004185 if (ObjCInterfaceDecl *Interface = Category->getClassInterface())
4186 searchFromContainer(Interface);
Douglas Gregorcf4ac442012-05-03 21:25:24 +00004187 } else {
4188 searchFromContainer(container);
4189 }
Douglas Gregor33823722011-06-11 01:09:30 +00004190 }
John McCalld2930c22011-07-22 02:45:48 +00004191
Akira Hatanaka4c687f32018-02-06 23:44:40 +00004192 typedef decltype(Overridden)::iterator iterator;
John McCalld2930c22011-07-22 02:45:48 +00004193 iterator begin() const { return Overridden.begin(); }
4194 iterator end() const { return Overridden.end(); }
4195
4196private:
4197 void searchFromContainer(ObjCContainerDecl *container) {
4198 if (container->isInvalidDecl()) return;
4199
4200 switch (container->getDeclKind()) {
4201#define OBJCCONTAINER(type, base) \
4202 case Decl::type: \
4203 searchFrom(cast<type##Decl>(container)); \
4204 break;
4205#define ABSTRACT_DECL(expansion)
4206#define DECL(type, base) \
4207 case Decl::type:
4208#include "clang/AST/DeclNodes.inc"
4209 llvm_unreachable("not an ObjC container!");
4210 }
4211 }
4212
4213 void searchFrom(ObjCProtocolDecl *protocol) {
Douglas Gregore6e48b12012-01-01 19:29:29 +00004214 if (!protocol->hasDefinition())
4215 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00004216
John McCalld2930c22011-07-22 02:45:48 +00004217 // A method in a protocol declaration overrides declarations from
4218 // referenced ("parent") protocols.
4219 search(protocol->getReferencedProtocols());
4220 }
4221
4222 void searchFrom(ObjCCategoryDecl *category) {
4223 // A method in a category declaration overrides declarations from
4224 // the main class and from protocols the category references.
Douglas Gregorcf4ac442012-05-03 21:25:24 +00004225 // The main class is handled in the constructor.
John McCalld2930c22011-07-22 02:45:48 +00004226 search(category->getReferencedProtocols());
4227 }
4228
4229 void searchFrom(ObjCCategoryImplDecl *impl) {
4230 // A method in a category definition that has a category
4231 // declaration overrides declarations from the category
4232 // declaration.
4233 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
4234 search(category);
Douglas Gregorc5928af2012-05-17 22:39:14 +00004235 if (ObjCInterfaceDecl *Interface = category->getClassInterface())
4236 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00004237
4238 // Otherwise it overrides declarations from the class.
Douglas Gregorc5928af2012-05-17 22:39:14 +00004239 } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) {
4240 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00004241 }
4242 }
4243
4244 void searchFrom(ObjCInterfaceDecl *iface) {
4245 // A method in a class declaration overrides declarations from
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00004246 if (!iface->hasDefinition())
4247 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00004248
John McCalld2930c22011-07-22 02:45:48 +00004249 // - categories,
Aaron Ballman15063e12014-03-13 21:35:02 +00004250 for (auto *Cat : iface->known_categories())
4251 search(Cat);
John McCalld2930c22011-07-22 02:45:48 +00004252
4253 // - the super class, and
4254 if (ObjCInterfaceDecl *super = iface->getSuperClass())
4255 search(super);
4256
4257 // - any referenced protocols.
4258 search(iface->getReferencedProtocols());
4259 }
4260
4261 void searchFrom(ObjCImplementationDecl *impl) {
4262 // A method in a class implementation overrides declarations from
4263 // the class interface.
Douglas Gregorc5928af2012-05-17 22:39:14 +00004264 if (ObjCInterfaceDecl *Interface = impl->getClassInterface())
4265 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00004266 }
4267
John McCalld2930c22011-07-22 02:45:48 +00004268 void search(const ObjCProtocolList &protocols) {
4269 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
4270 i != e; ++i)
4271 search(*i);
4272 }
4273
4274 void search(ObjCContainerDecl *container) {
John McCalld2930c22011-07-22 02:45:48 +00004275 // Check for a method in this container which matches this selector.
4276 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
Argyrios Kyrtzidisbd8cd3e2013-03-29 21:51:48 +00004277 Method->isInstanceMethod(),
4278 /*AllowHidden=*/true);
John McCalld2930c22011-07-22 02:45:48 +00004279
4280 // If we find one, record it and bail out.
4281 if (meth) {
4282 Overridden.insert(meth);
4283 return;
4284 }
4285
4286 // Otherwise, search for methods that a hypothetical method here
4287 // would have overridden.
4288
4289 // Note that we're now in a recursive case.
4290 Recursive = true;
4291
4292 searchFromContainer(container);
4293 }
4294};
Hans Wennborgdcfba332015-10-06 23:40:43 +00004295} // end anonymous namespace
Douglas Gregor33823722011-06-11 01:09:30 +00004296
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004297void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
4298 ObjCInterfaceDecl *CurrentClass,
4299 ResultTypeCompatibilityKind RTC) {
4300 // Search for overridden methods and merge information down from them.
4301 OverrideSearch overrides(*this, ObjCMethod);
4302 // Keep track if the method overrides any method in the class's base classes,
4303 // its protocols, or its categories' protocols; we will keep that info
4304 // in the ObjCMethodDecl.
4305 // For this info, a method in an implementation is not considered as
4306 // overriding the same method in the interface or its categories.
4307 bool hasOverriddenMethodsInBaseOrProtocol = false;
4308 for (OverrideSearch::iterator
4309 i = overrides.begin(), e = overrides.end(); i != e; ++i) {
4310 ObjCMethodDecl *overridden = *i;
4311
Argyrios Kyrtzidisc2091d52013-04-17 00:09:08 +00004312 if (!hasOverriddenMethodsInBaseOrProtocol) {
4313 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
4314 CurrentClass != overridden->getClassInterface() ||
4315 overridden->isOverriding()) {
4316 hasOverriddenMethodsInBaseOrProtocol = true;
4317
4318 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
4319 // OverrideSearch will return as "overridden" the same method in the
4320 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
4321 // check whether a category of a base class introduced a method with the
4322 // same selector, after the interface method declaration.
4323 // To avoid unnecessary lookups in the majority of cases, we use the
4324 // extra info bits in GlobalMethodPool to check whether there were any
4325 // category methods with this selector.
4326 GlobalMethodPool::iterator It =
4327 MethodPool.find(ObjCMethod->getSelector());
4328 if (It != MethodPool.end()) {
4329 ObjCMethodList &List =
4330 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
4331 unsigned CategCount = List.getBits();
4332 if (CategCount > 0) {
4333 // If the method is in a category we'll do lookup if there were at
4334 // least 2 category methods recorded, otherwise only one will do.
4335 if (CategCount > 1 ||
4336 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
4337 OverrideSearch overrides(*this, overridden);
4338 for (OverrideSearch::iterator
4339 OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) {
4340 ObjCMethodDecl *SuperOverridden = *OI;
Argyrios Kyrtzidis04703a62013-04-27 00:10:12 +00004341 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
4342 CurrentClass != SuperOverridden->getClassInterface()) {
Argyrios Kyrtzidisc2091d52013-04-17 00:09:08 +00004343 hasOverriddenMethodsInBaseOrProtocol = true;
4344 overridden->setOverriding(true);
4345 break;
4346 }
4347 }
4348 }
4349 }
4350 }
4351 }
4352 }
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004353
4354 // Propagate down the 'related result type' bit from overridden methods.
4355 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
Erich Keane9b18eca2018-08-01 21:31:08 +00004356 ObjCMethod->setRelatedResultType();
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004357
4358 // Then merge the declarations.
4359 mergeObjCMethodDecls(ObjCMethod, overridden);
4360
4361 if (ObjCMethod->isImplicit() && overridden->isImplicit())
4362 continue; // Conflicting properties are detected elsewhere.
4363
4364 // Check for overriding methods
Fangrui Song6907ce22018-07-30 19:24:48 +00004365 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004366 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
4367 CheckConflictingOverridingMethod(ObjCMethod, overridden,
4368 isa<ObjCProtocolDecl>(overridden->getDeclContext()));
Fangrui Song6907ce22018-07-30 19:24:48 +00004369
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004370 if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
Fariborz Jahanian31a25682012-07-05 22:26:07 +00004371 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
4372 !overridden->isImplicit() /* not meant for properties */) {
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004373 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
4374 E = ObjCMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +00004375 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
4376 PrevE = overridden->param_end();
4377 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004378 assert(PrevI != overridden->param_end() && "Param mismatch");
4379 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
4380 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
4381 // If type of argument of method in this class does not match its
4382 // respective argument type in the super class method, issue warning;
4383 if (!Context.typesAreCompatible(T1, T2)) {
4384 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
4385 << T1 << T2;
4386 Diag(overridden->getLocation(), diag::note_previous_declaration);
4387 break;
4388 }
4389 }
4390 }
4391 }
4392
4393 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
4394}
4395
Douglas Gregor813a0662015-06-19 18:14:38 +00004396/// Merge type nullability from for a redeclaration of the same entity,
4397/// producing the updated type of the redeclared entity.
4398static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc,
4399 QualType type,
4400 bool usesCSKeyword,
4401 SourceLocation prevLoc,
4402 QualType prevType,
4403 bool prevUsesCSKeyword) {
4404 // Determine the nullability of both types.
4405 auto nullability = type->getNullability(S.Context);
4406 auto prevNullability = prevType->getNullability(S.Context);
4407
4408 // Easy case: both have nullability.
4409 if (nullability.hasValue() == prevNullability.hasValue()) {
4410 // Neither has nullability; continue.
4411 if (!nullability)
4412 return type;
4413
4414 // The nullabilities are equivalent; do nothing.
4415 if (*nullability == *prevNullability)
4416 return type;
4417
4418 // Complain about mismatched nullability.
4419 S.Diag(loc, diag::err_nullability_conflicting)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00004420 << DiagNullabilityKind(*nullability, usesCSKeyword)
4421 << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword);
Douglas Gregor813a0662015-06-19 18:14:38 +00004422 return type;
4423 }
4424
4425 // If it's the redeclaration that has nullability, don't change anything.
4426 if (nullability)
4427 return type;
4428
4429 // Otherwise, provide the result with the same nullability.
4430 return S.Context.getAttributedType(
4431 AttributedType::getNullabilityAttrKind(*prevNullability),
4432 type, type);
4433}
4434
NAKAMURA Takumi2df5c3c2015-06-20 03:52:52 +00004435/// Merge information from the declaration of a method in the \@interface
Douglas Gregor813a0662015-06-19 18:14:38 +00004436/// (or a category/extension) into the corresponding method in the
4437/// @implementation (for a class or category).
4438static void mergeInterfaceMethodToImpl(Sema &S,
4439 ObjCMethodDecl *method,
4440 ObjCMethodDecl *prevMethod) {
4441 // Merge the objc_requires_super attribute.
4442 if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() &&
4443 !method->hasAttr<ObjCRequiresSuperAttr>()) {
4444 // merge the attribute into implementation.
4445 method->addAttr(
4446 ObjCRequiresSuperAttr::CreateImplicit(S.Context,
4447 method->getLocation()));
4448 }
4449
4450 // Merge nullability of the result type.
4451 QualType newReturnType
4452 = mergeTypeNullabilityForRedecl(
4453 S, method->getReturnTypeSourceRange().getBegin(),
4454 method->getReturnType(),
4455 method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4456 prevMethod->getReturnTypeSourceRange().getBegin(),
4457 prevMethod->getReturnType(),
4458 prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4459 method->setReturnType(newReturnType);
4460
4461 // Handle each of the parameters.
4462 unsigned numParams = method->param_size();
4463 unsigned numPrevParams = prevMethod->param_size();
4464 for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) {
4465 ParmVarDecl *param = method->param_begin()[i];
4466 ParmVarDecl *prevParam = prevMethod->param_begin()[i];
4467
4468 // Merge nullability.
4469 QualType newParamType
4470 = mergeTypeNullabilityForRedecl(
4471 S, param->getLocation(), param->getType(),
4472 param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4473 prevParam->getLocation(), prevParam->getType(),
4474 prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4475 param->setType(newParamType);
4476 }
4477}
4478
Alex Lorenza8a372d2017-04-27 10:43:48 +00004479/// Verify that the method parameters/return value have types that are supported
4480/// by the x86 target.
4481static void checkObjCMethodX86VectorTypes(Sema &SemaRef,
4482 const ObjCMethodDecl *Method) {
4483 assert(SemaRef.getASTContext().getTargetInfo().getTriple().getArch() ==
4484 llvm::Triple::x86 &&
4485 "x86-specific check invoked for a different target");
4486 SourceLocation Loc;
4487 QualType T;
4488 for (const ParmVarDecl *P : Method->parameters()) {
4489 if (P->getType()->isVectorType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004490 Loc = P->getBeginLoc();
Alex Lorenza8a372d2017-04-27 10:43:48 +00004491 T = P->getType();
4492 break;
4493 }
4494 }
4495 if (Loc.isInvalid()) {
4496 if (Method->getReturnType()->isVectorType()) {
4497 Loc = Method->getReturnTypeSourceRange().getBegin();
4498 T = Method->getReturnType();
4499 } else
4500 return;
4501 }
4502
4503 // Vector parameters/return values are not supported by objc_msgSend on x86 in
4504 // iOS < 9 and macOS < 10.11.
4505 const auto &Triple = SemaRef.getASTContext().getTargetInfo().getTriple();
4506 VersionTuple AcceptedInVersion;
4507 if (Triple.getOS() == llvm::Triple::IOS)
4508 AcceptedInVersion = VersionTuple(/*Major=*/9);
4509 else if (Triple.isMacOSX())
4510 AcceptedInVersion = VersionTuple(/*Major=*/10, /*Minor=*/11);
4511 else
4512 return;
Alex Lorenza8a372d2017-04-27 10:43:48 +00004513 if (SemaRef.getASTContext().getTargetInfo().getPlatformMinVersion() >=
Alex Lorenz92824832017-05-05 16:15:17 +00004514 AcceptedInVersion)
Alex Lorenza8a372d2017-04-27 10:43:48 +00004515 return;
4516 SemaRef.Diag(Loc, diag::err_objc_method_unsupported_param_ret_type)
4517 << T << (Method->getReturnType()->isVectorType() ? /*return value*/ 1
4518 : /*parameter*/ 0)
4519 << (Triple.isMacOSX() ? "macOS 10.11" : "iOS 9");
4520}
4521
John McCall48871652010-08-21 09:40:31 +00004522Decl *Sema::ActOnMethodDeclaration(
Erich Keanec480f302018-07-12 21:09:05 +00004523 Scope *S, SourceLocation MethodLoc, SourceLocation EndLoc,
4524 tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
4525 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
Chris Lattnerda463fe2007-12-12 07:09:47 +00004526 // optional arguments. The number of types/arguments is obtained
4527 // from the Sel.getNumArgs().
Erich Keanec480f302018-07-12 21:09:05 +00004528 ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
4529 unsigned CNumArgs, // c-style args
4530 const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodDeclKind,
Fariborz Jahanianc677f692011-03-12 18:54:30 +00004531 bool isVariadic, bool MethodDefinition) {
Steve Naroff83777fe2008-02-29 21:48:07 +00004532 // Make sure we can establish a context for the method.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004533 if (!CurContext->isObjCContainer()) {
Richard Smithf8812672016-12-02 22:38:31 +00004534 Diag(MethodLoc, diag::err_missing_method_context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004535 return nullptr;
Steve Naroff83777fe2008-02-29 21:48:07 +00004536 }
George Burgess IV00f70bd2018-03-01 05:43:23 +00004537 Decl *ClassDecl = cast<ObjCContainerDecl>(CurContext);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004538 QualType resultDeclType;
Mike Stump11289f42009-09-09 15:08:12 +00004539
Douglas Gregorbab8a962011-09-08 01:46:34 +00004540 bool HasRelatedResultType = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00004541 TypeSourceInfo *ReturnTInfo = nullptr;
Steve Naroff32606412009-02-20 22:59:16 +00004542 if (ReturnType) {
Alp Toker314cc812014-01-25 16:55:45 +00004543 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004544
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004545 if (CheckFunctionReturnType(resultDeclType, MethodLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00004546 return nullptr;
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004547
Douglas Gregor813a0662015-06-19 18:14:38 +00004548 QualType bareResultType = resultDeclType;
4549 (void)AttributedType::stripOuterNullability(bareResultType);
4550 HasRelatedResultType = (bareResultType == Context.getObjCInstanceType());
Fariborz Jahanianb5a52ca2011-07-21 17:00:47 +00004551 } else { // get the type for "id".
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004552 resultDeclType = Context.getObjCIdType();
Fariborz Jahanianb21138f2011-07-21 17:38:14 +00004553 Diag(MethodLoc, diag::warn_missing_method_return_type)
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004554 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
Fariborz Jahanianb5a52ca2011-07-21 17:00:47 +00004555 }
Mike Stump11289f42009-09-09 15:08:12 +00004556
Alp Toker314cc812014-01-25 16:55:45 +00004557 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
4558 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
4559 MethodType == tok::minus, isVariadic,
4560 /*isPropertyAccessor=*/false,
4561 /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
4562 MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
4563 : ObjCMethodDecl::Required,
4564 HasRelatedResultType);
Mike Stump11289f42009-09-09 15:08:12 +00004565
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004566 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump11289f42009-09-09 15:08:12 +00004567
Chris Lattner23b0faf2009-04-11 19:42:43 +00004568 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
John McCall856bbea2009-10-23 21:48:59 +00004569 QualType ArgType;
John McCallbcd03502009-12-07 02:54:59 +00004570 TypeSourceInfo *DI;
Mike Stump11289f42009-09-09 15:08:12 +00004571
David Blaikie7d170102013-05-15 07:37:26 +00004572 if (!ArgInfo[i].Type) {
John McCall856bbea2009-10-23 21:48:59 +00004573 ArgType = Context.getObjCIdType();
Craig Topperc3ec1492014-05-26 06:22:03 +00004574 DI = nullptr;
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004575 } else {
John McCall856bbea2009-10-23 21:48:59 +00004576 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004577 }
Mike Stump11289f42009-09-09 15:08:12 +00004578
Fangrui Song6907ce22018-07-30 19:24:48 +00004579 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
Richard Smithbecb92d2017-10-10 22:33:17 +00004580 LookupOrdinaryName, forRedeclarationInCurContext());
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004581 LookupName(R, S);
4582 if (R.isSingleResult()) {
4583 NamedDecl *PrevDecl = R.getFoundDecl();
4584 if (S->isDeclScope(PrevDecl)) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004585 Diag(ArgInfo[i].NameLoc,
4586 (MethodDefinition ? diag::warn_method_param_redefinition
4587 : diag::warn_method_param_declaration))
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004588 << ArgInfo[i].Name;
Fangrui Song6907ce22018-07-30 19:24:48 +00004589 Diag(PrevDecl->getLocation(),
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004590 diag::note_previous_declaration);
4591 }
4592 }
4593
Abramo Bagnaradff19302011-03-08 08:55:46 +00004594 SourceLocation StartLoc = DI
4595 ? DI->getTypeLoc().getBeginLoc()
4596 : ArgInfo[i].NameLoc;
4597
John McCalld44f4d72011-04-23 02:46:06 +00004598 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
4599 ArgInfo[i].NameLoc, ArgInfo[i].Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004600 ArgType, DI, SC_None);
Mike Stump11289f42009-09-09 15:08:12 +00004601
John McCall82490832011-05-02 00:30:12 +00004602 Param->setObjCMethodScopeInfo(i);
4603
Chris Lattnerc5ffed42008-04-04 06:12:32 +00004604 Param->setObjCDeclQualifier(
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004605 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
Mike Stump11289f42009-09-09 15:08:12 +00004606
Chris Lattner9713a1c2009-04-11 19:34:56 +00004607 // Apply the attributes to the parameter.
Douglas Gregor758a8692009-06-17 21:51:59 +00004608 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00004609 AddPragmaAttributes(TUScope, Param);
Mike Stump11289f42009-09-09 15:08:12 +00004610
Fariborz Jahanian52d02f62012-01-14 18:44:35 +00004611 if (Param->hasAttr<BlocksAttr>()) {
4612 Diag(Param->getLocation(), diag::err_block_on_nonlocal);
4613 Param->setInvalidDecl();
4614 }
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004615 S->AddDecl(Param);
4616 IdResolver.AddDecl(Param);
4617
Chris Lattnerc5ffed42008-04-04 06:12:32 +00004618 Params.push_back(Param);
4619 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004620
Fariborz Jahanian60462092010-04-08 00:30:06 +00004621 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +00004622 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
Fariborz Jahanian60462092010-04-08 00:30:06 +00004623 QualType ArgType = Param->getType();
4624 if (ArgType.isNull())
4625 ArgType = Context.getObjCIdType();
4626 else
4627 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
Douglas Gregor84280642011-07-12 04:42:08 +00004628 ArgType = Context.getAdjustedParameterType(ArgType);
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004629
Fariborz Jahanian60462092010-04-08 00:30:06 +00004630 Param->setDeclContext(ObjCMethod);
Fariborz Jahanian60462092010-04-08 00:30:06 +00004631 Params.push_back(Param);
4632 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004633
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004634 ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004635 ObjCMethod->setObjCDeclQualifier(
4636 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
Daniel Dunbarc136e0c2008-09-26 04:12:28 +00004637
Erich Keanec480f302018-07-12 21:09:05 +00004638 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00004639 AddPragmaAttributes(TUScope, ObjCMethod);
Mike Stump11289f42009-09-09 15:08:12 +00004640
Douglas Gregor87e92752010-12-21 17:34:17 +00004641 // Add the method now.
Craig Topperc3ec1492014-05-26 06:22:03 +00004642 const ObjCMethodDecl *PrevMethod = nullptr;
John McCalld2930c22011-07-22 02:45:48 +00004643 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00004644 if (MethodType == tok::minus) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004645 PrevMethod = ImpDecl->getInstanceMethod(Sel);
4646 ImpDecl->addInstanceMethod(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004647 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004648 PrevMethod = ImpDecl->getClassMethod(Sel);
4649 ImpDecl->addClassMethod(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004650 }
Douglas Gregor33823722011-06-11 01:09:30 +00004651
Douglas Gregor813a0662015-06-19 18:14:38 +00004652 // Merge information from the @interface declaration into the
4653 // @implementation.
4654 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) {
4655 if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
4656 ObjCMethod->isInstanceMethod())) {
4657 mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD);
4658
4659 // Warn about defining -dealloc in a category.
4660 if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() &&
4661 ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) {
4662 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
4663 << ObjCMethod->getDeclName();
4664 }
4665 }
Akira Hatanakaa6b5e002018-07-28 04:06:13 +00004666
4667 // Warn if a method declared in a protocol to which a category or
4668 // extension conforms is non-escaping and the implementation's method is
4669 // escaping.
4670 for (auto *C : IDecl->visible_categories())
4671 for (auto &P : C->protocols())
4672 if (auto *IMD = P->lookupMethod(ObjCMethod->getSelector(),
4673 ObjCMethod->isInstanceMethod())) {
4674 assert(ObjCMethod->parameters().size() ==
4675 IMD->parameters().size() &&
4676 "Methods have different number of parameters");
4677 auto OI = IMD->param_begin(), OE = IMD->param_end();
4678 auto NI = ObjCMethod->param_begin();
4679 for (; OI != OE; ++OI, ++NI)
4680 diagnoseNoescape(*NI, *OI, C, P, *this);
4681 }
Fariborz Jahanian7e350d22013-12-17 22:44:28 +00004682 }
Douglas Gregor87e92752010-12-21 17:34:17 +00004683 } else {
4684 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004685 }
John McCalld2930c22011-07-22 02:45:48 +00004686
Chris Lattnerda463fe2007-12-12 07:09:47 +00004687 if (PrevMethod) {
4688 // You can never have two method definitions with the same name.
Chris Lattner0369c572008-11-23 23:12:31 +00004689 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00004690 << ObjCMethod->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00004691 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian096f7c12013-05-13 17:27:00 +00004692 ObjCMethod->setInvalidDecl();
4693 return ObjCMethod;
Mike Stump11289f42009-09-09 15:08:12 +00004694 }
John McCall28a6aea2009-11-04 02:18:39 +00004695
Douglas Gregor33823722011-06-11 01:09:30 +00004696 // If this Objective-C method does not have a related result type, but we
4697 // are allowed to infer related result types, try to do so based on the
4698 // method family.
4699 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
4700 if (!CurrentClass) {
4701 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
4702 CurrentClass = Cat->getClassInterface();
4703 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
4704 CurrentClass = Impl->getClassInterface();
4705 else if (ObjCCategoryImplDecl *CatImpl
4706 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
4707 CurrentClass = CatImpl->getClassInterface();
4708 }
John McCalld2930c22011-07-22 02:45:48 +00004709
Douglas Gregorbab8a962011-09-08 01:46:34 +00004710 ResultTypeCompatibilityKind RTC
4711 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
John McCalld2930c22011-07-22 02:45:48 +00004712
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004713 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
John McCalld2930c22011-07-22 02:45:48 +00004714
John McCall31168b02011-06-15 23:02:42 +00004715 bool ARCError = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004716 if (getLangOpts().ObjCAutoRefCount)
John McCalle48f3892013-04-04 01:38:37 +00004717 ARCError = CheckARCMethodDecl(ObjCMethod);
John McCall31168b02011-06-15 23:02:42 +00004718
Douglas Gregorbab8a962011-09-08 01:46:34 +00004719 // Infer the related result type when possible.
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004720 if (!ARCError && RTC == Sema::RTC_Compatible &&
Douglas Gregorbab8a962011-09-08 01:46:34 +00004721 !ObjCMethod->hasRelatedResultType() &&
4722 LangOpts.ObjCInferRelatedResultType) {
Douglas Gregor33823722011-06-11 01:09:30 +00004723 bool InferRelatedResultType = false;
4724 switch (ObjCMethod->getMethodFamily()) {
4725 case OMF_None:
4726 case OMF_copy:
4727 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +00004728 case OMF_finalize:
Douglas Gregor33823722011-06-11 01:09:30 +00004729 case OMF_mutableCopy:
4730 case OMF_release:
4731 case OMF_retainCount:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00004732 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00004733 case OMF_performSelector:
Douglas Gregor33823722011-06-11 01:09:30 +00004734 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004735
Douglas Gregor33823722011-06-11 01:09:30 +00004736 case OMF_alloc:
4737 case OMF_new:
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00004738 InferRelatedResultType = ObjCMethod->isClassMethod();
Douglas Gregor33823722011-06-11 01:09:30 +00004739 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004740
Douglas Gregor33823722011-06-11 01:09:30 +00004741 case OMF_init:
4742 case OMF_autorelease:
4743 case OMF_retain:
4744 case OMF_self:
4745 InferRelatedResultType = ObjCMethod->isInstanceMethod();
4746 break;
4747 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004748
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00004749 if (InferRelatedResultType &&
4750 !ObjCMethod->getReturnType()->isObjCIndependentClassType())
Erich Keane9b18eca2018-08-01 21:31:08 +00004751 ObjCMethod->setRelatedResultType();
Douglas Gregor33823722011-06-11 01:09:30 +00004752 }
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00004753
Alex Lorenza8a372d2017-04-27 10:43:48 +00004754 if (MethodDefinition &&
4755 Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
4756 checkObjCMethodX86VectorTypes(*this, ObjCMethod);
4757
Steven Wu3bb4aa52018-04-16 23:34:18 +00004758 // + load method cannot have availability attributes. It get called on
4759 // startup, so it has to have the availability of the deployment target.
4760 if (const auto *attr = ObjCMethod->getAttr<AvailabilityAttr>()) {
4761 if (ObjCMethod->isClassMethod() &&
4762 ObjCMethod->getSelector().getAsString() == "load") {
4763 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
4764 << 0;
4765 ObjCMethod->dropAttr<AvailabilityAttr>();
4766 }
4767 }
4768
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00004769 ActOnDocumentableDecl(ObjCMethod);
4770
John McCall48871652010-08-21 09:40:31 +00004771 return ObjCMethod;
Chris Lattnerda463fe2007-12-12 07:09:47 +00004772}
4773
Chris Lattner438e5012008-12-17 07:13:27 +00004774bool Sema::CheckObjCDeclScope(Decl *D) {
Fariborz Jahanianf36734d2011-08-22 18:34:22 +00004775 // Following is also an error. But it is caused by a missing @end
4776 // and diagnostic is issued elsewhere.
Argyrios Kyrtzidis822c4332012-03-23 23:24:23 +00004777 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004778 return false;
Argyrios Kyrtzidis822c4332012-03-23 23:24:23 +00004779
4780 // If we switched context to translation unit while we are still lexically in
4781 // an objc container, it means the parser missed emitting an error.
4782 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
4783 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004784
Anders Carlssona6b508a2008-11-04 16:57:32 +00004785 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
4786 D->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004787
Anders Carlssona6b508a2008-11-04 16:57:32 +00004788 return true;
4789}
Chris Lattner438e5012008-12-17 07:13:27 +00004790
James Dennett634962f2012-06-14 21:40:34 +00004791/// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
Chris Lattner438e5012008-12-17 07:13:27 +00004792/// instance variables of ClassName into Decls.
John McCall48871652010-08-21 09:40:31 +00004793void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
Chris Lattner438e5012008-12-17 07:13:27 +00004794 IdentifierInfo *ClassName,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004795 SmallVectorImpl<Decl*> &Decls) {
Chris Lattner438e5012008-12-17 07:13:27 +00004796 // Check that ClassName is a valid class
Douglas Gregorb2ccf012010-04-15 22:33:43 +00004797 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
Chris Lattner438e5012008-12-17 07:13:27 +00004798 if (!Class) {
4799 Diag(DeclStart, diag::err_undef_interface) << ClassName;
4800 return;
4801 }
John McCall5fb5df92012-06-20 06:18:46 +00004802 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanianece1b2b2009-04-21 20:28:41 +00004803 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
4804 return;
4805 }
Mike Stump11289f42009-09-09 15:08:12 +00004806
Chris Lattner438e5012008-12-17 07:13:27 +00004807 // Collect the instance variables
Jordy Rosea91768e2011-07-22 02:08:32 +00004808 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004809 Context.DeepCollectObjCIvars(Class, true, Ivars);
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004810 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004811 for (unsigned i = 0; i < Ivars.size(); i++) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00004812 const FieldDecl* ID = Ivars[i];
John McCall48871652010-08-21 09:40:31 +00004813 RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
Abramo Bagnaradff19302011-03-08 08:55:46 +00004814 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
4815 /*FIXME: StartL=*/ID->getLocation(),
4816 ID->getLocation(),
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004817 ID->getIdentifier(), ID->getType(),
4818 ID->getBitWidth());
John McCall48871652010-08-21 09:40:31 +00004819 Decls.push_back(FD);
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004820 }
Mike Stump11289f42009-09-09 15:08:12 +00004821
Chris Lattner438e5012008-12-17 07:13:27 +00004822 // Introduce all of these fields into the appropriate scope.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004823 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
Chris Lattner438e5012008-12-17 07:13:27 +00004824 D != Decls.end(); ++D) {
John McCall48871652010-08-21 09:40:31 +00004825 FieldDecl *FD = cast<FieldDecl>(*D);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004826 if (getLangOpts().CPlusPlus)
George Burgess IV00f70bd2018-03-01 05:43:23 +00004827 PushOnScopeChains(FD, S);
John McCall48871652010-08-21 09:40:31 +00004828 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004829 Record->addDecl(FD);
Chris Lattner438e5012008-12-17 07:13:27 +00004830 }
4831}
4832
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004833/// Build a type-check a new Objective-C exception variable declaration.
Abramo Bagnaradff19302011-03-08 08:55:46 +00004834VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
4835 SourceLocation StartLoc,
4836 SourceLocation IdLoc,
4837 IdentifierInfo *Id,
Douglas Gregorf3564192010-04-26 17:32:49 +00004838 bool Invalid) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004839 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
Douglas Gregorf3564192010-04-26 17:32:49 +00004840 // duration shall not be qualified by an address-space qualifier."
4841 // Since all parameters have automatic store duration, they can not have
4842 // an address space.
Alexander Richardson6d989432017-10-15 18:48:14 +00004843 if (T.getAddressSpace() != LangAS::Default) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004844 Diag(IdLoc, diag::err_arg_with_address_space);
Douglas Gregorf3564192010-04-26 17:32:49 +00004845 Invalid = true;
4846 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004847
Douglas Gregorf3564192010-04-26 17:32:49 +00004848 // An @catch parameter must be an unqualified object pointer type;
4849 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
4850 if (Invalid) {
4851 // Don't do any further checking.
Douglas Gregorf4e837f2010-04-26 17:57:08 +00004852 } else if (T->isDependentType()) {
4853 // Okay: we don't know what this type will instantiate to.
Douglas Gregorf3564192010-04-26 17:32:49 +00004854 } else if (T->isObjCQualifiedIdType()) {
4855 Invalid = true;
Abramo Bagnaradff19302011-03-08 08:55:46 +00004856 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
Saleem Abdulrasool278e1c42018-05-20 19:26:44 +00004857 } else if (T->isObjCIdType()) {
4858 // Okay: we don't know what this type will instantiate to.
4859 } else if (!T->isObjCObjectPointerType()) {
4860 Invalid = true;
4861 Diag(IdLoc, diag::err_catch_param_not_objc_type);
4862 } else if (!T->getAs<ObjCObjectPointerType>()->getInterfaceType()) {
4863 Invalid = true;
4864 Diag(IdLoc, diag::err_catch_param_not_objc_type);
Douglas Gregorf3564192010-04-26 17:32:49 +00004865 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004866
Abramo Bagnaradff19302011-03-08 08:55:46 +00004867 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004868 T, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00004869 New->setExceptionVariable(true);
Fangrui Song6907ce22018-07-30 19:24:48 +00004870
Douglas Gregor8ca0c642011-12-10 01:22:52 +00004871 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004872 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
Douglas Gregor8ca0c642011-12-10 01:22:52 +00004873 Invalid = true;
4874
Douglas Gregorf3564192010-04-26 17:32:49 +00004875 if (Invalid)
4876 New->setInvalidDecl();
4877 return New;
4878}
4879
John McCall48871652010-08-21 09:40:31 +00004880Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
Douglas Gregorf3564192010-04-26 17:32:49 +00004881 const DeclSpec &DS = D.getDeclSpec();
Fangrui Song6907ce22018-07-30 19:24:48 +00004882
Douglas Gregorf3564192010-04-26 17:32:49 +00004883 // We allow the "register" storage class on exception variables because
4884 // GCC did, but we drop it completely. Any other storage class is an error.
4885 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
4886 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
4887 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
Richard Smithb4a9e862013-04-12 22:46:28 +00004888 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
Douglas Gregorf3564192010-04-26 17:32:49 +00004889 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
Richard Smithb4a9e862013-04-12 22:46:28 +00004890 << DeclSpec::getSpecifierName(SCS);
4891 }
Richard Smith62f19e72016-06-25 00:15:56 +00004892 if (DS.isInlineSpecified())
4893 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004894 << getLangOpts().CPlusPlus17;
Richard Smithb4a9e862013-04-12 22:46:28 +00004895 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
4896 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
4897 diag::err_invalid_thread)
4898 << DeclSpec::getSpecifierName(TSCS);
Douglas Gregorf3564192010-04-26 17:32:49 +00004899 D.getMutableDeclSpec().ClearStorageClassSpecs();
4900
Richard Smithb1402ae2013-03-18 22:52:47 +00004901 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Fangrui Song6907ce22018-07-30 19:24:48 +00004902
Douglas Gregorf3564192010-04-26 17:32:49 +00004903 // Check that there are no default arguments inside the type of this
4904 // exception object (C++ only).
David Blaikiebbafb8a2012-03-11 07:00:24 +00004905 if (getLangOpts().CPlusPlus)
Douglas Gregorf3564192010-04-26 17:32:49 +00004906 CheckExtraCXXDefaultArguments(D);
Fangrui Song6907ce22018-07-30 19:24:48 +00004907
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00004908 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00004909 QualType ExceptionType = TInfo->getType();
Douglas Gregorf3564192010-04-26 17:32:49 +00004910
Abramo Bagnaradff19302011-03-08 08:55:46 +00004911 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
4912 D.getSourceRange().getBegin(),
4913 D.getIdentifierLoc(),
4914 D.getIdentifier(),
Douglas Gregorf3564192010-04-26 17:32:49 +00004915 D.isInvalidType());
Fangrui Song6907ce22018-07-30 19:24:48 +00004916
Douglas Gregorf3564192010-04-26 17:32:49 +00004917 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
4918 if (D.getCXXScopeSpec().isSet()) {
4919 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
4920 << D.getCXXScopeSpec().getRange();
4921 New->setInvalidDecl();
4922 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004923
Douglas Gregorf3564192010-04-26 17:32:49 +00004924 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00004925 S->AddDecl(New);
Douglas Gregorf3564192010-04-26 17:32:49 +00004926 if (D.getIdentifier())
4927 IdResolver.AddDecl(New);
Fangrui Song6907ce22018-07-30 19:24:48 +00004928
Douglas Gregorf3564192010-04-26 17:32:49 +00004929 ProcessDeclAttributes(S, New, D);
Fangrui Song6907ce22018-07-30 19:24:48 +00004930
Douglas Gregorf3564192010-04-26 17:32:49 +00004931 if (New->hasAttr<BlocksAttr>())
4932 Diag(New->getLocation(), diag::err_block_on_nonlocal);
John McCall48871652010-08-21 09:40:31 +00004933 return New;
Douglas Gregore11ee112010-04-23 23:01:43 +00004934}
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004935
4936/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004937/// initialization.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004938void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004939 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004940 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004941 Iv= Iv->getNextIvar()) {
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004942 QualType QT = Context.getBaseElementType(Iv->getType());
Douglas Gregor527786e2010-05-20 02:24:22 +00004943 if (QT->isRecordType())
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004944 Ivars.push_back(Iv);
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004945 }
4946}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004947
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004948void Sema::DiagnoseUseOfUnimplementedSelectors() {
Douglas Gregor72e357f2011-07-28 14:54:22 +00004949 // Load referenced selectors from the external source.
4950 if (ExternalSource) {
4951 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
4952 ExternalSource->ReadReferencedSelectors(Sels);
4953 for (unsigned I = 0, N = Sels.size(); I != N; ++I)
4954 ReferencedSelectors[Sels[I].first] = Sels[I].second;
4955 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004956
Fariborz Jahanianc9b7c202011-02-04 23:19:27 +00004957 // Warning will be issued only when selector table is
4958 // generated (which means there is at lease one implementation
4959 // in the TU). This is to match gcc's behavior.
Fangrui Song6907ce22018-07-30 19:24:48 +00004960 if (ReferencedSelectors.empty() ||
Fariborz Jahanianc9b7c202011-02-04 23:19:27 +00004961 !Context.AnyObjCImplementation())
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004962 return;
Chandler Carruth12c8f652015-03-27 00:55:05 +00004963 for (auto &SelectorAndLocation : ReferencedSelectors) {
4964 Selector Sel = SelectorAndLocation.first;
4965 SourceLocation Loc = SelectorAndLocation.second;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004966 if (!LookupImplementedMethodInGlobalPool(Sel))
Chandler Carruth12c8f652015-03-27 00:55:05 +00004967 Diag(Loc, diag::warn_unimplemented_selector) << Sel;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004968 }
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004969}
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004970
4971ObjCIvarDecl *
4972Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4973 const ObjCPropertyDecl *&PDecl) const {
Fariborz Jahanian1cc7ae12014-01-02 17:24:32 +00004974 if (Method->isClassMethod())
Craig Topperc3ec1492014-05-26 06:22:03 +00004975 return nullptr;
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004976 const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
4977 if (!IDecl)
Craig Topperc3ec1492014-05-26 06:22:03 +00004978 return nullptr;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004979 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
4980 /*shallowCategoryLookup=*/false,
4981 /*followSuper=*/false);
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004982 if (!Method || !Method->isPropertyAccessor())
Craig Topperc3ec1492014-05-26 06:22:03 +00004983 return nullptr;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004984 if ((PDecl = Method->findPropertyDecl()))
Fariborz Jahanian122d94f2014-01-27 22:27:43 +00004985 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
4986 // property backing ivar must belong to property's class
4987 // or be a private ivar in class's implementation.
4988 // FIXME. fix the const-ness issue.
4989 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
4990 IV->getIdentifier());
4991 return IV;
4992 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004993 return nullptr;
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004994}
4995
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004996namespace {
4997 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
4998 /// accessor references the backing ivar.
Argyrios Kyrtzidis98045c12014-01-03 19:53:09 +00004999 class UnusedBackingIvarChecker :
Richard Smith50668452015-11-24 03:55:01 +00005000 public RecursiveASTVisitor<UnusedBackingIvarChecker> {
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005001 public:
5002 Sema &S;
5003 const ObjCMethodDecl *Method;
5004 const ObjCIvarDecl *IvarD;
5005 bool AccessedIvar;
5006 bool InvokedSelfMethod;
5007
5008 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
5009 const ObjCIvarDecl *IvarD)
5010 : S(S), Method(Method), IvarD(IvarD),
5011 AccessedIvar(false), InvokedSelfMethod(false) {
5012 assert(IvarD);
5013 }
5014
5015 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
5016 if (E->getDecl() == IvarD) {
5017 AccessedIvar = true;
5018 return false;
5019 }
5020 return true;
5021 }
5022
5023 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
5024 if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
5025 S.isSelfExpr(E->getInstanceReceiver(), Method)) {
5026 InvokedSelfMethod = true;
5027 }
5028 return true;
5029 }
5030 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00005031} // end anonymous namespace
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005032
5033void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
5034 const ObjCImplementationDecl *ImplD) {
5035 if (S->hasUnrecoverableErrorOccurred())
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00005036 return;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005037
Aaron Ballmanf26acce2014-03-13 19:50:17 +00005038 for (const auto *CurMethod : ImplD->instance_methods()) {
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005039 unsigned DIAG = diag::warn_unused_property_backing_ivar;
5040 SourceLocation Loc = CurMethod->getLocation();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005041 if (Diags.isIgnored(DIAG, Loc))
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005042 continue;
5043
5044 const ObjCPropertyDecl *PDecl;
5045 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
5046 if (!IV)
5047 continue;
5048
5049 UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
5050 Checker.TraverseStmt(CurMethod->getBody());
5051 if (Checker.AccessedIvar)
5052 continue;
5053
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00005054 // Do not issue this warning if backing ivar is used somewhere and accessor
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005055 // implementation makes a self call. This is to prevent false positive in
5056 // cases where the ivar is accessed by another method that the accessor
5057 // delegates to.
5058 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
Argyrios Kyrtzidisd8a35322014-01-03 19:39:23 +00005059 Diag(Loc, DIAG) << IV;
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00005060 Diag(PDecl->getLocation(), diag::note_property_declare);
5061 }
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00005062 }
5063}