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