1 //===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements semantic analysis for Objective C declarations.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/DataRecursiveASTVisitor.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Sema/DeclSpec.h"
24 #include "clang/Sema/ExternalSemaSource.h"
25 #include "clang/Sema/Lookup.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/ScopeInfo.h"
28 #include "llvm/ADT/DenseSet.h"
29
30 using namespace clang;
31
32 /// Check whether the given method, which must be in the 'init'
33 /// family, is a valid member of that family.
34 ///
35 /// \param receiverTypeIfCall - if null, check this as if declaring it;
36 /// if non-null, check this as if making a call to it with the given
37 /// receiver type
38 ///
39 /// \return true to indicate that there was an error and appropriate
40 /// actions were taken
checkInitMethod(ObjCMethodDecl * method,QualType receiverTypeIfCall)41 bool Sema::checkInitMethod(ObjCMethodDecl *method,
42 QualType receiverTypeIfCall) {
43 if (method->isInvalidDecl()) return true;
44
45 // This castAs is safe: methods that don't return an object
46 // pointer won't be inferred as inits and will reject an explicit
47 // objc_method_family(init).
48
49 // We ignore protocols here. Should we? What about Class?
50
51 const ObjCObjectType *result =
52 method->getReturnType()->castAs<ObjCObjectPointerType>()->getObjectType();
53
54 if (result->isObjCId()) {
55 return false;
56 } else if (result->isObjCClass()) {
57 // fall through: always an error
58 } else {
59 ObjCInterfaceDecl *resultClass = result->getInterface();
60 assert(resultClass && "unexpected object type!");
61
62 // It's okay for the result type to still be a forward declaration
63 // if we're checking an interface declaration.
64 if (!resultClass->hasDefinition()) {
65 if (receiverTypeIfCall.isNull() &&
66 !isa<ObjCImplementationDecl>(method->getDeclContext()))
67 return false;
68
69 // Otherwise, we try to compare class types.
70 } else {
71 // If this method was declared in a protocol, we can't check
72 // anything unless we have a receiver type that's an interface.
73 const ObjCInterfaceDecl *receiverClass = nullptr;
74 if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
75 if (receiverTypeIfCall.isNull())
76 return false;
77
78 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
79 ->getInterfaceDecl();
80
81 // This can be null for calls to e.g. id<Foo>.
82 if (!receiverClass) return false;
83 } else {
84 receiverClass = method->getClassInterface();
85 assert(receiverClass && "method not associated with a class!");
86 }
87
88 // If either class is a subclass of the other, it's fine.
89 if (receiverClass->isSuperClassOf(resultClass) ||
90 resultClass->isSuperClassOf(receiverClass))
91 return false;
92 }
93 }
94
95 SourceLocation loc = method->getLocation();
96
97 // If we're in a system header, and this is not a call, just make
98 // the method unusable.
99 if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
100 method->addAttr(UnavailableAttr::CreateImplicit(Context,
101 "init method returns a type unrelated to its receiver type",
102 loc));
103 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
CheckObjCMethodOverride(ObjCMethodDecl * NewMethod,const ObjCMethodDecl * Overridden)112 void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
113 const ObjCMethodDecl *Overridden) {
114 if (Overridden->hasRelatedResultType() &&
115 !NewMethod->hasRelatedResultType()) {
116 // This can only happen when the method follows a naming convention that
117 // implies a related result type, and the original (overridden) method has
118 // a suitable return type, but the new (overriding) method does not have
119 // a suitable return type.
120 QualType ResultType = NewMethod->getReturnType();
121 SourceRange ResultTypeRange;
122 if (const TypeSourceInfo *ResultTypeInfo =
123 NewMethod->getReturnTypeSourceInfo())
124 ResultTypeRange = ResultTypeInfo->getTypeLoc().getSourceRange();
125
126 // Figure out which class this method is part of, if any.
127 ObjCInterfaceDecl *CurrentClass
128 = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
129 if (!CurrentClass) {
130 DeclContext *DC = NewMethod->getDeclContext();
131 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
132 CurrentClass = Cat->getClassInterface();
133 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
134 CurrentClass = Impl->getClassInterface();
135 else if (ObjCCategoryImplDecl *CatImpl
136 = dyn_cast<ObjCCategoryImplDecl>(DC))
137 CurrentClass = CatImpl->getClassInterface();
138 }
139
140 if (CurrentClass) {
141 Diag(NewMethod->getLocation(),
142 diag::warn_related_result_type_compatibility_class)
143 << Context.getObjCInterfaceType(CurrentClass)
144 << ResultType
145 << ResultTypeRange;
146 } else {
147 Diag(NewMethod->getLocation(),
148 diag::warn_related_result_type_compatibility_protocol)
149 << ResultType
150 << ResultTypeRange;
151 }
152
153 if (ObjCMethodFamily Family = Overridden->getMethodFamily())
154 Diag(Overridden->getLocation(),
155 diag::note_related_result_type_family)
156 << /*overridden method*/ 0
157 << Family;
158 else
159 Diag(Overridden->getLocation(),
160 diag::note_related_result_type_overridden);
161 }
162 if (getLangOpts().ObjCAutoRefCount) {
163 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
164 Overridden->hasAttr<NSReturnsRetainedAttr>())) {
165 Diag(NewMethod->getLocation(),
166 diag::err_nsreturns_retained_attribute_mismatch) << 1;
167 Diag(Overridden->getLocation(), diag::note_previous_decl)
168 << "method";
169 }
170 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
171 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
172 Diag(NewMethod->getLocation(),
173 diag::err_nsreturns_retained_attribute_mismatch) << 0;
174 Diag(Overridden->getLocation(), diag::note_previous_decl)
175 << "method";
176 }
177 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
178 oe = Overridden->param_end();
179 for (ObjCMethodDecl::param_iterator
180 ni = NewMethod->param_begin(), ne = NewMethod->param_end();
181 ni != ne && oi != oe; ++ni, ++oi) {
182 const ParmVarDecl *oldDecl = (*oi);
183 ParmVarDecl *newDecl = (*ni);
184 if (newDecl->hasAttr<NSConsumedAttr>() !=
185 oldDecl->hasAttr<NSConsumedAttr>()) {
186 Diag(newDecl->getLocation(),
187 diag::err_nsconsumed_attribute_mismatch);
188 Diag(oldDecl->getLocation(), diag::note_previous_decl)
189 << "parameter";
190 }
191 }
192 }
193 }
194
195 /// \brief Check a method declaration for compatibility with the Objective-C
196 /// ARC conventions.
CheckARCMethodDecl(ObjCMethodDecl * method)197 bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
198 ObjCMethodFamily family = method->getMethodFamily();
199 switch (family) {
200 case OMF_None:
201 case OMF_finalize:
202 case OMF_retain:
203 case OMF_release:
204 case OMF_autorelease:
205 case OMF_retainCount:
206 case OMF_self:
207 case OMF_performSelector:
208 return false;
209
210 case OMF_dealloc:
211 if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
212 SourceRange ResultTypeRange;
213 if (const TypeSourceInfo *ResultTypeInfo =
214 method->getReturnTypeSourceInfo())
215 ResultTypeRange = ResultTypeInfo->getTypeLoc().getSourceRange();
216 if (ResultTypeRange.isInvalid())
217 Diag(method->getLocation(), diag::error_dealloc_bad_result_type)
218 << method->getReturnType()
219 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
220 else
221 Diag(method->getLocation(), diag::error_dealloc_bad_result_type)
222 << method->getReturnType()
223 << FixItHint::CreateReplacement(ResultTypeRange, "void");
224 return true;
225 }
226 return false;
227
228 case OMF_init:
229 // If the method doesn't obey the init rules, don't bother annotating it.
230 if (checkInitMethod(method, QualType()))
231 return true;
232
233 method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
234
235 // Don't add a second copy of this attribute, but otherwise don't
236 // let it be suppressed.
237 if (method->hasAttr<NSReturnsRetainedAttr>())
238 return false;
239 break;
240
241 case OMF_alloc:
242 case OMF_copy:
243 case OMF_mutableCopy:
244 case OMF_new:
245 if (method->hasAttr<NSReturnsRetainedAttr>() ||
246 method->hasAttr<NSReturnsNotRetainedAttr>() ||
247 method->hasAttr<NSReturnsAutoreleasedAttr>())
248 return false;
249 break;
250 }
251
252 method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
253 return false;
254 }
255
DiagnoseObjCImplementedDeprecations(Sema & S,NamedDecl * ND,SourceLocation ImplLoc,int select)256 static void DiagnoseObjCImplementedDeprecations(Sema &S,
257 NamedDecl *ND,
258 SourceLocation ImplLoc,
259 int select) {
260 if (ND && ND->isDeprecated()) {
261 S.Diag(ImplLoc, diag::warn_deprecated_def) << select;
262 if (select == 0)
263 S.Diag(ND->getLocation(), diag::note_method_declared_at)
264 << ND->getDeclName();
265 else
266 S.Diag(ND->getLocation(), diag::note_previous_decl) << "class";
267 }
268 }
269
270 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
271 /// pool.
AddAnyMethodToGlobalPool(Decl * D)272 void Sema::AddAnyMethodToGlobalPool(Decl *D) {
273 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
274
275 // If we don't have a valid method decl, simply return.
276 if (!MDecl)
277 return;
278 if (MDecl->isInstanceMethod())
279 AddInstanceMethodToGlobalPool(MDecl, true);
280 else
281 AddFactoryMethodToGlobalPool(MDecl, true);
282 }
283
284 /// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
285 /// has explicit ownership attribute; false otherwise.
286 static bool
HasExplicitOwnershipAttr(Sema & S,ParmVarDecl * Param)287 HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
288 QualType T = Param->getType();
289
290 if (const PointerType *PT = T->getAs<PointerType>()) {
291 T = PT->getPointeeType();
292 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
293 T = RT->getPointeeType();
294 } else {
295 return true;
296 }
297
298 // If we have a lifetime qualifier, but it's local, we must have
299 // inferred it. So, it is implicit.
300 return !T.getLocalQualifiers().hasObjCLifetime();
301 }
302
303 /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
304 /// and user declared, in the method definition's AST.
ActOnStartOfObjCMethodDef(Scope * FnBodyScope,Decl * D)305 void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
306 assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
307 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
308
309 // If we don't have a valid method decl, simply return.
310 if (!MDecl)
311 return;
312
313 // Allow all of Sema to see that we are entering a method definition.
314 PushDeclContext(FnBodyScope, MDecl);
315 PushFunctionScope();
316
317 // Create Decl objects for each parameter, entrring them in the scope for
318 // binding to their use.
319
320 // Insert the invisible arguments, self and _cmd!
321 MDecl->createImplicitParams(Context, MDecl->getClassInterface());
322
323 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
324 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
325
326 // The ObjC parser requires parameter names so there's no need to check.
327 CheckParmsForFunctionDef(MDecl->param_begin(), MDecl->param_end(),
328 /*CheckParameterNames=*/false);
329
330 // Introduce all of the other parameters into this scope.
331 for (auto *Param : MDecl->params()) {
332 if (!Param->isInvalidDecl() &&
333 getLangOpts().ObjCAutoRefCount &&
334 !HasExplicitOwnershipAttr(*this, Param))
335 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
336 Param->getType();
337
338 if (Param->getIdentifier())
339 PushOnScopeChains(Param, FnBodyScope);
340 }
341
342 // In ARC, disallow definition of retain/release/autorelease/retainCount
343 if (getLangOpts().ObjCAutoRefCount) {
344 switch (MDecl->getMethodFamily()) {
345 case OMF_retain:
346 case OMF_retainCount:
347 case OMF_release:
348 case OMF_autorelease:
349 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
350 << 0 << MDecl->getSelector();
351 break;
352
353 case OMF_None:
354 case OMF_dealloc:
355 case OMF_finalize:
356 case OMF_alloc:
357 case OMF_init:
358 case OMF_mutableCopy:
359 case OMF_copy:
360 case OMF_new:
361 case OMF_self:
362 case OMF_performSelector:
363 break;
364 }
365 }
366
367 // Warn on deprecated methods under -Wdeprecated-implementations,
368 // and prepare for warning on missing super calls.
369 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
370 ObjCMethodDecl *IMD =
371 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
372
373 if (IMD) {
374 ObjCImplDecl *ImplDeclOfMethodDef =
375 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
376 ObjCContainerDecl *ContDeclOfMethodDecl =
377 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
378 ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
379 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
380 ImplDeclOfMethodDecl = OID->getImplementation();
381 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
382 if (CD->IsClassExtension()) {
383 if (ObjCInterfaceDecl *OID = CD->getClassInterface())
384 ImplDeclOfMethodDecl = OID->getImplementation();
385 } else
386 ImplDeclOfMethodDecl = CD->getImplementation();
387 }
388 // No need to issue deprecated warning if deprecated mehod in class/category
389 // is being implemented in its own implementation (no overriding is involved).
390 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
391 DiagnoseObjCImplementedDeprecations(*this,
392 dyn_cast<NamedDecl>(IMD),
393 MDecl->getLocation(), 0);
394 }
395
396 if (MDecl->getMethodFamily() == OMF_init) {
397 if (MDecl->isDesignatedInitializerForTheInterface()) {
398 getCurFunction()->ObjCIsDesignatedInit = true;
399 getCurFunction()->ObjCWarnForNoDesignatedInitChain =
400 IC->getSuperClass() != nullptr;
401 } else if (IC->hasDesignatedInitializers()) {
402 getCurFunction()->ObjCIsSecondaryInit = true;
403 getCurFunction()->ObjCWarnForNoInitDelegation = true;
404 }
405 }
406
407 // If this is "dealloc" or "finalize", set some bit here.
408 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
409 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
410 // Only do this if the current class actually has a superclass.
411 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
412 ObjCMethodFamily Family = MDecl->getMethodFamily();
413 if (Family == OMF_dealloc) {
414 if (!(getLangOpts().ObjCAutoRefCount ||
415 getLangOpts().getGC() == LangOptions::GCOnly))
416 getCurFunction()->ObjCShouldCallSuper = true;
417
418 } else if (Family == OMF_finalize) {
419 if (Context.getLangOpts().getGC() != LangOptions::NonGC)
420 getCurFunction()->ObjCShouldCallSuper = true;
421
422 } else {
423 const ObjCMethodDecl *SuperMethod =
424 SuperClass->lookupMethod(MDecl->getSelector(),
425 MDecl->isInstanceMethod());
426 getCurFunction()->ObjCShouldCallSuper =
427 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
428 }
429 }
430 }
431 }
432
433 namespace {
434
435 // Callback to only accept typo corrections that are Objective-C classes.
436 // If an ObjCInterfaceDecl* is given to the constructor, then the validation
437 // function will reject corrections to that class.
438 class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback {
439 public:
ObjCInterfaceValidatorCCC()440 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
ObjCInterfaceValidatorCCC(ObjCInterfaceDecl * IDecl)441 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
442 : CurrentIDecl(IDecl) {}
443
ValidateCandidate(const TypoCorrection & candidate)444 bool ValidateCandidate(const TypoCorrection &candidate) override {
445 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
446 return ID && !declaresSameEntity(ID, CurrentIDecl);
447 }
448
449 private:
450 ObjCInterfaceDecl *CurrentIDecl;
451 };
452
453 }
454
455 Decl *Sema::
ActOnStartClassInterface(SourceLocation AtInterfaceLoc,IdentifierInfo * ClassName,SourceLocation ClassLoc,IdentifierInfo * SuperName,SourceLocation SuperLoc,Decl * const * ProtoRefs,unsigned NumProtoRefs,const SourceLocation * ProtoLocs,SourceLocation EndProtoLoc,AttributeList * AttrList)456 ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
457 IdentifierInfo *ClassName, SourceLocation ClassLoc,
458 IdentifierInfo *SuperName, SourceLocation SuperLoc,
459 Decl * const *ProtoRefs, unsigned NumProtoRefs,
460 const SourceLocation *ProtoLocs,
461 SourceLocation EndProtoLoc, AttributeList *AttrList) {
462 assert(ClassName && "Missing class identifier");
463
464 // Check for another declaration kind with the same name.
465 NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
466 LookupOrdinaryName, ForRedeclaration);
467
468 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
469 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
470 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
471 }
472
473 // Create a declaration to describe this @interface.
474 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
475
476 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
477 // A previous decl with a different name is because of
478 // @compatibility_alias, for example:
479 // \code
480 // @class NewImage;
481 // @compatibility_alias OldImage NewImage;
482 // \endcode
483 // A lookup for 'OldImage' will return the 'NewImage' decl.
484 //
485 // In such a case use the real declaration name, instead of the alias one,
486 // otherwise we will break IdentifierResolver and redecls-chain invariants.
487 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
488 // has been aliased.
489 ClassName = PrevIDecl->getIdentifier();
490 }
491
492 ObjCInterfaceDecl *IDecl
493 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
494 PrevIDecl, ClassLoc);
495
496 if (PrevIDecl) {
497 // Class already seen. Was it a definition?
498 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
499 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
500 << PrevIDecl->getDeclName();
501 Diag(Def->getLocation(), diag::note_previous_definition);
502 IDecl->setInvalidDecl();
503 }
504 }
505
506 if (AttrList)
507 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
508 PushOnScopeChains(IDecl, TUScope);
509
510 // Start the definition of this class. If we're in a redefinition case, there
511 // may already be a definition, so we'll end up adding to it.
512 if (!IDecl->hasDefinition())
513 IDecl->startDefinition();
514
515 if (SuperName) {
516 // Check if a different kind of symbol declared in this scope.
517 PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
518 LookupOrdinaryName);
519
520 if (!PrevDecl) {
521 // Try to correct for a typo in the superclass name without correcting
522 // to the class we're defining.
523 ObjCInterfaceValidatorCCC Validator(IDecl);
524 if (TypoCorrection Corrected = CorrectTypo(
525 DeclarationNameInfo(SuperName, SuperLoc), LookupOrdinaryName, TUScope,
526 nullptr, Validator, CTK_ErrorRecovery)) {
527 diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
528 << SuperName << ClassName);
529 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
530 }
531 }
532
533 if (declaresSameEntity(PrevDecl, IDecl)) {
534 Diag(SuperLoc, diag::err_recursive_superclass)
535 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
536 IDecl->setEndOfDefinitionLoc(ClassLoc);
537 } else {
538 ObjCInterfaceDecl *SuperClassDecl =
539 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
540
541 // Diagnose classes that inherit from deprecated classes.
542 if (SuperClassDecl)
543 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
544
545 if (PrevDecl && !SuperClassDecl) {
546 // The previous declaration was not a class decl. Check if we have a
547 // typedef. If we do, get the underlying class type.
548 if (const TypedefNameDecl *TDecl =
549 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
550 QualType T = TDecl->getUnderlyingType();
551 if (T->isObjCObjectType()) {
552 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
553 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
554 // This handles the following case:
555 // @interface NewI @end
556 // typedef NewI DeprI __attribute__((deprecated("blah")))
557 // @interface SI : DeprI /* warn here */ @end
558 (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
559 }
560 }
561 }
562
563 // This handles the following case:
564 //
565 // typedef int SuperClass;
566 // @interface MyClass : SuperClass {} @end
567 //
568 if (!SuperClassDecl) {
569 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
570 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
571 }
572 }
573
574 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
575 if (!SuperClassDecl)
576 Diag(SuperLoc, diag::err_undef_superclass)
577 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
578 else if (RequireCompleteType(SuperLoc,
579 Context.getObjCInterfaceType(SuperClassDecl),
580 diag::err_forward_superclass,
581 SuperClassDecl->getDeclName(),
582 ClassName,
583 SourceRange(AtInterfaceLoc, ClassLoc))) {
584 SuperClassDecl = nullptr;
585 }
586 }
587 IDecl->setSuperClass(SuperClassDecl);
588 IDecl->setSuperClassLoc(SuperLoc);
589 IDecl->setEndOfDefinitionLoc(SuperLoc);
590 }
591 } else { // we have a root class.
592 IDecl->setEndOfDefinitionLoc(ClassLoc);
593 }
594
595 // Check then save referenced protocols.
596 if (NumProtoRefs) {
597 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
598 ProtoLocs, Context);
599 IDecl->setEndOfDefinitionLoc(EndProtoLoc);
600 }
601
602 CheckObjCDeclScope(IDecl);
603 return ActOnObjCContainerStartDefinition(IDecl);
604 }
605
606 /// ActOnTypedefedProtocols - this action finds protocol list as part of the
607 /// typedef'ed use for a qualified super class and adds them to the list
608 /// of the protocols.
ActOnTypedefedProtocols(SmallVectorImpl<Decl * > & ProtocolRefs,IdentifierInfo * SuperName,SourceLocation SuperLoc)609 void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
610 IdentifierInfo *SuperName,
611 SourceLocation SuperLoc) {
612 if (!SuperName)
613 return;
614 NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
615 LookupOrdinaryName);
616 if (!IDecl)
617 return;
618
619 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
620 QualType T = TDecl->getUnderlyingType();
621 if (T->isObjCObjectType())
622 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>())
623 for (auto *I : OPT->quals())
624 ProtocolRefs.push_back(I);
625 }
626 }
627
628 /// ActOnCompatibilityAlias - this action is called after complete parsing of
629 /// a \@compatibility_alias declaration. It sets up the alias relationships.
ActOnCompatibilityAlias(SourceLocation AtLoc,IdentifierInfo * AliasName,SourceLocation AliasLocation,IdentifierInfo * ClassName,SourceLocation ClassLocation)630 Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
631 IdentifierInfo *AliasName,
632 SourceLocation AliasLocation,
633 IdentifierInfo *ClassName,
634 SourceLocation ClassLocation) {
635 // Look for previous declaration of alias name
636 NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
637 LookupOrdinaryName, ForRedeclaration);
638 if (ADecl) {
639 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
640 Diag(ADecl->getLocation(), diag::note_previous_declaration);
641 return nullptr;
642 }
643 // Check for class declaration
644 NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
645 LookupOrdinaryName, ForRedeclaration);
646 if (const TypedefNameDecl *TDecl =
647 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
648 QualType T = TDecl->getUnderlyingType();
649 if (T->isObjCObjectType()) {
650 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
651 ClassName = IDecl->getIdentifier();
652 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
653 LookupOrdinaryName, ForRedeclaration);
654 }
655 }
656 }
657 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
658 if (!CDecl) {
659 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
660 if (CDeclU)
661 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
662 return nullptr;
663 }
664
665 // Everything checked out, instantiate a new alias declaration AST.
666 ObjCCompatibleAliasDecl *AliasDecl =
667 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
668
669 if (!CheckObjCDeclScope(AliasDecl))
670 PushOnScopeChains(AliasDecl, TUScope);
671
672 return AliasDecl;
673 }
674
CheckForwardProtocolDeclarationForCircularDependency(IdentifierInfo * PName,SourceLocation & Ploc,SourceLocation PrevLoc,const ObjCList<ObjCProtocolDecl> & PList)675 bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
676 IdentifierInfo *PName,
677 SourceLocation &Ploc, SourceLocation PrevLoc,
678 const ObjCList<ObjCProtocolDecl> &PList) {
679
680 bool res = false;
681 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
682 E = PList.end(); I != E; ++I) {
683 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
684 Ploc)) {
685 if (PDecl->getIdentifier() == PName) {
686 Diag(Ploc, diag::err_protocol_has_circular_dependency);
687 Diag(PrevLoc, diag::note_previous_definition);
688 res = true;
689 }
690
691 if (!PDecl->hasDefinition())
692 continue;
693
694 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
695 PDecl->getLocation(), PDecl->getReferencedProtocols()))
696 res = true;
697 }
698 }
699 return res;
700 }
701
702 Decl *
ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,IdentifierInfo * ProtocolName,SourceLocation ProtocolLoc,Decl * const * ProtoRefs,unsigned NumProtoRefs,const SourceLocation * ProtoLocs,SourceLocation EndProtoLoc,AttributeList * AttrList)703 Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
704 IdentifierInfo *ProtocolName,
705 SourceLocation ProtocolLoc,
706 Decl * const *ProtoRefs,
707 unsigned NumProtoRefs,
708 const SourceLocation *ProtoLocs,
709 SourceLocation EndProtoLoc,
710 AttributeList *AttrList) {
711 bool err = false;
712 // FIXME: Deal with AttrList.
713 assert(ProtocolName && "Missing protocol identifier");
714 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
715 ForRedeclaration);
716 ObjCProtocolDecl *PDecl = nullptr;
717 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
718 // If we already have a definition, complain.
719 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
720 Diag(Def->getLocation(), diag::note_previous_definition);
721
722 // Create a new protocol that is completely distinct from previous
723 // declarations, and do not make this protocol available for name lookup.
724 // That way, we'll end up completely ignoring the duplicate.
725 // FIXME: Can we turn this into an error?
726 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
727 ProtocolLoc, AtProtoInterfaceLoc,
728 /*PrevDecl=*/nullptr);
729 PDecl->startDefinition();
730 } else {
731 if (PrevDecl) {
732 // Check for circular dependencies among protocol declarations. This can
733 // only happen if this protocol was forward-declared.
734 ObjCList<ObjCProtocolDecl> PList;
735 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
736 err = CheckForwardProtocolDeclarationForCircularDependency(
737 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
738 }
739
740 // Create the new declaration.
741 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
742 ProtocolLoc, AtProtoInterfaceLoc,
743 /*PrevDecl=*/PrevDecl);
744
745 PushOnScopeChains(PDecl, TUScope);
746 PDecl->startDefinition();
747 }
748
749 if (AttrList)
750 ProcessDeclAttributeList(TUScope, PDecl, AttrList);
751
752 // Merge attributes from previous declarations.
753 if (PrevDecl)
754 mergeDeclAttributes(PDecl, PrevDecl);
755
756 if (!err && NumProtoRefs ) {
757 /// Check then save referenced protocols.
758 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
759 ProtoLocs, Context);
760 }
761
762 CheckObjCDeclScope(PDecl);
763 return ActOnObjCContainerStartDefinition(PDecl);
764 }
765
NestedProtocolHasNoDefinition(ObjCProtocolDecl * PDecl,ObjCProtocolDecl * & UndefinedProtocol)766 static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
767 ObjCProtocolDecl *&UndefinedProtocol) {
768 if (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()) {
769 UndefinedProtocol = PDecl;
770 return true;
771 }
772
773 for (auto *PI : PDecl->protocols())
774 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
775 UndefinedProtocol = PI;
776 return true;
777 }
778 return false;
779 }
780
781 /// FindProtocolDeclaration - This routine looks up protocols and
782 /// issues an error if they are not declared. It returns list of
783 /// protocol declarations in its 'Protocols' argument.
784 void
FindProtocolDeclaration(bool WarnOnDeclarations,const IdentifierLocPair * ProtocolId,unsigned NumProtocols,SmallVectorImpl<Decl * > & Protocols)785 Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
786 const IdentifierLocPair *ProtocolId,
787 unsigned NumProtocols,
788 SmallVectorImpl<Decl *> &Protocols) {
789 for (unsigned i = 0; i != NumProtocols; ++i) {
790 ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first,
791 ProtocolId[i].second);
792 if (!PDecl) {
793 DeclFilterCCC<ObjCProtocolDecl> Validator;
794 TypoCorrection Corrected = CorrectTypo(
795 DeclarationNameInfo(ProtocolId[i].first, ProtocolId[i].second),
796 LookupObjCProtocolName, TUScope, nullptr, Validator,
797 CTK_ErrorRecovery);
798 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
799 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
800 << ProtocolId[i].first);
801 }
802
803 if (!PDecl) {
804 Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
805 << ProtocolId[i].first;
806 continue;
807 }
808 // If this is a forward protocol declaration, get its definition.
809 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
810 PDecl = PDecl->getDefinition();
811
812 (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
813
814 // If this is a forward declaration and we are supposed to warn in this
815 // case, do it.
816 // FIXME: Recover nicely in the hidden case.
817 ObjCProtocolDecl *UndefinedProtocol;
818
819 if (WarnOnDeclarations &&
820 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
821 Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
822 << ProtocolId[i].first;
823 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
824 << UndefinedProtocol;
825 }
826 Protocols.push_back(PDecl);
827 }
828 }
829
830 /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
831 /// a class method in its extension.
832 ///
DiagnoseClassExtensionDupMethods(ObjCCategoryDecl * CAT,ObjCInterfaceDecl * ID)833 void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
834 ObjCInterfaceDecl *ID) {
835 if (!ID)
836 return; // Possibly due to previous error
837
838 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
839 for (auto *MD : ID->methods())
840 MethodMap[MD->getSelector()] = MD;
841
842 if (MethodMap.empty())
843 return;
844 for (const auto *Method : CAT->methods()) {
845 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
846 if (PrevMethod &&
847 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
848 !MatchTwoMethodDeclarations(Method, PrevMethod)) {
849 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
850 << Method->getDeclName();
851 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
852 }
853 }
854 }
855
856 /// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
857 Sema::DeclGroupPtrTy
ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,const IdentifierLocPair * IdentList,unsigned NumElts,AttributeList * attrList)858 Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
859 const IdentifierLocPair *IdentList,
860 unsigned NumElts,
861 AttributeList *attrList) {
862 SmallVector<Decl *, 8> DeclsInGroup;
863 for (unsigned i = 0; i != NumElts; ++i) {
864 IdentifierInfo *Ident = IdentList[i].first;
865 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentList[i].second,
866 ForRedeclaration);
867 ObjCProtocolDecl *PDecl
868 = ObjCProtocolDecl::Create(Context, CurContext, Ident,
869 IdentList[i].second, AtProtocolLoc,
870 PrevDecl);
871
872 PushOnScopeChains(PDecl, TUScope);
873 CheckObjCDeclScope(PDecl);
874
875 if (attrList)
876 ProcessDeclAttributeList(TUScope, PDecl, attrList);
877
878 if (PrevDecl)
879 mergeDeclAttributes(PDecl, PrevDecl);
880
881 DeclsInGroup.push_back(PDecl);
882 }
883
884 return BuildDeclaratorGroup(DeclsInGroup, false);
885 }
886
887 Decl *Sema::
ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,IdentifierInfo * ClassName,SourceLocation ClassLoc,IdentifierInfo * CategoryName,SourceLocation CategoryLoc,Decl * const * ProtoRefs,unsigned NumProtoRefs,const SourceLocation * ProtoLocs,SourceLocation EndProtoLoc)888 ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
889 IdentifierInfo *ClassName, SourceLocation ClassLoc,
890 IdentifierInfo *CategoryName,
891 SourceLocation CategoryLoc,
892 Decl * const *ProtoRefs,
893 unsigned NumProtoRefs,
894 const SourceLocation *ProtoLocs,
895 SourceLocation EndProtoLoc) {
896 ObjCCategoryDecl *CDecl;
897 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
898
899 /// Check that class of this category is already completely declared.
900
901 if (!IDecl
902 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
903 diag::err_category_forward_interface,
904 CategoryName == nullptr)) {
905 // Create an invalid ObjCCategoryDecl to serve as context for
906 // the enclosing method declarations. We mark the decl invalid
907 // to make it clear that this isn't a valid AST.
908 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
909 ClassLoc, CategoryLoc, CategoryName,IDecl);
910 CDecl->setInvalidDecl();
911 CurContext->addDecl(CDecl);
912
913 if (!IDecl)
914 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
915 return ActOnObjCContainerStartDefinition(CDecl);
916 }
917
918 if (!CategoryName && IDecl->getImplementation()) {
919 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
920 Diag(IDecl->getImplementation()->getLocation(),
921 diag::note_implementation_declared);
922 }
923
924 if (CategoryName) {
925 /// Check for duplicate interface declaration for this category
926 if (ObjCCategoryDecl *Previous
927 = IDecl->FindCategoryDeclaration(CategoryName)) {
928 // Class extensions can be declared multiple times, categories cannot.
929 Diag(CategoryLoc, diag::warn_dup_category_def)
930 << ClassName << CategoryName;
931 Diag(Previous->getLocation(), diag::note_previous_definition);
932 }
933 }
934
935 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
936 ClassLoc, CategoryLoc, CategoryName, IDecl);
937 // FIXME: PushOnScopeChains?
938 CurContext->addDecl(CDecl);
939
940 if (NumProtoRefs) {
941 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
942 ProtoLocs, Context);
943 // Protocols in the class extension belong to the class.
944 if (CDecl->IsClassExtension())
945 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
946 NumProtoRefs, Context);
947 }
948
949 CheckObjCDeclScope(CDecl);
950 return ActOnObjCContainerStartDefinition(CDecl);
951 }
952
953 /// ActOnStartCategoryImplementation - Perform semantic checks on the
954 /// category implementation declaration and build an ObjCCategoryImplDecl
955 /// object.
ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,IdentifierInfo * ClassName,SourceLocation ClassLoc,IdentifierInfo * CatName,SourceLocation CatLoc)956 Decl *Sema::ActOnStartCategoryImplementation(
957 SourceLocation AtCatImplLoc,
958 IdentifierInfo *ClassName, SourceLocation ClassLoc,
959 IdentifierInfo *CatName, SourceLocation CatLoc) {
960 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
961 ObjCCategoryDecl *CatIDecl = nullptr;
962 if (IDecl && IDecl->hasDefinition()) {
963 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
964 if (!CatIDecl) {
965 // Category @implementation with no corresponding @interface.
966 // Create and install one.
967 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
968 ClassLoc, CatLoc,
969 CatName, IDecl);
970 CatIDecl->setImplicit();
971 }
972 }
973
974 ObjCCategoryImplDecl *CDecl =
975 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
976 ClassLoc, AtCatImplLoc, CatLoc);
977 /// Check that class of this category is already completely declared.
978 if (!IDecl) {
979 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
980 CDecl->setInvalidDecl();
981 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
982 diag::err_undef_interface)) {
983 CDecl->setInvalidDecl();
984 }
985
986 // FIXME: PushOnScopeChains?
987 CurContext->addDecl(CDecl);
988
989 // If the interface is deprecated/unavailable, warn/error about it.
990 if (IDecl)
991 DiagnoseUseOfDecl(IDecl, ClassLoc);
992
993 /// Check that CatName, category name, is not used in another implementation.
994 if (CatIDecl) {
995 if (CatIDecl->getImplementation()) {
996 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
997 << CatName;
998 Diag(CatIDecl->getImplementation()->getLocation(),
999 diag::note_previous_definition);
1000 CDecl->setInvalidDecl();
1001 } else {
1002 CatIDecl->setImplementation(CDecl);
1003 // Warn on implementating category of deprecated class under
1004 // -Wdeprecated-implementations flag.
1005 DiagnoseObjCImplementedDeprecations(*this,
1006 dyn_cast<NamedDecl>(IDecl),
1007 CDecl->getLocation(), 2);
1008 }
1009 }
1010
1011 CheckObjCDeclScope(CDecl);
1012 return ActOnObjCContainerStartDefinition(CDecl);
1013 }
1014
ActOnStartClassImplementation(SourceLocation AtClassImplLoc,IdentifierInfo * ClassName,SourceLocation ClassLoc,IdentifierInfo * SuperClassname,SourceLocation SuperClassLoc)1015 Decl *Sema::ActOnStartClassImplementation(
1016 SourceLocation AtClassImplLoc,
1017 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1018 IdentifierInfo *SuperClassname,
1019 SourceLocation SuperClassLoc) {
1020 ObjCInterfaceDecl *IDecl = nullptr;
1021 // Check for another declaration kind with the same name.
1022 NamedDecl *PrevDecl
1023 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
1024 ForRedeclaration);
1025 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1026 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
1027 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1028 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
1029 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1030 diag::warn_undef_interface);
1031 } else {
1032 // We did not find anything with the name ClassName; try to correct for
1033 // typos in the class name.
1034 ObjCInterfaceValidatorCCC Validator;
1035 TypoCorrection Corrected =
1036 CorrectTypo(DeclarationNameInfo(ClassName, ClassLoc),
1037 LookupOrdinaryName, TUScope, nullptr, Validator,
1038 CTK_NonError);
1039 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1040 // Suggest the (potentially) correct interface name. Don't provide a
1041 // code-modification hint or use the typo name for recovery, because
1042 // this is just a warning. The program may actually be correct.
1043 diagnoseTypo(Corrected,
1044 PDiag(diag::warn_undef_interface_suggest) << ClassName,
1045 /*ErrorRecovery*/false);
1046 } else {
1047 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
1048 }
1049 }
1050
1051 // Check that super class name is valid class name
1052 ObjCInterfaceDecl *SDecl = nullptr;
1053 if (SuperClassname) {
1054 // Check if a different kind of symbol declared in this scope.
1055 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
1056 LookupOrdinaryName);
1057 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1058 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
1059 << SuperClassname;
1060 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1061 } else {
1062 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
1063 if (SDecl && !SDecl->hasDefinition())
1064 SDecl = nullptr;
1065 if (!SDecl)
1066 Diag(SuperClassLoc, diag::err_undef_superclass)
1067 << SuperClassname << ClassName;
1068 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
1069 // This implementation and its interface do not have the same
1070 // super class.
1071 Diag(SuperClassLoc, diag::err_conflicting_super_class)
1072 << SDecl->getDeclName();
1073 Diag(SDecl->getLocation(), diag::note_previous_definition);
1074 }
1075 }
1076 }
1077
1078 if (!IDecl) {
1079 // Legacy case of @implementation with no corresponding @interface.
1080 // Build, chain & install the interface decl into the identifier.
1081
1082 // FIXME: Do we support attributes on the @implementation? If so we should
1083 // copy them over.
1084 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
1085 ClassName, /*PrevDecl=*/nullptr, ClassLoc,
1086 true);
1087 IDecl->startDefinition();
1088 if (SDecl) {
1089 IDecl->setSuperClass(SDecl);
1090 IDecl->setSuperClassLoc(SuperClassLoc);
1091 IDecl->setEndOfDefinitionLoc(SuperClassLoc);
1092 } else {
1093 IDecl->setEndOfDefinitionLoc(ClassLoc);
1094 }
1095
1096 PushOnScopeChains(IDecl, TUScope);
1097 } else {
1098 // Mark the interface as being completed, even if it was just as
1099 // @class ....;
1100 // declaration; the user cannot reopen it.
1101 if (!IDecl->hasDefinition())
1102 IDecl->startDefinition();
1103 }
1104
1105 ObjCImplementationDecl* IMPDecl =
1106 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
1107 ClassLoc, AtClassImplLoc, SuperClassLoc);
1108
1109 if (CheckObjCDeclScope(IMPDecl))
1110 return ActOnObjCContainerStartDefinition(IMPDecl);
1111
1112 // Check that there is no duplicate implementation of this class.
1113 if (IDecl->getImplementation()) {
1114 // FIXME: Don't leak everything!
1115 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
1116 Diag(IDecl->getImplementation()->getLocation(),
1117 diag::note_previous_definition);
1118 IMPDecl->setInvalidDecl();
1119 } else { // add it to the list.
1120 IDecl->setImplementation(IMPDecl);
1121 PushOnScopeChains(IMPDecl, TUScope);
1122 // Warn on implementating deprecated class under
1123 // -Wdeprecated-implementations flag.
1124 DiagnoseObjCImplementedDeprecations(*this,
1125 dyn_cast<NamedDecl>(IDecl),
1126 IMPDecl->getLocation(), 1);
1127 }
1128 return ActOnObjCContainerStartDefinition(IMPDecl);
1129 }
1130
1131 Sema::DeclGroupPtrTy
ActOnFinishObjCImplementation(Decl * ObjCImpDecl,ArrayRef<Decl * > Decls)1132 Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
1133 SmallVector<Decl *, 64> DeclsInGroup;
1134 DeclsInGroup.reserve(Decls.size() + 1);
1135
1136 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
1137 Decl *Dcl = Decls[i];
1138 if (!Dcl)
1139 continue;
1140 if (Dcl->getDeclContext()->isFileContext())
1141 Dcl->setTopLevelDeclInObjCContainer();
1142 DeclsInGroup.push_back(Dcl);
1143 }
1144
1145 DeclsInGroup.push_back(ObjCImpDecl);
1146
1147 return BuildDeclaratorGroup(DeclsInGroup, false);
1148 }
1149
CheckImplementationIvars(ObjCImplementationDecl * ImpDecl,ObjCIvarDecl ** ivars,unsigned numIvars,SourceLocation RBrace)1150 void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
1151 ObjCIvarDecl **ivars, unsigned numIvars,
1152 SourceLocation RBrace) {
1153 assert(ImpDecl && "missing implementation decl");
1154 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
1155 if (!IDecl)
1156 return;
1157 /// Check case of non-existing \@interface decl.
1158 /// (legacy objective-c \@implementation decl without an \@interface decl).
1159 /// Add implementations's ivar to the synthesize class's ivar list.
1160 if (IDecl->isImplicitInterfaceDecl()) {
1161 IDecl->setEndOfDefinitionLoc(RBrace);
1162 // Add ivar's to class's DeclContext.
1163 for (unsigned i = 0, e = numIvars; i != e; ++i) {
1164 ivars[i]->setLexicalDeclContext(ImpDecl);
1165 IDecl->makeDeclVisibleInContext(ivars[i]);
1166 ImpDecl->addDecl(ivars[i]);
1167 }
1168
1169 return;
1170 }
1171 // If implementation has empty ivar list, just return.
1172 if (numIvars == 0)
1173 return;
1174
1175 assert(ivars && "missing @implementation ivars");
1176 if (LangOpts.ObjCRuntime.isNonFragile()) {
1177 if (ImpDecl->getSuperClass())
1178 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
1179 for (unsigned i = 0; i < numIvars; i++) {
1180 ObjCIvarDecl* ImplIvar = ivars[i];
1181 if (const ObjCIvarDecl *ClsIvar =
1182 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
1183 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
1184 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1185 continue;
1186 }
1187 // Check class extensions (unnamed categories) for duplicate ivars.
1188 for (const auto *CDecl : IDecl->visible_extensions()) {
1189 if (const ObjCIvarDecl *ClsExtIvar =
1190 CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
1191 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
1192 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
1193 continue;
1194 }
1195 }
1196 // Instance ivar to Implementation's DeclContext.
1197 ImplIvar->setLexicalDeclContext(ImpDecl);
1198 IDecl->makeDeclVisibleInContext(ImplIvar);
1199 ImpDecl->addDecl(ImplIvar);
1200 }
1201 return;
1202 }
1203 // Check interface's Ivar list against those in the implementation.
1204 // names and types must match.
1205 //
1206 unsigned j = 0;
1207 ObjCInterfaceDecl::ivar_iterator
1208 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
1209 for (; numIvars > 0 && IVI != IVE; ++IVI) {
1210 ObjCIvarDecl* ImplIvar = ivars[j++];
1211 ObjCIvarDecl* ClsIvar = *IVI;
1212 assert (ImplIvar && "missing implementation ivar");
1213 assert (ClsIvar && "missing class ivar");
1214
1215 // First, make sure the types match.
1216 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
1217 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
1218 << ImplIvar->getIdentifier()
1219 << ImplIvar->getType() << ClsIvar->getType();
1220 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1221 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
1222 ImplIvar->getBitWidthValue(Context) !=
1223 ClsIvar->getBitWidthValue(Context)) {
1224 Diag(ImplIvar->getBitWidth()->getLocStart(),
1225 diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier();
1226 Diag(ClsIvar->getBitWidth()->getLocStart(),
1227 diag::note_previous_definition);
1228 }
1229 // Make sure the names are identical.
1230 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
1231 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
1232 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
1233 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1234 }
1235 --numIvars;
1236 }
1237
1238 if (numIvars > 0)
1239 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
1240 else if (IVI != IVE)
1241 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
1242 }
1243
WarnUndefinedMethod(Sema & S,SourceLocation ImpLoc,ObjCMethodDecl * method,bool & IncompleteImpl,unsigned DiagID,NamedDecl * NeededFor=nullptr)1244 static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
1245 ObjCMethodDecl *method,
1246 bool &IncompleteImpl,
1247 unsigned DiagID,
1248 NamedDecl *NeededFor = nullptr) {
1249 // No point warning no definition of method which is 'unavailable'.
1250 switch (method->getAvailability()) {
1251 case AR_Available:
1252 case AR_Deprecated:
1253 break;
1254
1255 // Don't warn about unavailable or not-yet-introduced methods.
1256 case AR_NotYetIntroduced:
1257 case AR_Unavailable:
1258 return;
1259 }
1260
1261 // FIXME: For now ignore 'IncompleteImpl'.
1262 // Previously we grouped all unimplemented methods under a single
1263 // warning, but some users strongly voiced that they would prefer
1264 // separate warnings. We will give that approach a try, as that
1265 // matches what we do with protocols.
1266 {
1267 const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
1268 B << method;
1269 if (NeededFor)
1270 B << NeededFor;
1271 }
1272
1273 // Issue a note to the original declaration.
1274 SourceLocation MethodLoc = method->getLocStart();
1275 if (MethodLoc.isValid())
1276 S.Diag(MethodLoc, diag::note_method_declared_at) << method;
1277 }
1278
1279 /// Determines if type B can be substituted for type A. Returns true if we can
1280 /// guarantee that anything that the user will do to an object of type A can
1281 /// also be done to an object of type B. This is trivially true if the two
1282 /// types are the same, or if B is a subclass of A. It becomes more complex
1283 /// in cases where protocols are involved.
1284 ///
1285 /// Object types in Objective-C describe the minimum requirements for an
1286 /// object, rather than providing a complete description of a type. For
1287 /// example, if A is a subclass of B, then B* may refer to an instance of A.
1288 /// The principle of substitutability means that we may use an instance of A
1289 /// anywhere that we may use an instance of B - it will implement all of the
1290 /// ivars of B and all of the methods of B.
1291 ///
1292 /// This substitutability is important when type checking methods, because
1293 /// the implementation may have stricter type definitions than the interface.
1294 /// The interface specifies minimum requirements, but the implementation may
1295 /// have more accurate ones. For example, a method may privately accept
1296 /// instances of B, but only publish that it accepts instances of A. Any
1297 /// object passed to it will be type checked against B, and so will implicitly
1298 /// by a valid A*. Similarly, a method may return a subclass of the class that
1299 /// it is declared as returning.
1300 ///
1301 /// This is most important when considering subclassing. A method in a
1302 /// subclass must accept any object as an argument that its superclass's
1303 /// implementation accepts. It may, however, accept a more general type
1304 /// without breaking substitutability (i.e. you can still use the subclass
1305 /// anywhere that you can use the superclass, but not vice versa). The
1306 /// converse requirement applies to return types: the return type for a
1307 /// subclass method must be a valid object of the kind that the superclass
1308 /// advertises, but it may be specified more accurately. This avoids the need
1309 /// for explicit down-casting by callers.
1310 ///
1311 /// Note: This is a stricter requirement than for assignment.
isObjCTypeSubstitutable(ASTContext & Context,const ObjCObjectPointerType * A,const ObjCObjectPointerType * B,bool rejectId)1312 static bool isObjCTypeSubstitutable(ASTContext &Context,
1313 const ObjCObjectPointerType *A,
1314 const ObjCObjectPointerType *B,
1315 bool rejectId) {
1316 // Reject a protocol-unqualified id.
1317 if (rejectId && B->isObjCIdType()) return false;
1318
1319 // If B is a qualified id, then A must also be a qualified id and it must
1320 // implement all of the protocols in B. It may not be a qualified class.
1321 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
1322 // stricter definition so it is not substitutable for id<A>.
1323 if (B->isObjCQualifiedIdType()) {
1324 return A->isObjCQualifiedIdType() &&
1325 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
1326 QualType(B,0),
1327 false);
1328 }
1329
1330 /*
1331 // id is a special type that bypasses type checking completely. We want a
1332 // warning when it is used in one place but not another.
1333 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
1334
1335
1336 // If B is a qualified id, then A must also be a qualified id (which it isn't
1337 // if we've got this far)
1338 if (B->isObjCQualifiedIdType()) return false;
1339 */
1340
1341 // Now we know that A and B are (potentially-qualified) class types. The
1342 // normal rules for assignment apply.
1343 return Context.canAssignObjCInterfaces(A, B);
1344 }
1345
getTypeRange(TypeSourceInfo * TSI)1346 static SourceRange getTypeRange(TypeSourceInfo *TSI) {
1347 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
1348 }
1349
CheckMethodOverrideReturn(Sema & S,ObjCMethodDecl * MethodImpl,ObjCMethodDecl * MethodDecl,bool IsProtocolMethodDecl,bool IsOverridingMode,bool Warn)1350 static bool CheckMethodOverrideReturn(Sema &S,
1351 ObjCMethodDecl *MethodImpl,
1352 ObjCMethodDecl *MethodDecl,
1353 bool IsProtocolMethodDecl,
1354 bool IsOverridingMode,
1355 bool Warn) {
1356 if (IsProtocolMethodDecl &&
1357 (MethodDecl->getObjCDeclQualifier() !=
1358 MethodImpl->getObjCDeclQualifier())) {
1359 if (Warn) {
1360 S.Diag(MethodImpl->getLocation(),
1361 (IsOverridingMode
1362 ? diag::warn_conflicting_overriding_ret_type_modifiers
1363 : diag::warn_conflicting_ret_type_modifiers))
1364 << MethodImpl->getDeclName()
1365 << getTypeRange(MethodImpl->getReturnTypeSourceInfo());
1366 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
1367 << getTypeRange(MethodDecl->getReturnTypeSourceInfo());
1368 }
1369 else
1370 return false;
1371 }
1372
1373 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
1374 MethodDecl->getReturnType()))
1375 return true;
1376 if (!Warn)
1377 return false;
1378
1379 unsigned DiagID =
1380 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
1381 : diag::warn_conflicting_ret_types;
1382
1383 // Mismatches between ObjC pointers go into a different warning
1384 // category, and sometimes they're even completely whitelisted.
1385 if (const ObjCObjectPointerType *ImplPtrTy =
1386 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
1387 if (const ObjCObjectPointerType *IfacePtrTy =
1388 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
1389 // Allow non-matching return types as long as they don't violate
1390 // the principle of substitutability. Specifically, we permit
1391 // return types that are subclasses of the declared return type,
1392 // or that are more-qualified versions of the declared type.
1393 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
1394 return false;
1395
1396 DiagID =
1397 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
1398 : diag::warn_non_covariant_ret_types;
1399 }
1400 }
1401
1402 S.Diag(MethodImpl->getLocation(), DiagID)
1403 << MethodImpl->getDeclName() << MethodDecl->getReturnType()
1404 << MethodImpl->getReturnType()
1405 << getTypeRange(MethodImpl->getReturnTypeSourceInfo());
1406 S.Diag(MethodDecl->getLocation(), IsOverridingMode
1407 ? diag::note_previous_declaration
1408 : diag::note_previous_definition)
1409 << getTypeRange(MethodDecl->getReturnTypeSourceInfo());
1410 return false;
1411 }
1412
CheckMethodOverrideParam(Sema & S,ObjCMethodDecl * MethodImpl,ObjCMethodDecl * MethodDecl,ParmVarDecl * ImplVar,ParmVarDecl * IfaceVar,bool IsProtocolMethodDecl,bool IsOverridingMode,bool Warn)1413 static bool CheckMethodOverrideParam(Sema &S,
1414 ObjCMethodDecl *MethodImpl,
1415 ObjCMethodDecl *MethodDecl,
1416 ParmVarDecl *ImplVar,
1417 ParmVarDecl *IfaceVar,
1418 bool IsProtocolMethodDecl,
1419 bool IsOverridingMode,
1420 bool Warn) {
1421 if (IsProtocolMethodDecl &&
1422 (ImplVar->getObjCDeclQualifier() !=
1423 IfaceVar->getObjCDeclQualifier())) {
1424 if (Warn) {
1425 if (IsOverridingMode)
1426 S.Diag(ImplVar->getLocation(),
1427 diag::warn_conflicting_overriding_param_modifiers)
1428 << getTypeRange(ImplVar->getTypeSourceInfo())
1429 << MethodImpl->getDeclName();
1430 else S.Diag(ImplVar->getLocation(),
1431 diag::warn_conflicting_param_modifiers)
1432 << getTypeRange(ImplVar->getTypeSourceInfo())
1433 << MethodImpl->getDeclName();
1434 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
1435 << getTypeRange(IfaceVar->getTypeSourceInfo());
1436 }
1437 else
1438 return false;
1439 }
1440
1441 QualType ImplTy = ImplVar->getType();
1442 QualType IfaceTy = IfaceVar->getType();
1443
1444 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
1445 return true;
1446
1447 if (!Warn)
1448 return false;
1449 unsigned DiagID =
1450 IsOverridingMode ? diag::warn_conflicting_overriding_param_types
1451 : diag::warn_conflicting_param_types;
1452
1453 // Mismatches between ObjC pointers go into a different warning
1454 // category, and sometimes they're even completely whitelisted.
1455 if (const ObjCObjectPointerType *ImplPtrTy =
1456 ImplTy->getAs<ObjCObjectPointerType>()) {
1457 if (const ObjCObjectPointerType *IfacePtrTy =
1458 IfaceTy->getAs<ObjCObjectPointerType>()) {
1459 // Allow non-matching argument types as long as they don't
1460 // violate the principle of substitutability. Specifically, the
1461 // implementation must accept any objects that the superclass
1462 // accepts, however it may also accept others.
1463 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
1464 return false;
1465
1466 DiagID =
1467 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
1468 : diag::warn_non_contravariant_param_types;
1469 }
1470 }
1471
1472 S.Diag(ImplVar->getLocation(), DiagID)
1473 << getTypeRange(ImplVar->getTypeSourceInfo())
1474 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
1475 S.Diag(IfaceVar->getLocation(),
1476 (IsOverridingMode ? diag::note_previous_declaration
1477 : diag::note_previous_definition))
1478 << getTypeRange(IfaceVar->getTypeSourceInfo());
1479 return false;
1480 }
1481
1482 /// In ARC, check whether the conventional meanings of the two methods
1483 /// match. If they don't, it's a hard error.
checkMethodFamilyMismatch(Sema & S,ObjCMethodDecl * impl,ObjCMethodDecl * decl)1484 static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
1485 ObjCMethodDecl *decl) {
1486 ObjCMethodFamily implFamily = impl->getMethodFamily();
1487 ObjCMethodFamily declFamily = decl->getMethodFamily();
1488 if (implFamily == declFamily) return false;
1489
1490 // Since conventions are sorted by selector, the only possibility is
1491 // that the types differ enough to cause one selector or the other
1492 // to fall out of the family.
1493 assert(implFamily == OMF_None || declFamily == OMF_None);
1494
1495 // No further diagnostics required on invalid declarations.
1496 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
1497
1498 const ObjCMethodDecl *unmatched = impl;
1499 ObjCMethodFamily family = declFamily;
1500 unsigned errorID = diag::err_arc_lost_method_convention;
1501 unsigned noteID = diag::note_arc_lost_method_convention;
1502 if (declFamily == OMF_None) {
1503 unmatched = decl;
1504 family = implFamily;
1505 errorID = diag::err_arc_gained_method_convention;
1506 noteID = diag::note_arc_gained_method_convention;
1507 }
1508
1509 // Indexes into a %select clause in the diagnostic.
1510 enum FamilySelector {
1511 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
1512 };
1513 FamilySelector familySelector = FamilySelector();
1514
1515 switch (family) {
1516 case OMF_None: llvm_unreachable("logic error, no method convention");
1517 case OMF_retain:
1518 case OMF_release:
1519 case OMF_autorelease:
1520 case OMF_dealloc:
1521 case OMF_finalize:
1522 case OMF_retainCount:
1523 case OMF_self:
1524 case OMF_performSelector:
1525 // Mismatches for these methods don't change ownership
1526 // conventions, so we don't care.
1527 return false;
1528
1529 case OMF_init: familySelector = F_init; break;
1530 case OMF_alloc: familySelector = F_alloc; break;
1531 case OMF_copy: familySelector = F_copy; break;
1532 case OMF_mutableCopy: familySelector = F_mutableCopy; break;
1533 case OMF_new: familySelector = F_new; break;
1534 }
1535
1536 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
1537 ReasonSelector reasonSelector;
1538
1539 // The only reason these methods don't fall within their families is
1540 // due to unusual result types.
1541 if (unmatched->getReturnType()->isObjCObjectPointerType()) {
1542 reasonSelector = R_UnrelatedReturn;
1543 } else {
1544 reasonSelector = R_NonObjectReturn;
1545 }
1546
1547 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
1548 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
1549
1550 return true;
1551 }
1552
WarnConflictingTypedMethods(ObjCMethodDecl * ImpMethodDecl,ObjCMethodDecl * MethodDecl,bool IsProtocolMethodDecl)1553 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
1554 ObjCMethodDecl *MethodDecl,
1555 bool IsProtocolMethodDecl) {
1556 if (getLangOpts().ObjCAutoRefCount &&
1557 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
1558 return;
1559
1560 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
1561 IsProtocolMethodDecl, false,
1562 true);
1563
1564 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
1565 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
1566 EF = MethodDecl->param_end();
1567 IM != EM && IF != EF; ++IM, ++IF) {
1568 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
1569 IsProtocolMethodDecl, false, true);
1570 }
1571
1572 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
1573 Diag(ImpMethodDecl->getLocation(),
1574 diag::warn_conflicting_variadic);
1575 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
1576 }
1577 }
1578
CheckConflictingOverridingMethod(ObjCMethodDecl * Method,ObjCMethodDecl * Overridden,bool IsProtocolMethodDecl)1579 void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
1580 ObjCMethodDecl *Overridden,
1581 bool IsProtocolMethodDecl) {
1582
1583 CheckMethodOverrideReturn(*this, Method, Overridden,
1584 IsProtocolMethodDecl, true,
1585 true);
1586
1587 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
1588 IF = Overridden->param_begin(), EM = Method->param_end(),
1589 EF = Overridden->param_end();
1590 IM != EM && IF != EF; ++IM, ++IF) {
1591 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
1592 IsProtocolMethodDecl, true, true);
1593 }
1594
1595 if (Method->isVariadic() != Overridden->isVariadic()) {
1596 Diag(Method->getLocation(),
1597 diag::warn_conflicting_overriding_variadic);
1598 Diag(Overridden->getLocation(), diag::note_previous_declaration);
1599 }
1600 }
1601
1602 /// WarnExactTypedMethods - This routine issues a warning if method
1603 /// implementation declaration matches exactly that of its declaration.
WarnExactTypedMethods(ObjCMethodDecl * ImpMethodDecl,ObjCMethodDecl * MethodDecl,bool IsProtocolMethodDecl)1604 void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
1605 ObjCMethodDecl *MethodDecl,
1606 bool IsProtocolMethodDecl) {
1607 // don't issue warning when protocol method is optional because primary
1608 // class is not required to implement it and it is safe for protocol
1609 // to implement it.
1610 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
1611 return;
1612 // don't issue warning when primary class's method is
1613 // depecated/unavailable.
1614 if (MethodDecl->hasAttr<UnavailableAttr>() ||
1615 MethodDecl->hasAttr<DeprecatedAttr>())
1616 return;
1617
1618 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
1619 IsProtocolMethodDecl, false, false);
1620 if (match)
1621 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
1622 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
1623 EF = MethodDecl->param_end();
1624 IM != EM && IF != EF; ++IM, ++IF) {
1625 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
1626 *IM, *IF,
1627 IsProtocolMethodDecl, false, false);
1628 if (!match)
1629 break;
1630 }
1631 if (match)
1632 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
1633 if (match)
1634 match = !(MethodDecl->isClassMethod() &&
1635 MethodDecl->getSelector() == GetNullarySelector("load", Context));
1636
1637 if (match) {
1638 Diag(ImpMethodDecl->getLocation(),
1639 diag::warn_category_method_impl_match);
1640 Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
1641 << MethodDecl->getDeclName();
1642 }
1643 }
1644
1645 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
1646 /// improve the efficiency of selector lookups and type checking by associating
1647 /// with each protocol / interface / category the flattened instance tables. If
1648 /// we used an immutable set to keep the table then it wouldn't add significant
1649 /// memory cost and it would be handy for lookups.
1650
1651 typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
1652 typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
1653
findProtocolsWithExplicitImpls(const ObjCProtocolDecl * PDecl,ProtocolNameSet & PNS)1654 static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
1655 ProtocolNameSet &PNS) {
1656 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
1657 PNS.insert(PDecl->getIdentifier());
1658 for (const auto *PI : PDecl->protocols())
1659 findProtocolsWithExplicitImpls(PI, PNS);
1660 }
1661
1662 /// Recursively populates a set with all conformed protocols in a class
1663 /// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
1664 /// attribute.
findProtocolsWithExplicitImpls(const ObjCInterfaceDecl * Super,ProtocolNameSet & PNS)1665 static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
1666 ProtocolNameSet &PNS) {
1667 if (!Super)
1668 return;
1669
1670 for (const auto *I : Super->all_referenced_protocols())
1671 findProtocolsWithExplicitImpls(I, PNS);
1672
1673 findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
1674 }
1675
1676 /// CheckProtocolMethodDefs - This routine checks unimplemented methods
1677 /// Declared in protocol, and those referenced by it.
CheckProtocolMethodDefs(Sema & S,SourceLocation ImpLoc,ObjCProtocolDecl * PDecl,bool & IncompleteImpl,const Sema::SelectorSet & InsMap,const Sema::SelectorSet & ClsMap,ObjCContainerDecl * CDecl,LazyProtocolNameSet & ProtocolsExplictImpl)1678 static void CheckProtocolMethodDefs(Sema &S,
1679 SourceLocation ImpLoc,
1680 ObjCProtocolDecl *PDecl,
1681 bool& IncompleteImpl,
1682 const Sema::SelectorSet &InsMap,
1683 const Sema::SelectorSet &ClsMap,
1684 ObjCContainerDecl *CDecl,
1685 LazyProtocolNameSet &ProtocolsExplictImpl) {
1686 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
1687 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
1688 : dyn_cast<ObjCInterfaceDecl>(CDecl);
1689 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
1690
1691 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
1692 ObjCInterfaceDecl *NSIDecl = nullptr;
1693
1694 // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
1695 // then we should check if any class in the super class hierarchy also
1696 // conforms to this protocol, either directly or via protocol inheritance.
1697 // If so, we can skip checking this protocol completely because we
1698 // know that a parent class already satisfies this protocol.
1699 //
1700 // Note: we could generalize this logic for all protocols, and merely
1701 // add the limit on looking at the super class chain for just
1702 // specially marked protocols. This may be a good optimization. This
1703 // change is restricted to 'objc_protocol_requires_explicit_implementation'
1704 // protocols for now for controlled evaluation.
1705 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
1706 if (!ProtocolsExplictImpl) {
1707 ProtocolsExplictImpl.reset(new ProtocolNameSet);
1708 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
1709 }
1710 if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
1711 ProtocolsExplictImpl->end())
1712 return;
1713
1714 // If no super class conforms to the protocol, we should not search
1715 // for methods in the super class to implicitly satisfy the protocol.
1716 Super = nullptr;
1717 }
1718
1719 if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
1720 // check to see if class implements forwardInvocation method and objects
1721 // of this class are derived from 'NSProxy' so that to forward requests
1722 // from one object to another.
1723 // Under such conditions, which means that every method possible is
1724 // implemented in the class, we should not issue "Method definition not
1725 // found" warnings.
1726 // FIXME: Use a general GetUnarySelector method for this.
1727 IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
1728 Selector fISelector = S.Context.Selectors.getSelector(1, &II);
1729 if (InsMap.count(fISelector))
1730 // Is IDecl derived from 'NSProxy'? If so, no instance methods
1731 // need be implemented in the implementation.
1732 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
1733 }
1734
1735 // If this is a forward protocol declaration, get its definition.
1736 if (!PDecl->isThisDeclarationADefinition() &&
1737 PDecl->getDefinition())
1738 PDecl = PDecl->getDefinition();
1739
1740 // If a method lookup fails locally we still need to look and see if
1741 // the method was implemented by a base class or an inherited
1742 // protocol. This lookup is slow, but occurs rarely in correct code
1743 // and otherwise would terminate in a warning.
1744
1745 // check unimplemented instance methods.
1746 if (!NSIDecl)
1747 for (auto *method : PDecl->instance_methods()) {
1748 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1749 !method->isPropertyAccessor() &&
1750 !InsMap.count(method->getSelector()) &&
1751 (!Super || !Super->lookupMethod(method->getSelector(),
1752 true /* instance */,
1753 false /* shallowCategory */,
1754 true /* followsSuper */,
1755 nullptr /* category */))) {
1756 // If a method is not implemented in the category implementation but
1757 // has been declared in its primary class, superclass,
1758 // or in one of their protocols, no need to issue the warning.
1759 // This is because method will be implemented in the primary class
1760 // or one of its super class implementation.
1761
1762 // Ugly, but necessary. Method declared in protcol might have
1763 // have been synthesized due to a property declared in the class which
1764 // uses the protocol.
1765 if (ObjCMethodDecl *MethodInClass =
1766 IDecl->lookupMethod(method->getSelector(),
1767 true /* instance */,
1768 true /* shallowCategoryLookup */,
1769 false /* followSuper */))
1770 if (C || MethodInClass->isPropertyAccessor())
1771 continue;
1772 unsigned DIAG = diag::warn_unimplemented_protocol_method;
1773 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
1774 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
1775 PDecl);
1776 }
1777 }
1778 }
1779 // check unimplemented class methods
1780 for (auto *method : PDecl->class_methods()) {
1781 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1782 !ClsMap.count(method->getSelector()) &&
1783 (!Super || !Super->lookupMethod(method->getSelector(),
1784 false /* class method */,
1785 false /* shallowCategoryLookup */,
1786 true /* followSuper */,
1787 nullptr /* category */))) {
1788 // See above comment for instance method lookups.
1789 if (C && IDecl->lookupMethod(method->getSelector(),
1790 false /* class */,
1791 true /* shallowCategoryLookup */,
1792 false /* followSuper */))
1793 continue;
1794
1795 unsigned DIAG = diag::warn_unimplemented_protocol_method;
1796 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
1797 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
1798 }
1799 }
1800 }
1801 // Check on this protocols's referenced protocols, recursively.
1802 for (auto *PI : PDecl->protocols())
1803 CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
1804 CDecl, ProtocolsExplictImpl);
1805 }
1806
1807 /// MatchAllMethodDeclarations - Check methods declared in interface
1808 /// or protocol against those declared in their implementations.
1809 ///
MatchAllMethodDeclarations(const SelectorSet & InsMap,const SelectorSet & ClsMap,SelectorSet & InsMapSeen,SelectorSet & ClsMapSeen,ObjCImplDecl * IMPDecl,ObjCContainerDecl * CDecl,bool & IncompleteImpl,bool ImmediateClass,bool WarnCategoryMethodImpl)1810 void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
1811 const SelectorSet &ClsMap,
1812 SelectorSet &InsMapSeen,
1813 SelectorSet &ClsMapSeen,
1814 ObjCImplDecl* IMPDecl,
1815 ObjCContainerDecl* CDecl,
1816 bool &IncompleteImpl,
1817 bool ImmediateClass,
1818 bool WarnCategoryMethodImpl) {
1819 // Check and see if instance methods in class interface have been
1820 // implemented in the implementation class. If so, their types match.
1821 for (auto *I : CDecl->instance_methods()) {
1822 if (!InsMapSeen.insert(I->getSelector()))
1823 continue;
1824 if (!I->isPropertyAccessor() &&
1825 !InsMap.count(I->getSelector())) {
1826 if (ImmediateClass)
1827 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
1828 diag::warn_undef_method_impl);
1829 continue;
1830 } else {
1831 ObjCMethodDecl *ImpMethodDecl =
1832 IMPDecl->getInstanceMethod(I->getSelector());
1833 assert(CDecl->getInstanceMethod(I->getSelector()) &&
1834 "Expected to find the method through lookup as well");
1835 // ImpMethodDecl may be null as in a @dynamic property.
1836 if (ImpMethodDecl) {
1837 if (!WarnCategoryMethodImpl)
1838 WarnConflictingTypedMethods(ImpMethodDecl, I,
1839 isa<ObjCProtocolDecl>(CDecl));
1840 else if (!I->isPropertyAccessor())
1841 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
1842 }
1843 }
1844 }
1845
1846 // Check and see if class methods in class interface have been
1847 // implemented in the implementation class. If so, their types match.
1848 for (auto *I : CDecl->class_methods()) {
1849 if (!ClsMapSeen.insert(I->getSelector()))
1850 continue;
1851 if (!ClsMap.count(I->getSelector())) {
1852 if (ImmediateClass)
1853 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
1854 diag::warn_undef_method_impl);
1855 } else {
1856 ObjCMethodDecl *ImpMethodDecl =
1857 IMPDecl->getClassMethod(I->getSelector());
1858 assert(CDecl->getClassMethod(I->getSelector()) &&
1859 "Expected to find the method through lookup as well");
1860 if (!WarnCategoryMethodImpl)
1861 WarnConflictingTypedMethods(ImpMethodDecl, I,
1862 isa<ObjCProtocolDecl>(CDecl));
1863 else
1864 WarnExactTypedMethods(ImpMethodDecl, I,
1865 isa<ObjCProtocolDecl>(CDecl));
1866 }
1867 }
1868
1869 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
1870 // Also, check for methods declared in protocols inherited by
1871 // this protocol.
1872 for (auto *PI : PD->protocols())
1873 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1874 IMPDecl, PI, IncompleteImpl, false,
1875 WarnCategoryMethodImpl);
1876 }
1877
1878 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
1879 // when checking that methods in implementation match their declaration,
1880 // i.e. when WarnCategoryMethodImpl is false, check declarations in class
1881 // extension; as well as those in categories.
1882 if (!WarnCategoryMethodImpl) {
1883 for (auto *Cat : I->visible_categories())
1884 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1885 IMPDecl, Cat, IncompleteImpl, false,
1886 WarnCategoryMethodImpl);
1887 } else {
1888 // Also methods in class extensions need be looked at next.
1889 for (auto *Ext : I->visible_extensions())
1890 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1891 IMPDecl, Ext, IncompleteImpl, false,
1892 WarnCategoryMethodImpl);
1893 }
1894
1895 // Check for any implementation of a methods declared in protocol.
1896 for (auto *PI : I->all_referenced_protocols())
1897 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1898 IMPDecl, PI, IncompleteImpl, false,
1899 WarnCategoryMethodImpl);
1900
1901 // FIXME. For now, we are not checking for extact match of methods
1902 // in category implementation and its primary class's super class.
1903 if (!WarnCategoryMethodImpl && I->getSuperClass())
1904 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1905 IMPDecl,
1906 I->getSuperClass(), IncompleteImpl, false);
1907 }
1908 }
1909
1910 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
1911 /// category matches with those implemented in its primary class and
1912 /// warns each time an exact match is found.
CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl * CatIMPDecl)1913 void Sema::CheckCategoryVsClassMethodMatches(
1914 ObjCCategoryImplDecl *CatIMPDecl) {
1915 // Get category's primary class.
1916 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
1917 if (!CatDecl)
1918 return;
1919 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
1920 if (!IDecl)
1921 return;
1922 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
1923 SelectorSet InsMap, ClsMap;
1924
1925 for (const auto *I : CatIMPDecl->instance_methods()) {
1926 Selector Sel = I->getSelector();
1927 // When checking for methods implemented in the category, skip over
1928 // those declared in category class's super class. This is because
1929 // the super class must implement the method.
1930 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
1931 continue;
1932 InsMap.insert(Sel);
1933 }
1934
1935 for (const auto *I : CatIMPDecl->class_methods()) {
1936 Selector Sel = I->getSelector();
1937 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
1938 continue;
1939 ClsMap.insert(Sel);
1940 }
1941 if (InsMap.empty() && ClsMap.empty())
1942 return;
1943
1944 SelectorSet InsMapSeen, ClsMapSeen;
1945 bool IncompleteImpl = false;
1946 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1947 CatIMPDecl, IDecl,
1948 IncompleteImpl, false,
1949 true /*WarnCategoryMethodImpl*/);
1950 }
1951
ImplMethodsVsClassMethods(Scope * S,ObjCImplDecl * IMPDecl,ObjCContainerDecl * CDecl,bool IncompleteImpl)1952 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
1953 ObjCContainerDecl* CDecl,
1954 bool IncompleteImpl) {
1955 SelectorSet InsMap;
1956 // Check and see if instance methods in class interface have been
1957 // implemented in the implementation class.
1958 for (const auto *I : IMPDecl->instance_methods())
1959 InsMap.insert(I->getSelector());
1960
1961 // Check and see if properties declared in the interface have either 1)
1962 // an implementation or 2) there is a @synthesize/@dynamic implementation
1963 // of the property in the @implementation.
1964 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1965 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
1966 LangOpts.ObjCRuntime.isNonFragile() &&
1967 !IDecl->isObjCRequiresPropertyDefs();
1968 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
1969 }
1970
1971 SelectorSet ClsMap;
1972 for (const auto *I : IMPDecl->class_methods())
1973 ClsMap.insert(I->getSelector());
1974
1975 // Check for type conflict of methods declared in a class/protocol and
1976 // its implementation; if any.
1977 SelectorSet InsMapSeen, ClsMapSeen;
1978 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1979 IMPDecl, CDecl,
1980 IncompleteImpl, true);
1981
1982 // check all methods implemented in category against those declared
1983 // in its primary class.
1984 if (ObjCCategoryImplDecl *CatDecl =
1985 dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
1986 CheckCategoryVsClassMethodMatches(CatDecl);
1987
1988 // Check the protocol list for unimplemented methods in the @implementation
1989 // class.
1990 // Check and see if class methods in class interface have been
1991 // implemented in the implementation class.
1992
1993 LazyProtocolNameSet ExplicitImplProtocols;
1994
1995 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
1996 for (auto *PI : I->all_referenced_protocols())
1997 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl,
1998 InsMap, ClsMap, I, ExplicitImplProtocols);
1999 // Check class extensions (unnamed categories)
2000 for (auto *Ext : I->visible_extensions())
2001 ImplMethodsVsClassMethods(S, IMPDecl, Ext, IncompleteImpl);
2002 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2003 // For extended class, unimplemented methods in its protocols will
2004 // be reported in the primary class.
2005 if (!C->IsClassExtension()) {
2006 for (auto *P : C->protocols())
2007 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P,
2008 IncompleteImpl, InsMap, ClsMap, CDecl,
2009 ExplicitImplProtocols);
2010 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
2011 /* SynthesizeProperties */ false);
2012 }
2013 } else
2014 llvm_unreachable("invalid ObjCContainerDecl type.");
2015 }
2016
2017 /// ActOnForwardClassDeclaration -
2018 Sema::DeclGroupPtrTy
ActOnForwardClassDeclaration(SourceLocation AtClassLoc,IdentifierInfo ** IdentList,SourceLocation * IdentLocs,unsigned NumElts)2019 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
2020 IdentifierInfo **IdentList,
2021 SourceLocation *IdentLocs,
2022 unsigned NumElts) {
2023 SmallVector<Decl *, 8> DeclsInGroup;
2024 for (unsigned i = 0; i != NumElts; ++i) {
2025 // Check for another declaration kind with the same name.
2026 NamedDecl *PrevDecl
2027 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
2028 LookupOrdinaryName, ForRedeclaration);
2029 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
2030 // GCC apparently allows the following idiom:
2031 //
2032 // typedef NSObject < XCElementTogglerP > XCElementToggler;
2033 // @class XCElementToggler;
2034 //
2035 // Here we have chosen to ignore the forward class declaration
2036 // with a warning. Since this is the implied behavior.
2037 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
2038 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
2039 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
2040 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2041 } else {
2042 // a forward class declaration matching a typedef name of a class refers
2043 // to the underlying class. Just ignore the forward class with a warning
2044 // as this will force the intended behavior which is to lookup the typedef
2045 // name.
2046 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
2047 Diag(AtClassLoc, diag::warn_forward_class_redefinition) << IdentList[i];
2048 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2049 continue;
2050 }
2051 }
2052 }
2053
2054 // Create a declaration to describe this forward declaration.
2055 ObjCInterfaceDecl *PrevIDecl
2056 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
2057
2058 IdentifierInfo *ClassName = IdentList[i];
2059 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
2060 // A previous decl with a different name is because of
2061 // @compatibility_alias, for example:
2062 // \code
2063 // @class NewImage;
2064 // @compatibility_alias OldImage NewImage;
2065 // \endcode
2066 // A lookup for 'OldImage' will return the 'NewImage' decl.
2067 //
2068 // In such a case use the real declaration name, instead of the alias one,
2069 // otherwise we will break IdentifierResolver and redecls-chain invariants.
2070 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
2071 // has been aliased.
2072 ClassName = PrevIDecl->getIdentifier();
2073 }
2074
2075 ObjCInterfaceDecl *IDecl
2076 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
2077 ClassName, PrevIDecl, IdentLocs[i]);
2078 IDecl->setAtEndRange(IdentLocs[i]);
2079
2080 PushOnScopeChains(IDecl, TUScope);
2081 CheckObjCDeclScope(IDecl);
2082 DeclsInGroup.push_back(IDecl);
2083 }
2084
2085 return BuildDeclaratorGroup(DeclsInGroup, false);
2086 }
2087
2088 static bool tryMatchRecordTypes(ASTContext &Context,
2089 Sema::MethodMatchStrategy strategy,
2090 const Type *left, const Type *right);
2091
matchTypes(ASTContext & Context,Sema::MethodMatchStrategy strategy,QualType leftQT,QualType rightQT)2092 static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
2093 QualType leftQT, QualType rightQT) {
2094 const Type *left =
2095 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
2096 const Type *right =
2097 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
2098
2099 if (left == right) return true;
2100
2101 // If we're doing a strict match, the types have to match exactly.
2102 if (strategy == Sema::MMS_strict) return false;
2103
2104 if (left->isIncompleteType() || right->isIncompleteType()) return false;
2105
2106 // Otherwise, use this absurdly complicated algorithm to try to
2107 // validate the basic, low-level compatibility of the two types.
2108
2109 // As a minimum, require the sizes and alignments to match.
2110 if (Context.getTypeInfo(left) != Context.getTypeInfo(right))
2111 return false;
2112
2113 // Consider all the kinds of non-dependent canonical types:
2114 // - functions and arrays aren't possible as return and parameter types
2115
2116 // - vector types of equal size can be arbitrarily mixed
2117 if (isa<VectorType>(left)) return isa<VectorType>(right);
2118 if (isa<VectorType>(right)) return false;
2119
2120 // - references should only match references of identical type
2121 // - structs, unions, and Objective-C objects must match more-or-less
2122 // exactly
2123 // - everything else should be a scalar
2124 if (!left->isScalarType() || !right->isScalarType())
2125 return tryMatchRecordTypes(Context, strategy, left, right);
2126
2127 // Make scalars agree in kind, except count bools as chars, and group
2128 // all non-member pointers together.
2129 Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
2130 Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
2131 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
2132 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
2133 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
2134 leftSK = Type::STK_ObjCObjectPointer;
2135 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
2136 rightSK = Type::STK_ObjCObjectPointer;
2137
2138 // Note that data member pointers and function member pointers don't
2139 // intermix because of the size differences.
2140
2141 return (leftSK == rightSK);
2142 }
2143
tryMatchRecordTypes(ASTContext & Context,Sema::MethodMatchStrategy strategy,const Type * lt,const Type * rt)2144 static bool tryMatchRecordTypes(ASTContext &Context,
2145 Sema::MethodMatchStrategy strategy,
2146 const Type *lt, const Type *rt) {
2147 assert(lt && rt && lt != rt);
2148
2149 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
2150 RecordDecl *left = cast<RecordType>(lt)->getDecl();
2151 RecordDecl *right = cast<RecordType>(rt)->getDecl();
2152
2153 // Require union-hood to match.
2154 if (left->isUnion() != right->isUnion()) return false;
2155
2156 // Require an exact match if either is non-POD.
2157 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
2158 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
2159 return false;
2160
2161 // Require size and alignment to match.
2162 if (Context.getTypeInfo(lt) != Context.getTypeInfo(rt)) return false;
2163
2164 // Require fields to match.
2165 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
2166 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
2167 for (; li != le && ri != re; ++li, ++ri) {
2168 if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
2169 return false;
2170 }
2171 return (li == le && ri == re);
2172 }
2173
2174 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and
2175 /// returns true, or false, accordingly.
2176 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
MatchTwoMethodDeclarations(const ObjCMethodDecl * left,const ObjCMethodDecl * right,MethodMatchStrategy strategy)2177 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
2178 const ObjCMethodDecl *right,
2179 MethodMatchStrategy strategy) {
2180 if (!matchTypes(Context, strategy, left->getReturnType(),
2181 right->getReturnType()))
2182 return false;
2183
2184 // If either is hidden, it is not considered to match.
2185 if (left->isHidden() || right->isHidden())
2186 return false;
2187
2188 if (getLangOpts().ObjCAutoRefCount &&
2189 (left->hasAttr<NSReturnsRetainedAttr>()
2190 != right->hasAttr<NSReturnsRetainedAttr>() ||
2191 left->hasAttr<NSConsumesSelfAttr>()
2192 != right->hasAttr<NSConsumesSelfAttr>()))
2193 return false;
2194
2195 ObjCMethodDecl::param_const_iterator
2196 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
2197 re = right->param_end();
2198
2199 for (; li != le && ri != re; ++li, ++ri) {
2200 assert(ri != right->param_end() && "Param mismatch");
2201 const ParmVarDecl *lparm = *li, *rparm = *ri;
2202
2203 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
2204 return false;
2205
2206 if (getLangOpts().ObjCAutoRefCount &&
2207 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
2208 return false;
2209 }
2210 return true;
2211 }
2212
addMethodToGlobalList(ObjCMethodList * List,ObjCMethodDecl * Method)2213 void Sema::addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method) {
2214 // Record at the head of the list whether there were 0, 1, or >= 2 methods
2215 // inside categories.
2216 if (ObjCCategoryDecl *
2217 CD = dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
2218 if (!CD->IsClassExtension() && List->getBits() < 2)
2219 List->setBits(List->getBits()+1);
2220
2221 // If the list is empty, make it a singleton list.
2222 if (List->Method == nullptr) {
2223 List->Method = Method;
2224 List->setNext(nullptr);
2225 return;
2226 }
2227
2228 // We've seen a method with this name, see if we have already seen this type
2229 // signature.
2230 ObjCMethodList *Previous = List;
2231 for (; List; Previous = List, List = List->getNext()) {
2232 // If we are building a module, keep all of the methods.
2233 if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty())
2234 continue;
2235
2236 if (!MatchTwoMethodDeclarations(Method, List->Method))
2237 continue;
2238
2239 ObjCMethodDecl *PrevObjCMethod = List->Method;
2240
2241 // Propagate the 'defined' bit.
2242 if (Method->isDefined())
2243 PrevObjCMethod->setDefined(true);
2244
2245 // If a method is deprecated, push it in the global pool.
2246 // This is used for better diagnostics.
2247 if (Method->isDeprecated()) {
2248 if (!PrevObjCMethod->isDeprecated())
2249 List->Method = Method;
2250 }
2251 // If new method is unavailable, push it into global pool
2252 // unless previous one is deprecated.
2253 if (Method->isUnavailable()) {
2254 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
2255 List->Method = Method;
2256 }
2257
2258 return;
2259 }
2260
2261 // We have a new signature for an existing method - add it.
2262 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
2263 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
2264 Previous->setNext(new (Mem) ObjCMethodList(Method, nullptr));
2265 }
2266
2267 /// \brief Read the contents of the method pool for a given selector from
2268 /// external storage.
ReadMethodPool(Selector Sel)2269 void Sema::ReadMethodPool(Selector Sel) {
2270 assert(ExternalSource && "We need an external AST source");
2271 ExternalSource->ReadMethodPool(Sel);
2272 }
2273
AddMethodToGlobalPool(ObjCMethodDecl * Method,bool impl,bool instance)2274 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
2275 bool instance) {
2276 // Ignore methods of invalid containers.
2277 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
2278 return;
2279
2280 if (ExternalSource)
2281 ReadMethodPool(Method->getSelector());
2282
2283 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
2284 if (Pos == MethodPool.end())
2285 Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
2286 GlobalMethods())).first;
2287
2288 Method->setDefined(impl);
2289
2290 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
2291 addMethodToGlobalList(&Entry, Method);
2292 }
2293
2294 /// Determines if this is an "acceptable" loose mismatch in the global
2295 /// method pool. This exists mostly as a hack to get around certain
2296 /// global mismatches which we can't afford to make warnings / errors.
2297 /// Really, what we want is a way to take a method out of the global
2298 /// method pool.
isAcceptableMethodMismatch(ObjCMethodDecl * chosen,ObjCMethodDecl * other)2299 static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
2300 ObjCMethodDecl *other) {
2301 if (!chosen->isInstanceMethod())
2302 return false;
2303
2304 Selector sel = chosen->getSelector();
2305 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
2306 return false;
2307
2308 // Don't complain about mismatches for -length if the method we
2309 // chose has an integral result type.
2310 return (chosen->getReturnType()->isIntegerType());
2311 }
2312
LookupMethodInGlobalPool(Selector Sel,SourceRange R,bool receiverIdOrClass,bool warn,bool instance)2313 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
2314 bool receiverIdOrClass,
2315 bool warn, bool instance) {
2316 if (ExternalSource)
2317 ReadMethodPool(Sel);
2318
2319 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2320 if (Pos == MethodPool.end())
2321 return nullptr;
2322
2323 // Gather the non-hidden methods.
2324 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
2325 SmallVector<ObjCMethodDecl *, 4> Methods;
2326 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
2327 if (M->Method && !M->Method->isHidden()) {
2328 // If we're not supposed to warn about mismatches, we're done.
2329 if (!warn)
2330 return M->Method;
2331
2332 Methods.push_back(M->Method);
2333 }
2334 }
2335
2336 // If there aren't any visible methods, we're done.
2337 // FIXME: Recover if there are any known-but-hidden methods?
2338 if (Methods.empty())
2339 return nullptr;
2340
2341 if (Methods.size() == 1)
2342 return Methods[0];
2343
2344 // We found multiple methods, so we may have to complain.
2345 bool issueDiagnostic = false, issueError = false;
2346
2347 // We support a warning which complains about *any* difference in
2348 // method signature.
2349 bool strictSelectorMatch =
2350 receiverIdOrClass && warn &&
2351 !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
2352 if (strictSelectorMatch) {
2353 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
2354 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
2355 issueDiagnostic = true;
2356 break;
2357 }
2358 }
2359 }
2360
2361 // If we didn't see any strict differences, we won't see any loose
2362 // differences. In ARC, however, we also need to check for loose
2363 // mismatches, because most of them are errors.
2364 if (!strictSelectorMatch ||
2365 (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
2366 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
2367 // This checks if the methods differ in type mismatch.
2368 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
2369 !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
2370 issueDiagnostic = true;
2371 if (getLangOpts().ObjCAutoRefCount)
2372 issueError = true;
2373 break;
2374 }
2375 }
2376
2377 if (issueDiagnostic) {
2378 if (issueError)
2379 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
2380 else if (strictSelectorMatch)
2381 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
2382 else
2383 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
2384
2385 Diag(Methods[0]->getLocStart(),
2386 issueError ? diag::note_possibility : diag::note_using)
2387 << Methods[0]->getSourceRange();
2388 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
2389 Diag(Methods[I]->getLocStart(), diag::note_also_found)
2390 << Methods[I]->getSourceRange();
2391 }
2392 }
2393 return Methods[0];
2394 }
2395
LookupImplementedMethodInGlobalPool(Selector Sel)2396 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
2397 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2398 if (Pos == MethodPool.end())
2399 return nullptr;
2400
2401 GlobalMethods &Methods = Pos->second;
2402 for (const ObjCMethodList *Method = &Methods.first; Method;
2403 Method = Method->getNext())
2404 if (Method->Method && Method->Method->isDefined())
2405 return Method->Method;
2406
2407 for (const ObjCMethodList *Method = &Methods.second; Method;
2408 Method = Method->getNext())
2409 if (Method->Method && Method->Method->isDefined())
2410 return Method->Method;
2411 return nullptr;
2412 }
2413
2414 static void
HelperSelectorsForTypoCorrection(SmallVectorImpl<const ObjCMethodDecl * > & BestMethod,StringRef Typo,const ObjCMethodDecl * Method)2415 HelperSelectorsForTypoCorrection(
2416 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
2417 StringRef Typo, const ObjCMethodDecl * Method) {
2418 const unsigned MaxEditDistance = 1;
2419 unsigned BestEditDistance = MaxEditDistance + 1;
2420 std::string MethodName = Method->getSelector().getAsString();
2421
2422 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
2423 if (MinPossibleEditDistance > 0 &&
2424 Typo.size() / MinPossibleEditDistance < 1)
2425 return;
2426 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
2427 if (EditDistance > MaxEditDistance)
2428 return;
2429 if (EditDistance == BestEditDistance)
2430 BestMethod.push_back(Method);
2431 else if (EditDistance < BestEditDistance) {
2432 BestMethod.clear();
2433 BestMethod.push_back(Method);
2434 }
2435 }
2436
HelperIsMethodInObjCType(Sema & S,Selector Sel,QualType ObjectType)2437 static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
2438 QualType ObjectType) {
2439 if (ObjectType.isNull())
2440 return true;
2441 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
2442 return true;
2443 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
2444 nullptr;
2445 }
2446
2447 const ObjCMethodDecl *
SelectorsForTypoCorrection(Selector Sel,QualType ObjectType)2448 Sema::SelectorsForTypoCorrection(Selector Sel,
2449 QualType ObjectType) {
2450 unsigned NumArgs = Sel.getNumArgs();
2451 SmallVector<const ObjCMethodDecl *, 8> Methods;
2452 bool ObjectIsId = true, ObjectIsClass = true;
2453 if (ObjectType.isNull())
2454 ObjectIsId = ObjectIsClass = false;
2455 else if (!ObjectType->isObjCObjectPointerType())
2456 return nullptr;
2457 else if (const ObjCObjectPointerType *ObjCPtr =
2458 ObjectType->getAsObjCInterfacePointerType()) {
2459 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
2460 ObjectIsId = ObjectIsClass = false;
2461 }
2462 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
2463 ObjectIsClass = false;
2464 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
2465 ObjectIsId = false;
2466 else
2467 return nullptr;
2468
2469 for (GlobalMethodPool::iterator b = MethodPool.begin(),
2470 e = MethodPool.end(); b != e; b++) {
2471 // instance methods
2472 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
2473 if (M->Method &&
2474 (M->Method->getSelector().getNumArgs() == NumArgs) &&
2475 (M->Method->getSelector() != Sel)) {
2476 if (ObjectIsId)
2477 Methods.push_back(M->Method);
2478 else if (!ObjectIsClass &&
2479 HelperIsMethodInObjCType(*this, M->Method->getSelector(), ObjectType))
2480 Methods.push_back(M->Method);
2481 }
2482 // class methods
2483 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
2484 if (M->Method &&
2485 (M->Method->getSelector().getNumArgs() == NumArgs) &&
2486 (M->Method->getSelector() != Sel)) {
2487 if (ObjectIsClass)
2488 Methods.push_back(M->Method);
2489 else if (!ObjectIsId &&
2490 HelperIsMethodInObjCType(*this, M->Method->getSelector(), ObjectType))
2491 Methods.push_back(M->Method);
2492 }
2493 }
2494
2495 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
2496 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
2497 HelperSelectorsForTypoCorrection(SelectedMethods,
2498 Sel.getAsString(), Methods[i]);
2499 }
2500 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
2501 }
2502
2503 /// DiagnoseDuplicateIvars -
2504 /// Check for duplicate ivars in the entire class at the start of
2505 /// \@implementation. This becomes necesssary because class extension can
2506 /// add ivars to a class in random order which will not be known until
2507 /// class's \@implementation is seen.
DiagnoseDuplicateIvars(ObjCInterfaceDecl * ID,ObjCInterfaceDecl * SID)2508 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
2509 ObjCInterfaceDecl *SID) {
2510 for (auto *Ivar : ID->ivars()) {
2511 if (Ivar->isInvalidDecl())
2512 continue;
2513 if (IdentifierInfo *II = Ivar->getIdentifier()) {
2514 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
2515 if (prevIvar) {
2516 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
2517 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
2518 Ivar->setInvalidDecl();
2519 }
2520 }
2521 }
2522 }
2523
getObjCContainerKind() const2524 Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
2525 switch (CurContext->getDeclKind()) {
2526 case Decl::ObjCInterface:
2527 return Sema::OCK_Interface;
2528 case Decl::ObjCProtocol:
2529 return Sema::OCK_Protocol;
2530 case Decl::ObjCCategory:
2531 if (dyn_cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
2532 return Sema::OCK_ClassExtension;
2533 else
2534 return Sema::OCK_Category;
2535 case Decl::ObjCImplementation:
2536 return Sema::OCK_Implementation;
2537 case Decl::ObjCCategoryImpl:
2538 return Sema::OCK_CategoryImplementation;
2539
2540 default:
2541 return Sema::OCK_None;
2542 }
2543 }
2544
2545 // Note: For class/category implementations, allMethods is always null.
ActOnAtEnd(Scope * S,SourceRange AtEnd,ArrayRef<Decl * > allMethods,ArrayRef<DeclGroupPtrTy> allTUVars)2546 Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
2547 ArrayRef<DeclGroupPtrTy> allTUVars) {
2548 if (getObjCContainerKind() == Sema::OCK_None)
2549 return nullptr;
2550
2551 assert(AtEnd.isValid() && "Invalid location for '@end'");
2552
2553 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
2554 Decl *ClassDecl = cast<Decl>(OCD);
2555
2556 bool isInterfaceDeclKind =
2557 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
2558 || isa<ObjCProtocolDecl>(ClassDecl);
2559 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
2560
2561 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
2562 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
2563 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
2564
2565 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
2566 ObjCMethodDecl *Method =
2567 cast_or_null<ObjCMethodDecl>(allMethods[i]);
2568
2569 if (!Method) continue; // Already issued a diagnostic.
2570 if (Method->isInstanceMethod()) {
2571 /// Check for instance method of the same name with incompatible types
2572 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
2573 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
2574 : false;
2575 if ((isInterfaceDeclKind && PrevMethod && !match)
2576 || (checkIdenticalMethods && match)) {
2577 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
2578 << Method->getDeclName();
2579 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2580 Method->setInvalidDecl();
2581 } else {
2582 if (PrevMethod) {
2583 Method->setAsRedeclaration(PrevMethod);
2584 if (!Context.getSourceManager().isInSystemHeader(
2585 Method->getLocation()))
2586 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
2587 << Method->getDeclName();
2588 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2589 }
2590 InsMap[Method->getSelector()] = Method;
2591 /// The following allows us to typecheck messages to "id".
2592 AddInstanceMethodToGlobalPool(Method);
2593 }
2594 } else {
2595 /// Check for class method of the same name with incompatible types
2596 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
2597 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
2598 : false;
2599 if ((isInterfaceDeclKind && PrevMethod && !match)
2600 || (checkIdenticalMethods && match)) {
2601 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
2602 << Method->getDeclName();
2603 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2604 Method->setInvalidDecl();
2605 } else {
2606 if (PrevMethod) {
2607 Method->setAsRedeclaration(PrevMethod);
2608 if (!Context.getSourceManager().isInSystemHeader(
2609 Method->getLocation()))
2610 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
2611 << Method->getDeclName();
2612 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2613 }
2614 ClsMap[Method->getSelector()] = Method;
2615 AddFactoryMethodToGlobalPool(Method);
2616 }
2617 }
2618 }
2619 if (isa<ObjCInterfaceDecl>(ClassDecl)) {
2620 // Nothing to do here.
2621 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
2622 // Categories are used to extend the class by declaring new methods.
2623 // By the same token, they are also used to add new properties. No
2624 // need to compare the added property to those in the class.
2625
2626 if (C->IsClassExtension()) {
2627 ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
2628 DiagnoseClassExtensionDupMethods(C, CCPrimary);
2629 }
2630 }
2631 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
2632 if (CDecl->getIdentifier())
2633 // ProcessPropertyDecl is responsible for diagnosing conflicts with any
2634 // user-defined setter/getter. It also synthesizes setter/getter methods
2635 // and adds them to the DeclContext and global method pools.
2636 for (auto *I : CDecl->properties())
2637 ProcessPropertyDecl(I, CDecl);
2638 CDecl->setAtEndRange(AtEnd);
2639 }
2640 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
2641 IC->setAtEndRange(AtEnd);
2642 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
2643 // Any property declared in a class extension might have user
2644 // declared setter or getter in current class extension or one
2645 // of the other class extensions. Mark them as synthesized as
2646 // property will be synthesized when property with same name is
2647 // seen in the @implementation.
2648 for (const auto *Ext : IDecl->visible_extensions()) {
2649 for (const auto *Property : Ext->properties()) {
2650 // Skip over properties declared @dynamic
2651 if (const ObjCPropertyImplDecl *PIDecl
2652 = IC->FindPropertyImplDecl(Property->getIdentifier()))
2653 if (PIDecl->getPropertyImplementation()
2654 == ObjCPropertyImplDecl::Dynamic)
2655 continue;
2656
2657 for (const auto *Ext : IDecl->visible_extensions()) {
2658 if (ObjCMethodDecl *GetterMethod
2659 = Ext->getInstanceMethod(Property->getGetterName()))
2660 GetterMethod->setPropertyAccessor(true);
2661 if (!Property->isReadOnly())
2662 if (ObjCMethodDecl *SetterMethod
2663 = Ext->getInstanceMethod(Property->getSetterName()))
2664 SetterMethod->setPropertyAccessor(true);
2665 }
2666 }
2667 }
2668 ImplMethodsVsClassMethods(S, IC, IDecl);
2669 AtomicPropertySetterGetterRules(IC, IDecl);
2670 DiagnoseOwningPropertyGetterSynthesis(IC);
2671 DiagnoseUnusedBackingIvarInAccessor(S, IC);
2672 if (IDecl->hasDesignatedInitializers())
2673 DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
2674
2675 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
2676 if (IDecl->getSuperClass() == nullptr) {
2677 // This class has no superclass, so check that it has been marked with
2678 // __attribute((objc_root_class)).
2679 if (!HasRootClassAttr) {
2680 SourceLocation DeclLoc(IDecl->getLocation());
2681 SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
2682 Diag(DeclLoc, diag::warn_objc_root_class_missing)
2683 << IDecl->getIdentifier();
2684 // See if NSObject is in the current scope, and if it is, suggest
2685 // adding " : NSObject " to the class declaration.
2686 NamedDecl *IF = LookupSingleName(TUScope,
2687 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
2688 DeclLoc, LookupOrdinaryName);
2689 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
2690 if (NSObjectDecl && NSObjectDecl->getDefinition()) {
2691 Diag(SuperClassLoc, diag::note_objc_needs_superclass)
2692 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
2693 } else {
2694 Diag(SuperClassLoc, diag::note_objc_needs_superclass);
2695 }
2696 }
2697 } else if (HasRootClassAttr) {
2698 // Complain that only root classes may have this attribute.
2699 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
2700 }
2701
2702 if (LangOpts.ObjCRuntime.isNonFragile()) {
2703 while (IDecl->getSuperClass()) {
2704 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
2705 IDecl = IDecl->getSuperClass();
2706 }
2707 }
2708 }
2709 SetIvarInitializers(IC);
2710 } else if (ObjCCategoryImplDecl* CatImplClass =
2711 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
2712 CatImplClass->setAtEndRange(AtEnd);
2713
2714 // Find category interface decl and then check that all methods declared
2715 // in this interface are implemented in the category @implementation.
2716 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
2717 if (ObjCCategoryDecl *Cat
2718 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
2719 ImplMethodsVsClassMethods(S, CatImplClass, Cat);
2720 }
2721 }
2722 }
2723 if (isInterfaceDeclKind) {
2724 // Reject invalid vardecls.
2725 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
2726 DeclGroupRef DG = allTUVars[i].get();
2727 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
2728 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
2729 if (!VDecl->hasExternalStorage())
2730 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
2731 }
2732 }
2733 }
2734 ActOnObjCContainerFinishDefinition();
2735
2736 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
2737 DeclGroupRef DG = allTUVars[i].get();
2738 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
2739 (*I)->setTopLevelDeclInObjCContainer();
2740 Consumer.HandleTopLevelDeclInObjCContainer(DG);
2741 }
2742
2743 ActOnDocumentableDecl(ClassDecl);
2744 return ClassDecl;
2745 }
2746
2747
2748 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
2749 /// objective-c's type qualifier from the parser version of the same info.
2750 static Decl::ObjCDeclQualifier
CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal)2751 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
2752 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
2753 }
2754
2755 /// \brief Check whether the declared result type of the given Objective-C
2756 /// method declaration is compatible with the method's class.
2757 ///
2758 static Sema::ResultTypeCompatibilityKind
CheckRelatedResultTypeCompatibility(Sema & S,ObjCMethodDecl * Method,ObjCInterfaceDecl * CurrentClass)2759 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
2760 ObjCInterfaceDecl *CurrentClass) {
2761 QualType ResultType = Method->getReturnType();
2762
2763 // If an Objective-C method inherits its related result type, then its
2764 // declared result type must be compatible with its own class type. The
2765 // declared result type is compatible if:
2766 if (const ObjCObjectPointerType *ResultObjectType
2767 = ResultType->getAs<ObjCObjectPointerType>()) {
2768 // - it is id or qualified id, or
2769 if (ResultObjectType->isObjCIdType() ||
2770 ResultObjectType->isObjCQualifiedIdType())
2771 return Sema::RTC_Compatible;
2772
2773 if (CurrentClass) {
2774 if (ObjCInterfaceDecl *ResultClass
2775 = ResultObjectType->getInterfaceDecl()) {
2776 // - it is the same as the method's class type, or
2777 if (declaresSameEntity(CurrentClass, ResultClass))
2778 return Sema::RTC_Compatible;
2779
2780 // - it is a superclass of the method's class type
2781 if (ResultClass->isSuperClassOf(CurrentClass))
2782 return Sema::RTC_Compatible;
2783 }
2784 } else {
2785 // Any Objective-C pointer type might be acceptable for a protocol
2786 // method; we just don't know.
2787 return Sema::RTC_Unknown;
2788 }
2789 }
2790
2791 return Sema::RTC_Incompatible;
2792 }
2793
2794 namespace {
2795 /// A helper class for searching for methods which a particular method
2796 /// overrides.
2797 class OverrideSearch {
2798 public:
2799 Sema &S;
2800 ObjCMethodDecl *Method;
2801 llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden;
2802 bool Recursive;
2803
2804 public:
OverrideSearch(Sema & S,ObjCMethodDecl * method)2805 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
2806 Selector selector = method->getSelector();
2807
2808 // Bypass this search if we've never seen an instance/class method
2809 // with this selector before.
2810 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
2811 if (it == S.MethodPool.end()) {
2812 if (!S.getExternalSource()) return;
2813 S.ReadMethodPool(selector);
2814
2815 it = S.MethodPool.find(selector);
2816 if (it == S.MethodPool.end())
2817 return;
2818 }
2819 ObjCMethodList &list =
2820 method->isInstanceMethod() ? it->second.first : it->second.second;
2821 if (!list.Method) return;
2822
2823 ObjCContainerDecl *container
2824 = cast<ObjCContainerDecl>(method->getDeclContext());
2825
2826 // Prevent the search from reaching this container again. This is
2827 // important with categories, which override methods from the
2828 // interface and each other.
2829 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) {
2830 searchFromContainer(container);
2831 if (ObjCInterfaceDecl *Interface = Category->getClassInterface())
2832 searchFromContainer(Interface);
2833 } else {
2834 searchFromContainer(container);
2835 }
2836 }
2837
2838 typedef llvm::SmallPtrSet<ObjCMethodDecl*, 128>::iterator iterator;
begin() const2839 iterator begin() const { return Overridden.begin(); }
end() const2840 iterator end() const { return Overridden.end(); }
2841
2842 private:
searchFromContainer(ObjCContainerDecl * container)2843 void searchFromContainer(ObjCContainerDecl *container) {
2844 if (container->isInvalidDecl()) return;
2845
2846 switch (container->getDeclKind()) {
2847 #define OBJCCONTAINER(type, base) \
2848 case Decl::type: \
2849 searchFrom(cast<type##Decl>(container)); \
2850 break;
2851 #define ABSTRACT_DECL(expansion)
2852 #define DECL(type, base) \
2853 case Decl::type:
2854 #include "clang/AST/DeclNodes.inc"
2855 llvm_unreachable("not an ObjC container!");
2856 }
2857 }
2858
searchFrom(ObjCProtocolDecl * protocol)2859 void searchFrom(ObjCProtocolDecl *protocol) {
2860 if (!protocol->hasDefinition())
2861 return;
2862
2863 // A method in a protocol declaration overrides declarations from
2864 // referenced ("parent") protocols.
2865 search(protocol->getReferencedProtocols());
2866 }
2867
searchFrom(ObjCCategoryDecl * category)2868 void searchFrom(ObjCCategoryDecl *category) {
2869 // A method in a category declaration overrides declarations from
2870 // the main class and from protocols the category references.
2871 // The main class is handled in the constructor.
2872 search(category->getReferencedProtocols());
2873 }
2874
searchFrom(ObjCCategoryImplDecl * impl)2875 void searchFrom(ObjCCategoryImplDecl *impl) {
2876 // A method in a category definition that has a category
2877 // declaration overrides declarations from the category
2878 // declaration.
2879 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
2880 search(category);
2881 if (ObjCInterfaceDecl *Interface = category->getClassInterface())
2882 search(Interface);
2883
2884 // Otherwise it overrides declarations from the class.
2885 } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) {
2886 search(Interface);
2887 }
2888 }
2889
searchFrom(ObjCInterfaceDecl * iface)2890 void searchFrom(ObjCInterfaceDecl *iface) {
2891 // A method in a class declaration overrides declarations from
2892 if (!iface->hasDefinition())
2893 return;
2894
2895 // - categories,
2896 for (auto *Cat : iface->known_categories())
2897 search(Cat);
2898
2899 // - the super class, and
2900 if (ObjCInterfaceDecl *super = iface->getSuperClass())
2901 search(super);
2902
2903 // - any referenced protocols.
2904 search(iface->getReferencedProtocols());
2905 }
2906
searchFrom(ObjCImplementationDecl * impl)2907 void searchFrom(ObjCImplementationDecl *impl) {
2908 // A method in a class implementation overrides declarations from
2909 // the class interface.
2910 if (ObjCInterfaceDecl *Interface = impl->getClassInterface())
2911 search(Interface);
2912 }
2913
2914
search(const ObjCProtocolList & protocols)2915 void search(const ObjCProtocolList &protocols) {
2916 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
2917 i != e; ++i)
2918 search(*i);
2919 }
2920
search(ObjCContainerDecl * container)2921 void search(ObjCContainerDecl *container) {
2922 // Check for a method in this container which matches this selector.
2923 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
2924 Method->isInstanceMethod(),
2925 /*AllowHidden=*/true);
2926
2927 // If we find one, record it and bail out.
2928 if (meth) {
2929 Overridden.insert(meth);
2930 return;
2931 }
2932
2933 // Otherwise, search for methods that a hypothetical method here
2934 // would have overridden.
2935
2936 // Note that we're now in a recursive case.
2937 Recursive = true;
2938
2939 searchFromContainer(container);
2940 }
2941 };
2942 }
2943
CheckObjCMethodOverrides(ObjCMethodDecl * ObjCMethod,ObjCInterfaceDecl * CurrentClass,ResultTypeCompatibilityKind RTC)2944 void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
2945 ObjCInterfaceDecl *CurrentClass,
2946 ResultTypeCompatibilityKind RTC) {
2947 // Search for overridden methods and merge information down from them.
2948 OverrideSearch overrides(*this, ObjCMethod);
2949 // Keep track if the method overrides any method in the class's base classes,
2950 // its protocols, or its categories' protocols; we will keep that info
2951 // in the ObjCMethodDecl.
2952 // For this info, a method in an implementation is not considered as
2953 // overriding the same method in the interface or its categories.
2954 bool hasOverriddenMethodsInBaseOrProtocol = false;
2955 for (OverrideSearch::iterator
2956 i = overrides.begin(), e = overrides.end(); i != e; ++i) {
2957 ObjCMethodDecl *overridden = *i;
2958
2959 if (!hasOverriddenMethodsInBaseOrProtocol) {
2960 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
2961 CurrentClass != overridden->getClassInterface() ||
2962 overridden->isOverriding()) {
2963 hasOverriddenMethodsInBaseOrProtocol = true;
2964
2965 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
2966 // OverrideSearch will return as "overridden" the same method in the
2967 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
2968 // check whether a category of a base class introduced a method with the
2969 // same selector, after the interface method declaration.
2970 // To avoid unnecessary lookups in the majority of cases, we use the
2971 // extra info bits in GlobalMethodPool to check whether there were any
2972 // category methods with this selector.
2973 GlobalMethodPool::iterator It =
2974 MethodPool.find(ObjCMethod->getSelector());
2975 if (It != MethodPool.end()) {
2976 ObjCMethodList &List =
2977 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
2978 unsigned CategCount = List.getBits();
2979 if (CategCount > 0) {
2980 // If the method is in a category we'll do lookup if there were at
2981 // least 2 category methods recorded, otherwise only one will do.
2982 if (CategCount > 1 ||
2983 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
2984 OverrideSearch overrides(*this, overridden);
2985 for (OverrideSearch::iterator
2986 OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) {
2987 ObjCMethodDecl *SuperOverridden = *OI;
2988 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
2989 CurrentClass != SuperOverridden->getClassInterface()) {
2990 hasOverriddenMethodsInBaseOrProtocol = true;
2991 overridden->setOverriding(true);
2992 break;
2993 }
2994 }
2995 }
2996 }
2997 }
2998 }
2999 }
3000
3001 // Propagate down the 'related result type' bit from overridden methods.
3002 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
3003 ObjCMethod->SetRelatedResultType();
3004
3005 // Then merge the declarations.
3006 mergeObjCMethodDecls(ObjCMethod, overridden);
3007
3008 if (ObjCMethod->isImplicit() && overridden->isImplicit())
3009 continue; // Conflicting properties are detected elsewhere.
3010
3011 // Check for overriding methods
3012 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
3013 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
3014 CheckConflictingOverridingMethod(ObjCMethod, overridden,
3015 isa<ObjCProtocolDecl>(overridden->getDeclContext()));
3016
3017 if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
3018 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
3019 !overridden->isImplicit() /* not meant for properties */) {
3020 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
3021 E = ObjCMethod->param_end();
3022 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
3023 PrevE = overridden->param_end();
3024 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
3025 assert(PrevI != overridden->param_end() && "Param mismatch");
3026 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
3027 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
3028 // If type of argument of method in this class does not match its
3029 // respective argument type in the super class method, issue warning;
3030 if (!Context.typesAreCompatible(T1, T2)) {
3031 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
3032 << T1 << T2;
3033 Diag(overridden->getLocation(), diag::note_previous_declaration);
3034 break;
3035 }
3036 }
3037 }
3038 }
3039
3040 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
3041 }
3042
ActOnMethodDeclaration(Scope * S,SourceLocation MethodLoc,SourceLocation EndLoc,tok::TokenKind MethodType,ObjCDeclSpec & ReturnQT,ParsedType ReturnType,ArrayRef<SourceLocation> SelectorLocs,Selector Sel,ObjCArgInfo * ArgInfo,DeclaratorChunk::ParamInfo * CParamInfo,unsigned CNumArgs,AttributeList * AttrList,tok::ObjCKeywordKind MethodDeclKind,bool isVariadic,bool MethodDefinition)3043 Decl *Sema::ActOnMethodDeclaration(
3044 Scope *S,
3045 SourceLocation MethodLoc, SourceLocation EndLoc,
3046 tok::TokenKind MethodType,
3047 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
3048 ArrayRef<SourceLocation> SelectorLocs,
3049 Selector Sel,
3050 // optional arguments. The number of types/arguments is obtained
3051 // from the Sel.getNumArgs().
3052 ObjCArgInfo *ArgInfo,
3053 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
3054 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
3055 bool isVariadic, bool MethodDefinition) {
3056 // Make sure we can establish a context for the method.
3057 if (!CurContext->isObjCContainer()) {
3058 Diag(MethodLoc, diag::error_missing_method_context);
3059 return nullptr;
3060 }
3061 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
3062 Decl *ClassDecl = cast<Decl>(OCD);
3063 QualType resultDeclType;
3064
3065 bool HasRelatedResultType = false;
3066 TypeSourceInfo *ReturnTInfo = nullptr;
3067 if (ReturnType) {
3068 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
3069
3070 if (CheckFunctionReturnType(resultDeclType, MethodLoc))
3071 return nullptr;
3072
3073 HasRelatedResultType = (resultDeclType == Context.getObjCInstanceType());
3074 } else { // get the type for "id".
3075 resultDeclType = Context.getObjCIdType();
3076 Diag(MethodLoc, diag::warn_missing_method_return_type)
3077 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
3078 }
3079
3080 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
3081 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
3082 MethodType == tok::minus, isVariadic,
3083 /*isPropertyAccessor=*/false,
3084 /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
3085 MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
3086 : ObjCMethodDecl::Required,
3087 HasRelatedResultType);
3088
3089 SmallVector<ParmVarDecl*, 16> Params;
3090
3091 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
3092 QualType ArgType;
3093 TypeSourceInfo *DI;
3094
3095 if (!ArgInfo[i].Type) {
3096 ArgType = Context.getObjCIdType();
3097 DI = nullptr;
3098 } else {
3099 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
3100 }
3101
3102 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
3103 LookupOrdinaryName, ForRedeclaration);
3104 LookupName(R, S);
3105 if (R.isSingleResult()) {
3106 NamedDecl *PrevDecl = R.getFoundDecl();
3107 if (S->isDeclScope(PrevDecl)) {
3108 Diag(ArgInfo[i].NameLoc,
3109 (MethodDefinition ? diag::warn_method_param_redefinition
3110 : diag::warn_method_param_declaration))
3111 << ArgInfo[i].Name;
3112 Diag(PrevDecl->getLocation(),
3113 diag::note_previous_declaration);
3114 }
3115 }
3116
3117 SourceLocation StartLoc = DI
3118 ? DI->getTypeLoc().getBeginLoc()
3119 : ArgInfo[i].NameLoc;
3120
3121 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
3122 ArgInfo[i].NameLoc, ArgInfo[i].Name,
3123 ArgType, DI, SC_None);
3124
3125 Param->setObjCMethodScopeInfo(i);
3126
3127 Param->setObjCDeclQualifier(
3128 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
3129
3130 // Apply the attributes to the parameter.
3131 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
3132
3133 if (Param->hasAttr<BlocksAttr>()) {
3134 Diag(Param->getLocation(), diag::err_block_on_nonlocal);
3135 Param->setInvalidDecl();
3136 }
3137 S->AddDecl(Param);
3138 IdResolver.AddDecl(Param);
3139
3140 Params.push_back(Param);
3141 }
3142
3143 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
3144 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
3145 QualType ArgType = Param->getType();
3146 if (ArgType.isNull())
3147 ArgType = Context.getObjCIdType();
3148 else
3149 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
3150 ArgType = Context.getAdjustedParameterType(ArgType);
3151
3152 Param->setDeclContext(ObjCMethod);
3153 Params.push_back(Param);
3154 }
3155
3156 ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
3157 ObjCMethod->setObjCDeclQualifier(
3158 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
3159
3160 if (AttrList)
3161 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
3162
3163 // Add the method now.
3164 const ObjCMethodDecl *PrevMethod = nullptr;
3165 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
3166 if (MethodType == tok::minus) {
3167 PrevMethod = ImpDecl->getInstanceMethod(Sel);
3168 ImpDecl->addInstanceMethod(ObjCMethod);
3169 } else {
3170 PrevMethod = ImpDecl->getClassMethod(Sel);
3171 ImpDecl->addClassMethod(ObjCMethod);
3172 }
3173
3174 ObjCMethodDecl *IMD = nullptr;
3175 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface())
3176 IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
3177 ObjCMethod->isInstanceMethod());
3178 if (IMD && IMD->hasAttr<ObjCRequiresSuperAttr>() &&
3179 !ObjCMethod->hasAttr<ObjCRequiresSuperAttr>()) {
3180 // merge the attribute into implementation.
3181 ObjCMethod->addAttr(ObjCRequiresSuperAttr::CreateImplicit(Context,
3182 ObjCMethod->getLocation()));
3183 }
3184 if (isa<ObjCCategoryImplDecl>(ImpDecl)) {
3185 ObjCMethodFamily family =
3186 ObjCMethod->getSelector().getMethodFamily();
3187 if (family == OMF_dealloc && IMD && IMD->isOverriding())
3188 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
3189 << ObjCMethod->getDeclName();
3190 }
3191 } else {
3192 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
3193 }
3194
3195 if (PrevMethod) {
3196 // You can never have two method definitions with the same name.
3197 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
3198 << ObjCMethod->getDeclName();
3199 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3200 ObjCMethod->setInvalidDecl();
3201 return ObjCMethod;
3202 }
3203
3204 // If this Objective-C method does not have a related result type, but we
3205 // are allowed to infer related result types, try to do so based on the
3206 // method family.
3207 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
3208 if (!CurrentClass) {
3209 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
3210 CurrentClass = Cat->getClassInterface();
3211 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
3212 CurrentClass = Impl->getClassInterface();
3213 else if (ObjCCategoryImplDecl *CatImpl
3214 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
3215 CurrentClass = CatImpl->getClassInterface();
3216 }
3217
3218 ResultTypeCompatibilityKind RTC
3219 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
3220
3221 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
3222
3223 bool ARCError = false;
3224 if (getLangOpts().ObjCAutoRefCount)
3225 ARCError = CheckARCMethodDecl(ObjCMethod);
3226
3227 // Infer the related result type when possible.
3228 if (!ARCError && RTC == Sema::RTC_Compatible &&
3229 !ObjCMethod->hasRelatedResultType() &&
3230 LangOpts.ObjCInferRelatedResultType) {
3231 bool InferRelatedResultType = false;
3232 switch (ObjCMethod->getMethodFamily()) {
3233 case OMF_None:
3234 case OMF_copy:
3235 case OMF_dealloc:
3236 case OMF_finalize:
3237 case OMF_mutableCopy:
3238 case OMF_release:
3239 case OMF_retainCount:
3240 case OMF_performSelector:
3241 break;
3242
3243 case OMF_alloc:
3244 case OMF_new:
3245 InferRelatedResultType = ObjCMethod->isClassMethod();
3246 break;
3247
3248 case OMF_init:
3249 case OMF_autorelease:
3250 case OMF_retain:
3251 case OMF_self:
3252 InferRelatedResultType = ObjCMethod->isInstanceMethod();
3253 break;
3254 }
3255
3256 if (InferRelatedResultType)
3257 ObjCMethod->SetRelatedResultType();
3258 }
3259
3260 ActOnDocumentableDecl(ObjCMethod);
3261
3262 return ObjCMethod;
3263 }
3264
CheckObjCDeclScope(Decl * D)3265 bool Sema::CheckObjCDeclScope(Decl *D) {
3266 // Following is also an error. But it is caused by a missing @end
3267 // and diagnostic is issued elsewhere.
3268 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
3269 return false;
3270
3271 // If we switched context to translation unit while we are still lexically in
3272 // an objc container, it means the parser missed emitting an error.
3273 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
3274 return false;
3275
3276 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
3277 D->setInvalidDecl();
3278
3279 return true;
3280 }
3281
3282 /// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
3283 /// instance variables of ClassName into Decls.
ActOnDefs(Scope * S,Decl * TagD,SourceLocation DeclStart,IdentifierInfo * ClassName,SmallVectorImpl<Decl * > & Decls)3284 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
3285 IdentifierInfo *ClassName,
3286 SmallVectorImpl<Decl*> &Decls) {
3287 // Check that ClassName is a valid class
3288 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
3289 if (!Class) {
3290 Diag(DeclStart, diag::err_undef_interface) << ClassName;
3291 return;
3292 }
3293 if (LangOpts.ObjCRuntime.isNonFragile()) {
3294 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
3295 return;
3296 }
3297
3298 // Collect the instance variables
3299 SmallVector<const ObjCIvarDecl*, 32> Ivars;
3300 Context.DeepCollectObjCIvars(Class, true, Ivars);
3301 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
3302 for (unsigned i = 0; i < Ivars.size(); i++) {
3303 const FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
3304 RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
3305 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
3306 /*FIXME: StartL=*/ID->getLocation(),
3307 ID->getLocation(),
3308 ID->getIdentifier(), ID->getType(),
3309 ID->getBitWidth());
3310 Decls.push_back(FD);
3311 }
3312
3313 // Introduce all of these fields into the appropriate scope.
3314 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
3315 D != Decls.end(); ++D) {
3316 FieldDecl *FD = cast<FieldDecl>(*D);
3317 if (getLangOpts().CPlusPlus)
3318 PushOnScopeChains(cast<FieldDecl>(FD), S);
3319 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
3320 Record->addDecl(FD);
3321 }
3322 }
3323
3324 /// \brief Build a type-check a new Objective-C exception variable declaration.
BuildObjCExceptionDecl(TypeSourceInfo * TInfo,QualType T,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,bool Invalid)3325 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
3326 SourceLocation StartLoc,
3327 SourceLocation IdLoc,
3328 IdentifierInfo *Id,
3329 bool Invalid) {
3330 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
3331 // duration shall not be qualified by an address-space qualifier."
3332 // Since all parameters have automatic store duration, they can not have
3333 // an address space.
3334 if (T.getAddressSpace() != 0) {
3335 Diag(IdLoc, diag::err_arg_with_address_space);
3336 Invalid = true;
3337 }
3338
3339 // An @catch parameter must be an unqualified object pointer type;
3340 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
3341 if (Invalid) {
3342 // Don't do any further checking.
3343 } else if (T->isDependentType()) {
3344 // Okay: we don't know what this type will instantiate to.
3345 } else if (!T->isObjCObjectPointerType()) {
3346 Invalid = true;
3347 Diag(IdLoc ,diag::err_catch_param_not_objc_type);
3348 } else if (T->isObjCQualifiedIdType()) {
3349 Invalid = true;
3350 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
3351 }
3352
3353 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
3354 T, TInfo, SC_None);
3355 New->setExceptionVariable(true);
3356
3357 // In ARC, infer 'retaining' for variables of retainable type.
3358 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
3359 Invalid = true;
3360
3361 if (Invalid)
3362 New->setInvalidDecl();
3363 return New;
3364 }
3365
ActOnObjCExceptionDecl(Scope * S,Declarator & D)3366 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
3367 const DeclSpec &DS = D.getDeclSpec();
3368
3369 // We allow the "register" storage class on exception variables because
3370 // GCC did, but we drop it completely. Any other storage class is an error.
3371 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
3372 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
3373 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
3374 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3375 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
3376 << DeclSpec::getSpecifierName(SCS);
3377 }
3378 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
3379 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
3380 diag::err_invalid_thread)
3381 << DeclSpec::getSpecifierName(TSCS);
3382 D.getMutableDeclSpec().ClearStorageClassSpecs();
3383
3384 DiagnoseFunctionSpecifiers(D.getDeclSpec());
3385
3386 // Check that there are no default arguments inside the type of this
3387 // exception object (C++ only).
3388 if (getLangOpts().CPlusPlus)
3389 CheckExtraCXXDefaultArguments(D);
3390
3391 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3392 QualType ExceptionType = TInfo->getType();
3393
3394 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
3395 D.getSourceRange().getBegin(),
3396 D.getIdentifierLoc(),
3397 D.getIdentifier(),
3398 D.isInvalidType());
3399
3400 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
3401 if (D.getCXXScopeSpec().isSet()) {
3402 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
3403 << D.getCXXScopeSpec().getRange();
3404 New->setInvalidDecl();
3405 }
3406
3407 // Add the parameter declaration into this scope.
3408 S->AddDecl(New);
3409 if (D.getIdentifier())
3410 IdResolver.AddDecl(New);
3411
3412 ProcessDeclAttributes(S, New, D);
3413
3414 if (New->hasAttr<BlocksAttr>())
3415 Diag(New->getLocation(), diag::err_block_on_nonlocal);
3416 return New;
3417 }
3418
3419 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3420 /// initialization.
CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl * OI,SmallVectorImpl<ObjCIvarDecl * > & Ivars)3421 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3422 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
3423 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
3424 Iv= Iv->getNextIvar()) {
3425 QualType QT = Context.getBaseElementType(Iv->getType());
3426 if (QT->isRecordType())
3427 Ivars.push_back(Iv);
3428 }
3429 }
3430
DiagnoseUseOfUnimplementedSelectors()3431 void Sema::DiagnoseUseOfUnimplementedSelectors() {
3432 // Load referenced selectors from the external source.
3433 if (ExternalSource) {
3434 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
3435 ExternalSource->ReadReferencedSelectors(Sels);
3436 for (unsigned I = 0, N = Sels.size(); I != N; ++I)
3437 ReferencedSelectors[Sels[I].first] = Sels[I].second;
3438 }
3439
3440 // Warning will be issued only when selector table is
3441 // generated (which means there is at lease one implementation
3442 // in the TU). This is to match gcc's behavior.
3443 if (ReferencedSelectors.empty() ||
3444 !Context.AnyObjCImplementation())
3445 return;
3446 for (llvm::DenseMap<Selector, SourceLocation>::iterator S =
3447 ReferencedSelectors.begin(),
3448 E = ReferencedSelectors.end(); S != E; ++S) {
3449 Selector Sel = (*S).first;
3450 if (!LookupImplementedMethodInGlobalPool(Sel))
3451 Diag((*S).second, diag::warn_unimplemented_selector) << Sel;
3452 }
3453 return;
3454 }
3455
3456 ObjCIvarDecl *
GetIvarBackingPropertyAccessor(const ObjCMethodDecl * Method,const ObjCPropertyDecl * & PDecl) const3457 Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3458 const ObjCPropertyDecl *&PDecl) const {
3459 if (Method->isClassMethod())
3460 return nullptr;
3461 const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
3462 if (!IDecl)
3463 return nullptr;
3464 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
3465 /*shallowCategoryLookup=*/false,
3466 /*followSuper=*/false);
3467 if (!Method || !Method->isPropertyAccessor())
3468 return nullptr;
3469 if ((PDecl = Method->findPropertyDecl()))
3470 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
3471 // property backing ivar must belong to property's class
3472 // or be a private ivar in class's implementation.
3473 // FIXME. fix the const-ness issue.
3474 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
3475 IV->getIdentifier());
3476 return IV;
3477 }
3478 return nullptr;
3479 }
3480
3481 namespace {
3482 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
3483 /// accessor references the backing ivar.
3484 class UnusedBackingIvarChecker :
3485 public DataRecursiveASTVisitor<UnusedBackingIvarChecker> {
3486 public:
3487 Sema &S;
3488 const ObjCMethodDecl *Method;
3489 const ObjCIvarDecl *IvarD;
3490 bool AccessedIvar;
3491 bool InvokedSelfMethod;
3492
UnusedBackingIvarChecker(Sema & S,const ObjCMethodDecl * Method,const ObjCIvarDecl * IvarD)3493 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
3494 const ObjCIvarDecl *IvarD)
3495 : S(S), Method(Method), IvarD(IvarD),
3496 AccessedIvar(false), InvokedSelfMethod(false) {
3497 assert(IvarD);
3498 }
3499
VisitObjCIvarRefExpr(ObjCIvarRefExpr * E)3500 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
3501 if (E->getDecl() == IvarD) {
3502 AccessedIvar = true;
3503 return false;
3504 }
3505 return true;
3506 }
3507
VisitObjCMessageExpr(ObjCMessageExpr * E)3508 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
3509 if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
3510 S.isSelfExpr(E->getInstanceReceiver(), Method)) {
3511 InvokedSelfMethod = true;
3512 }
3513 return true;
3514 }
3515 };
3516 }
3517
DiagnoseUnusedBackingIvarInAccessor(Scope * S,const ObjCImplementationDecl * ImplD)3518 void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3519 const ObjCImplementationDecl *ImplD) {
3520 if (S->hasUnrecoverableErrorOccurred())
3521 return;
3522
3523 for (const auto *CurMethod : ImplD->instance_methods()) {
3524 unsigned DIAG = diag::warn_unused_property_backing_ivar;
3525 SourceLocation Loc = CurMethod->getLocation();
3526 if (Diags.isIgnored(DIAG, Loc))
3527 continue;
3528
3529 const ObjCPropertyDecl *PDecl;
3530 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
3531 if (!IV)
3532 continue;
3533
3534 UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
3535 Checker.TraverseStmt(CurMethod->getBody());
3536 if (Checker.AccessedIvar)
3537 continue;
3538
3539 // Do not issue this warning if backing ivar is used somewhere and accessor
3540 // implementation makes a self call. This is to prevent false positive in
3541 // cases where the ivar is accessed by another method that the accessor
3542 // delegates to.
3543 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
3544 Diag(Loc, DIAG) << IV;
3545 Diag(PDecl->getLocation(), diag::note_property_declare);
3546 }
3547 }
3548 }
3549