SemaDeclObjC.cpp revision da92a7f91cf88f49e02050919676f7fb8e3bdff8
1402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski//===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
2402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski//
3402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski//                     The LLVM Compiler Infrastructure
4402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski//
5402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski// This file is distributed under the University of Illinois Open Source
6402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski// License. See LICENSE.TXT for details.
7402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski//
8402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski//===----------------------------------------------------------------------===//
9402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski//
10402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski//  This file implements semantic analysis for Objective C declarations.
11402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski//
12402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski//===----------------------------------------------------------------------===//
13402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski
1419903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski#include "clang/Sema/SemaInternal.h"
1519903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski#include "clang/Sema/Lookup.h"
16402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski#include "clang/Sema/ExternalSemaSource.h"
17402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski#include "clang/Sema/Scope.h"
18402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski#include "clang/Sema/ScopeInfo.h"
19402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski#include "clang/AST/ASTConsumer.h"
20402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski#include "clang/AST/Expr.h"
21402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski#include "clang/AST/ExprObjC.h"
22d5b16055782034ca90153880c36bd88b59c63aa0Caitlin Sadowski#include "clang/AST/ASTContext.h"
23402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski#include "clang/AST/DeclObjC.h"
24402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski#include "clang/Basic/SourceManager.h"
25402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski#include "clang/Sema/DeclSpec.h"
26402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski#include "llvm/ADT/DenseSet.h"
27402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski
28402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowskiusing namespace clang;
2919903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski
3019903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski/// Check whether the given method, which must be in the 'init'
31402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski/// family, is a valid member of that family.
32b50dd472cd6c8b13213626f13a928dbe41581f09Caitlin Sadowski///
33b50dd472cd6c8b13213626f13a928dbe41581f09Caitlin Sadowski/// \param receiverTypeIfCall - if null, check this as if declaring it;
34b50dd472cd6c8b13213626f13a928dbe41581f09Caitlin Sadowski///   if non-null, check this as if making a call to it with the given
35402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski///   receiver type
36402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski///
3719903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski/// \return true to indicate that there was an error and appropriate
3819903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski///   actions were taken
3919903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowskibool Sema::checkInitMethod(ObjCMethodDecl *method,
40402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski                           QualType receiverTypeIfCall) {
41b50dd472cd6c8b13213626f13a928dbe41581f09Caitlin Sadowski  if (method->isInvalidDecl()) return true;
42b50dd472cd6c8b13213626f13a928dbe41581f09Caitlin Sadowski
43402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski  // This castAs is safe: methods that don't return an object
44402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski  // pointer won't be inferred as inits and will reject an explicit
4519903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski  // objc_method_family(init).
4619903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski
47402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski  // We ignore protocols here.  Should we?  What about Class?
48b50dd472cd6c8b13213626f13a928dbe41581f09Caitlin Sadowski
49b50dd472cd6c8b13213626f13a928dbe41581f09Caitlin Sadowski  const ObjCObjectType *result = method->getResultType()
50402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski    ->castAs<ObjCObjectPointerType>()->getObjectType();
51402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski
524e4bc75d3570835e13183c66ac08974cdc016007Caitlin Sadowski  if (result->isObjCId()) {
534e4bc75d3570835e13183c66ac08974cdc016007Caitlin Sadowski    return false;
544e4bc75d3570835e13183c66ac08974cdc016007Caitlin Sadowski  } else if (result->isObjCClass()) {
554e4bc75d3570835e13183c66ac08974cdc016007Caitlin Sadowski    // fall through: always an error
564e4bc75d3570835e13183c66ac08974cdc016007Caitlin Sadowski  } else {
574e4bc75d3570835e13183c66ac08974cdc016007Caitlin Sadowski    ObjCInterfaceDecl *resultClass = result->getInterface();
584e4bc75d3570835e13183c66ac08974cdc016007Caitlin Sadowski    assert(resultClass && "unexpected object type!");
594e4bc75d3570835e13183c66ac08974cdc016007Caitlin Sadowski
604e4bc75d3570835e13183c66ac08974cdc016007Caitlin Sadowski    // It's okay for the result type to still be a forward declaration
614e4bc75d3570835e13183c66ac08974cdc016007Caitlin Sadowski    // if we're checking an interface declaration.
624e4bc75d3570835e13183c66ac08974cdc016007Caitlin Sadowski    if (resultClass->isForwardDecl()) {
634e4bc75d3570835e13183c66ac08974cdc016007Caitlin Sadowski      if (receiverTypeIfCall.isNull() &&
644e4bc75d3570835e13183c66ac08974cdc016007Caitlin Sadowski          !isa<ObjCImplementationDecl>(method->getDeclContext()))
654e4bc75d3570835e13183c66ac08974cdc016007Caitlin Sadowski        return false;
6619903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski
67402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski    // Otherwise, we try to compare class types.
68402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski    } else {
69402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski      // If this method was declared in a protocol, we can't check
709f80a97408ee0da939654d851ff42ad07d47e9c7DeLesley Hutchins      // anything unless we have a receiver type that's an interface.
7119903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski      const ObjCInterfaceDecl *receiverClass = 0;
7219903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski      if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
7319903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski        if (receiverTypeIfCall.isNull())
7499107ebc0a5aea953b736e12757e0919d5249d43Caitlin Sadowski          return false;
7519903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski
7619903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski        receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
7719903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski          ->getInterfaceDecl();
7819903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski
7919903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski        // This can be null for calls to e.g. id<Foo>.
8019903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski        if (!receiverClass) return false;
81402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski      } else {
8219903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski        receiverClass = method->getClassInterface();
8319903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski        assert(receiverClass && "method not associated with a class!");
8419903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski      }
8519903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski
86b50dd472cd6c8b13213626f13a928dbe41581f09Caitlin Sadowski      // If either class is a subclass of the other, it's fine.
87402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski      if (receiverClass->isSuperClassOf(resultClass) ||
8819903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski          resultClass->isSuperClassOf(receiverClass))
8919903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski        return false;
904e4bc75d3570835e13183c66ac08974cdc016007Caitlin Sadowski    }
914e4bc75d3570835e13183c66ac08974cdc016007Caitlin Sadowski  }
924e4bc75d3570835e13183c66ac08974cdc016007Caitlin Sadowski
934e4bc75d3570835e13183c66ac08974cdc016007Caitlin Sadowski  SourceLocation loc = method->getLocation();
9419903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski
9519903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski  // If we're in a system header, and this is not a call, just make
964e4bc75d3570835e13183c66ac08974cdc016007Caitlin Sadowski  // the method unusable.
974e4bc75d3570835e13183c66ac08974cdc016007Caitlin Sadowski  if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
984e4bc75d3570835e13183c66ac08974cdc016007Caitlin Sadowski    method->addAttr(new (Context) UnavailableAttr(loc, Context,
994e4bc75d3570835e13183c66ac08974cdc016007Caitlin Sadowski                "init method returns a type unrelated to its receiver type"));
10019903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski    return true;
10119903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski  }
10219903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski
10319903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski  // Otherwise, it's an error.
10419903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski  Diag(loc, diag::err_arc_init_method_unrelated_result_type);
10519903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski  method->setInvalidDecl();
106b50dd472cd6c8b13213626f13a928dbe41581f09Caitlin Sadowski  return true;
107b50dd472cd6c8b13213626f13a928dbe41581f09Caitlin Sadowski}
108402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski
109402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowskivoid Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
11019903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski                                   const ObjCMethodDecl *Overridden,
11119903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski                                   bool IsImplementation) {
11219903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski  if (Overridden->hasRelatedResultType() &&
11319903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski      !NewMethod->hasRelatedResultType()) {
11419903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski    // This can only happen when the method follows a naming convention that
115b50dd472cd6c8b13213626f13a928dbe41581f09Caitlin Sadowski    // implies a related result type, and the original (overridden) method has
116402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski    // a suitable return type, but the new (overriding) method does not have
117402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski    // a suitable return type.
11819903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski    QualType ResultType = NewMethod->getResultType();
11919903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski    SourceRange ResultTypeRange;
12019903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski    if (const TypeSourceInfo *ResultTypeInfo
12119903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski                                        = NewMethod->getResultTypeSourceInfo())
12219903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski      ResultTypeRange = ResultTypeInfo->getTypeLoc().getSourceRange();
12319903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski
12419903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski    // Figure out which class this method is part of, if any.
12519903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski    ObjCInterfaceDecl *CurrentClass
126b50dd472cd6c8b13213626f13a928dbe41581f09Caitlin Sadowski      = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
127402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski    if (!CurrentClass) {
128402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski      DeclContext *DC = NewMethod->getDeclContext();
129402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski      if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
13019903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski        CurrentClass = Cat->getClassInterface();
13119903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski      else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
13219903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski        CurrentClass = Impl->getClassInterface();
13319903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski      else if (ObjCCategoryImplDecl *CatImpl
13419903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski               = dyn_cast<ObjCCategoryImplDecl>(DC))
13519903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski        CurrentClass = CatImpl->getClassInterface();
136b50dd472cd6c8b13213626f13a928dbe41581f09Caitlin Sadowski    }
137402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski
138402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski    if (CurrentClass) {
139402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski      Diag(NewMethod->getLocation(),
140402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski           diag::warn_related_result_type_compatibility_class)
14119903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski        << Context.getObjCInterfaceType(CurrentClass)
14219903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski        << ResultType
14319903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski        << ResultTypeRange;
14419903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski    } else {
14519903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski      Diag(NewMethod->getLocation(),
146402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski           diag::warn_related_result_type_compatibility_protocol)
14719903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski        << ResultType
14819903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski        << ResultTypeRange;
14919903465e960329c0d5d93327f4046d036b0bc75Caitlin Sadowski    }
150402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski
151402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski    if (ObjCMethodFamily Family = Overridden->getMethodFamily())
152402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski      Diag(Overridden->getLocation(),
153402aa0698fec81e574818a0a6c2000fac0b2c4c6Caitlin Sadowski           diag::note_related_result_type_overridden_family)
154        << Family;
155    else
156      Diag(Overridden->getLocation(),
157           diag::note_related_result_type_overridden);
158  }
159  if (getLangOptions().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    for (ObjCMethodDecl::param_iterator oi = Overridden->param_begin(),
175         ni = NewMethod->param_begin(), ne = NewMethod->param_end();
176         ni != ne; ++ni, ++oi) {
177      ParmVarDecl *oldDecl = (*oi);
178      ParmVarDecl *newDecl = (*ni);
179      if (newDecl->hasAttr<NSConsumedAttr>() !=
180          oldDecl->hasAttr<NSConsumedAttr>()) {
181        Diag(newDecl->getLocation(),
182             diag::err_nsconsumed_attribute_mismatch);
183        Diag(oldDecl->getLocation(), diag::note_previous_decl)
184          << "parameter";
185      }
186    }
187  }
188}
189
190/// \brief Check a method declaration for compatibility with the Objective-C
191/// ARC conventions.
192static bool CheckARCMethodDecl(Sema &S, ObjCMethodDecl *method) {
193  ObjCMethodFamily family = method->getMethodFamily();
194  switch (family) {
195  case OMF_None:
196  case OMF_dealloc:
197  case OMF_finalize:
198  case OMF_retain:
199  case OMF_release:
200  case OMF_autorelease:
201  case OMF_retainCount:
202  case OMF_self:
203  case OMF_performSelector:
204    return false;
205
206  case OMF_init:
207    // If the method doesn't obey the init rules, don't bother annotating it.
208    if (S.checkInitMethod(method, QualType()))
209      return true;
210
211    method->addAttr(new (S.Context) NSConsumesSelfAttr(SourceLocation(),
212                                                       S.Context));
213
214    // Don't add a second copy of this attribute, but otherwise don't
215    // let it be suppressed.
216    if (method->hasAttr<NSReturnsRetainedAttr>())
217      return false;
218    break;
219
220  case OMF_alloc:
221  case OMF_copy:
222  case OMF_mutableCopy:
223  case OMF_new:
224    if (method->hasAttr<NSReturnsRetainedAttr>() ||
225        method->hasAttr<NSReturnsNotRetainedAttr>() ||
226        method->hasAttr<NSReturnsAutoreleasedAttr>())
227      return false;
228    break;
229  }
230
231  method->addAttr(new (S.Context) NSReturnsRetainedAttr(SourceLocation(),
232                                                        S.Context));
233  return false;
234}
235
236static void DiagnoseObjCImplementedDeprecations(Sema &S,
237                                                NamedDecl *ND,
238                                                SourceLocation ImplLoc,
239                                                int select) {
240  if (ND && ND->isDeprecated()) {
241    S.Diag(ImplLoc, diag::warn_deprecated_def) << select;
242    if (select == 0)
243      S.Diag(ND->getLocation(), diag::note_method_declared_at);
244    else
245      S.Diag(ND->getLocation(), diag::note_previous_decl) << "class";
246  }
247}
248
249/// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
250/// pool.
251void Sema::AddAnyMethodToGlobalPool(Decl *D) {
252  ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
253
254  // If we don't have a valid method decl, simply return.
255  if (!MDecl)
256    return;
257  if (MDecl->isInstanceMethod())
258    AddInstanceMethodToGlobalPool(MDecl, true);
259  else
260    AddFactoryMethodToGlobalPool(MDecl, true);
261}
262
263/// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
264/// and user declared, in the method definition's AST.
265void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
266  assert(getCurMethodDecl() == 0 && "Method parsing confused");
267  ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
268
269  // If we don't have a valid method decl, simply return.
270  if (!MDecl)
271    return;
272
273  // Allow all of Sema to see that we are entering a method definition.
274  PushDeclContext(FnBodyScope, MDecl);
275  PushFunctionScope();
276
277  // Create Decl objects for each parameter, entrring them in the scope for
278  // binding to their use.
279
280  // Insert the invisible arguments, self and _cmd!
281  MDecl->createImplicitParams(Context, MDecl->getClassInterface());
282
283  PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
284  PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
285
286  // Introduce all of the other parameters into this scope.
287  for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
288       E = MDecl->param_end(); PI != E; ++PI) {
289    ParmVarDecl *Param = (*PI);
290    if (!Param->isInvalidDecl() &&
291        RequireCompleteType(Param->getLocation(), Param->getType(),
292                            diag::err_typecheck_decl_incomplete_type))
293          Param->setInvalidDecl();
294    if ((*PI)->getIdentifier())
295      PushOnScopeChains(*PI, FnBodyScope);
296  }
297
298  // In ARC, disallow definition of retain/release/autorelease/retainCount
299  if (getLangOptions().ObjCAutoRefCount) {
300    switch (MDecl->getMethodFamily()) {
301    case OMF_retain:
302    case OMF_retainCount:
303    case OMF_release:
304    case OMF_autorelease:
305      Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
306        << MDecl->getSelector();
307      break;
308
309    case OMF_None:
310    case OMF_dealloc:
311    case OMF_finalize:
312    case OMF_alloc:
313    case OMF_init:
314    case OMF_mutableCopy:
315    case OMF_copy:
316    case OMF_new:
317    case OMF_self:
318    case OMF_performSelector:
319      break;
320    }
321  }
322
323  // Warn on deprecated methods under -Wdeprecated-implementations,
324  // and prepare for warning on missing super calls.
325  if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
326    if (ObjCMethodDecl *IMD =
327          IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod()))
328      DiagnoseObjCImplementedDeprecations(*this,
329                                          dyn_cast<NamedDecl>(IMD),
330                                          MDecl->getLocation(), 0);
331
332    // If this is "dealloc" or "finalize", set some bit here.
333    // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
334    // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
335    // Only do this if the current class actually has a superclass.
336    if (IC->getSuperClass()) {
337      ObjCShouldCallSuperDealloc =
338        !(Context.getLangOptions().ObjCAutoRefCount ||
339          Context.getLangOptions().getGC() == LangOptions::GCOnly) &&
340        MDecl->getMethodFamily() == OMF_dealloc;
341      ObjCShouldCallSuperFinalize =
342        Context.getLangOptions().getGC() != LangOptions::NonGC &&
343        MDecl->getMethodFamily() == OMF_finalize;
344    }
345  }
346}
347
348Decl *Sema::
349ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
350                         IdentifierInfo *ClassName, SourceLocation ClassLoc,
351                         IdentifierInfo *SuperName, SourceLocation SuperLoc,
352                         Decl * const *ProtoRefs, unsigned NumProtoRefs,
353                         const SourceLocation *ProtoLocs,
354                         SourceLocation EndProtoLoc, AttributeList *AttrList) {
355  assert(ClassName && "Missing class identifier");
356
357  // Check for another declaration kind with the same name.
358  NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
359                                         LookupOrdinaryName, ForRedeclaration);
360
361  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
362    Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
363    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
364  }
365
366  ObjCInterfaceDecl* IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
367  if (IDecl) {
368    // Class already seen. Is it a forward declaration?
369    if (!IDecl->isForwardDecl()) {
370      IDecl->setInvalidDecl();
371      Diag(AtInterfaceLoc, diag::err_duplicate_class_def)<<IDecl->getDeclName();
372      Diag(IDecl->getLocation(), diag::note_previous_definition);
373
374      // Return the previous class interface.
375      // FIXME: don't leak the objects passed in!
376      return IDecl;
377    } else {
378      IDecl->setLocation(AtInterfaceLoc);
379      IDecl->setForwardDecl(false);
380      IDecl->setClassLoc(ClassLoc);
381      // If the forward decl was in a PCH, we need to write it again in a
382      // dependent AST file.
383      IDecl->setChangedSinceDeserialization(true);
384
385      // Since this ObjCInterfaceDecl was created by a forward declaration,
386      // we now add it to the DeclContext since it wasn't added before
387      // (see ActOnForwardClassDeclaration).
388      IDecl->setLexicalDeclContext(CurContext);
389      CurContext->addDecl(IDecl);
390
391      if (AttrList)
392        ProcessDeclAttributeList(TUScope, IDecl, AttrList);
393    }
394  } else {
395    IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc,
396                                      ClassName, ClassLoc);
397    if (AttrList)
398      ProcessDeclAttributeList(TUScope, IDecl, AttrList);
399
400    PushOnScopeChains(IDecl, TUScope);
401  }
402
403  if (SuperName) {
404    // Check if a different kind of symbol declared in this scope.
405    PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
406                                LookupOrdinaryName);
407
408    if (!PrevDecl) {
409      // Try to correct for a typo in the superclass name.
410      TypoCorrection Corrected = CorrectTypo(
411          DeclarationNameInfo(SuperName, SuperLoc), LookupOrdinaryName, TUScope,
412          NULL, NULL, false, CTC_NoKeywords);
413      if ((PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>())) {
414        Diag(SuperLoc, diag::err_undef_superclass_suggest)
415          << SuperName << ClassName << PrevDecl->getDeclName();
416        Diag(PrevDecl->getLocation(), diag::note_previous_decl)
417          << PrevDecl->getDeclName();
418      }
419    }
420
421    if (PrevDecl == IDecl) {
422      Diag(SuperLoc, diag::err_recursive_superclass)
423        << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
424      IDecl->setLocEnd(ClassLoc);
425    } else {
426      ObjCInterfaceDecl *SuperClassDecl =
427                                dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
428
429      // Diagnose classes that inherit from deprecated classes.
430      if (SuperClassDecl)
431        (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
432
433      if (PrevDecl && SuperClassDecl == 0) {
434        // The previous declaration was not a class decl. Check if we have a
435        // typedef. If we do, get the underlying class type.
436        if (const TypedefNameDecl *TDecl =
437              dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
438          QualType T = TDecl->getUnderlyingType();
439          if (T->isObjCObjectType()) {
440            if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface())
441              SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
442          }
443        }
444
445        // This handles the following case:
446        //
447        // typedef int SuperClass;
448        // @interface MyClass : SuperClass {} @end
449        //
450        if (!SuperClassDecl) {
451          Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
452          Diag(PrevDecl->getLocation(), diag::note_previous_definition);
453        }
454      }
455
456      if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
457        if (!SuperClassDecl)
458          Diag(SuperLoc, diag::err_undef_superclass)
459            << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
460        else if (SuperClassDecl->isForwardDecl()) {
461          Diag(SuperLoc, diag::err_forward_superclass)
462            << SuperClassDecl->getDeclName() << ClassName
463            << SourceRange(AtInterfaceLoc, ClassLoc);
464          Diag(SuperClassDecl->getLocation(), diag::note_forward_class);
465          SuperClassDecl = 0;
466        }
467      }
468      IDecl->setSuperClass(SuperClassDecl);
469      IDecl->setSuperClassLoc(SuperLoc);
470      IDecl->setLocEnd(SuperLoc);
471    }
472  } else { // we have a root class.
473    IDecl->setLocEnd(ClassLoc);
474  }
475
476  // Check then save referenced protocols.
477  if (NumProtoRefs) {
478    IDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
479                           ProtoLocs, Context);
480    IDecl->setLocEnd(EndProtoLoc);
481  }
482
483  CheckObjCDeclScope(IDecl);
484  return IDecl;
485}
486
487/// ActOnCompatiblityAlias - this action is called after complete parsing of
488/// @compatibility_alias declaration. It sets up the alias relationships.
489Decl *Sema::ActOnCompatiblityAlias(SourceLocation AtLoc,
490                                        IdentifierInfo *AliasName,
491                                        SourceLocation AliasLocation,
492                                        IdentifierInfo *ClassName,
493                                        SourceLocation ClassLocation) {
494  // Look for previous declaration of alias name
495  NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
496                                      LookupOrdinaryName, ForRedeclaration);
497  if (ADecl) {
498    if (isa<ObjCCompatibleAliasDecl>(ADecl))
499      Diag(AliasLocation, diag::warn_previous_alias_decl);
500    else
501      Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
502    Diag(ADecl->getLocation(), diag::note_previous_declaration);
503    return 0;
504  }
505  // Check for class declaration
506  NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
507                                       LookupOrdinaryName, ForRedeclaration);
508  if (const TypedefNameDecl *TDecl =
509        dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
510    QualType T = TDecl->getUnderlyingType();
511    if (T->isObjCObjectType()) {
512      if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
513        ClassName = IDecl->getIdentifier();
514        CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
515                                  LookupOrdinaryName, ForRedeclaration);
516      }
517    }
518  }
519  ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
520  if (CDecl == 0) {
521    Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
522    if (CDeclU)
523      Diag(CDeclU->getLocation(), diag::note_previous_declaration);
524    return 0;
525  }
526
527  // Everything checked out, instantiate a new alias declaration AST.
528  ObjCCompatibleAliasDecl *AliasDecl =
529    ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
530
531  if (!CheckObjCDeclScope(AliasDecl))
532    PushOnScopeChains(AliasDecl, TUScope);
533
534  return AliasDecl;
535}
536
537bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
538  IdentifierInfo *PName,
539  SourceLocation &Ploc, SourceLocation PrevLoc,
540  const ObjCList<ObjCProtocolDecl> &PList) {
541
542  bool res = false;
543  for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
544       E = PList.end(); I != E; ++I) {
545    if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
546                                                 Ploc)) {
547      if (PDecl->getIdentifier() == PName) {
548        Diag(Ploc, diag::err_protocol_has_circular_dependency);
549        Diag(PrevLoc, diag::note_previous_definition);
550        res = true;
551      }
552      if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
553            PDecl->getLocation(), PDecl->getReferencedProtocols()))
554        res = true;
555    }
556  }
557  return res;
558}
559
560Decl *
561Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
562                                  IdentifierInfo *ProtocolName,
563                                  SourceLocation ProtocolLoc,
564                                  Decl * const *ProtoRefs,
565                                  unsigned NumProtoRefs,
566                                  const SourceLocation *ProtoLocs,
567                                  SourceLocation EndProtoLoc,
568                                  AttributeList *AttrList) {
569  bool err = false;
570  // FIXME: Deal with AttrList.
571  assert(ProtocolName && "Missing protocol identifier");
572  ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolName, ProtocolLoc);
573  if (PDecl) {
574    // Protocol already seen. Better be a forward protocol declaration
575    if (!PDecl->isForwardDecl()) {
576      Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
577      Diag(PDecl->getLocation(), diag::note_previous_definition);
578      // Just return the protocol we already had.
579      // FIXME: don't leak the objects passed in!
580      return PDecl;
581    }
582    ObjCList<ObjCProtocolDecl> PList;
583    PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
584    err = CheckForwardProtocolDeclarationForCircularDependency(
585            ProtocolName, ProtocolLoc, PDecl->getLocation(), PList);
586
587    // Make sure the cached decl gets a valid start location.
588    PDecl->setLocation(AtProtoInterfaceLoc);
589    PDecl->setForwardDecl(false);
590    // Since this ObjCProtocolDecl was created by a forward declaration,
591    // we now add it to the DeclContext since it wasn't added before
592    PDecl->setLexicalDeclContext(CurContext);
593    CurContext->addDecl(PDecl);
594    // Repeat in dependent AST files.
595    PDecl->setChangedSinceDeserialization(true);
596  } else {
597    PDecl = ObjCProtocolDecl::Create(Context, CurContext,
598                                     AtProtoInterfaceLoc,ProtocolName);
599    PushOnScopeChains(PDecl, TUScope);
600    PDecl->setForwardDecl(false);
601  }
602  if (AttrList)
603    ProcessDeclAttributeList(TUScope, PDecl, AttrList);
604  if (!err && NumProtoRefs ) {
605    /// Check then save referenced protocols.
606    PDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
607                           ProtoLocs, Context);
608    PDecl->setLocEnd(EndProtoLoc);
609  }
610
611  CheckObjCDeclScope(PDecl);
612  return PDecl;
613}
614
615/// FindProtocolDeclaration - This routine looks up protocols and
616/// issues an error if they are not declared. It returns list of
617/// protocol declarations in its 'Protocols' argument.
618void
619Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
620                              const IdentifierLocPair *ProtocolId,
621                              unsigned NumProtocols,
622                              SmallVectorImpl<Decl *> &Protocols) {
623  for (unsigned i = 0; i != NumProtocols; ++i) {
624    ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first,
625                                             ProtocolId[i].second);
626    if (!PDecl) {
627      TypoCorrection Corrected = CorrectTypo(
628          DeclarationNameInfo(ProtocolId[i].first, ProtocolId[i].second),
629          LookupObjCProtocolName, TUScope, NULL, NULL, false, CTC_NoKeywords);
630      if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>())) {
631        Diag(ProtocolId[i].second, diag::err_undeclared_protocol_suggest)
632          << ProtocolId[i].first << Corrected.getCorrection();
633        Diag(PDecl->getLocation(), diag::note_previous_decl)
634          << PDecl->getDeclName();
635      }
636    }
637
638    if (!PDecl) {
639      Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
640        << ProtocolId[i].first;
641      continue;
642    }
643
644    (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
645
646    // If this is a forward declaration and we are supposed to warn in this
647    // case, do it.
648    if (WarnOnDeclarations && PDecl->isForwardDecl())
649      Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
650        << ProtocolId[i].first;
651    Protocols.push_back(PDecl);
652  }
653}
654
655/// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
656/// a class method in its extension.
657///
658void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
659                                            ObjCInterfaceDecl *ID) {
660  if (!ID)
661    return;  // Possibly due to previous error
662
663  llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
664  for (ObjCInterfaceDecl::method_iterator i = ID->meth_begin(),
665       e =  ID->meth_end(); i != e; ++i) {
666    ObjCMethodDecl *MD = *i;
667    MethodMap[MD->getSelector()] = MD;
668  }
669
670  if (MethodMap.empty())
671    return;
672  for (ObjCCategoryDecl::method_iterator i = CAT->meth_begin(),
673       e =  CAT->meth_end(); i != e; ++i) {
674    ObjCMethodDecl *Method = *i;
675    const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
676    if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
677      Diag(Method->getLocation(), diag::err_duplicate_method_decl)
678            << Method->getDeclName();
679      Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
680    }
681  }
682}
683
684/// ActOnForwardProtocolDeclaration - Handle @protocol foo;
685Decl *
686Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
687                                      const IdentifierLocPair *IdentList,
688                                      unsigned NumElts,
689                                      AttributeList *attrList) {
690  SmallVector<ObjCProtocolDecl*, 32> Protocols;
691  SmallVector<SourceLocation, 8> ProtoLocs;
692
693  for (unsigned i = 0; i != NumElts; ++i) {
694    IdentifierInfo *Ident = IdentList[i].first;
695    ObjCProtocolDecl *PDecl = LookupProtocol(Ident, IdentList[i].second);
696    bool isNew = false;
697    if (PDecl == 0) { // Not already seen?
698      PDecl = ObjCProtocolDecl::Create(Context, CurContext,
699                                       IdentList[i].second, Ident);
700      PushOnScopeChains(PDecl, TUScope, false);
701      isNew = true;
702    }
703    if (attrList) {
704      ProcessDeclAttributeList(TUScope, PDecl, attrList);
705      if (!isNew)
706        PDecl->setChangedSinceDeserialization(true);
707    }
708    Protocols.push_back(PDecl);
709    ProtoLocs.push_back(IdentList[i].second);
710  }
711
712  ObjCForwardProtocolDecl *PDecl =
713    ObjCForwardProtocolDecl::Create(Context, CurContext, AtProtocolLoc,
714                                    Protocols.data(), Protocols.size(),
715                                    ProtoLocs.data());
716  CurContext->addDecl(PDecl);
717  CheckObjCDeclScope(PDecl);
718  return PDecl;
719}
720
721Decl *Sema::
722ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
723                            IdentifierInfo *ClassName, SourceLocation ClassLoc,
724                            IdentifierInfo *CategoryName,
725                            SourceLocation CategoryLoc,
726                            Decl * const *ProtoRefs,
727                            unsigned NumProtoRefs,
728                            const SourceLocation *ProtoLocs,
729                            SourceLocation EndProtoLoc) {
730  ObjCCategoryDecl *CDecl;
731  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
732
733  /// Check that class of this category is already completely declared.
734  if (!IDecl || IDecl->isForwardDecl()) {
735    // Create an invalid ObjCCategoryDecl to serve as context for
736    // the enclosing method declarations.  We mark the decl invalid
737    // to make it clear that this isn't a valid AST.
738    CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
739                                     ClassLoc, CategoryLoc, CategoryName,IDecl);
740    CDecl->setInvalidDecl();
741    Diag(ClassLoc, diag::err_undef_interface) << ClassName;
742    return CDecl;
743  }
744
745  if (!CategoryName && IDecl->getImplementation()) {
746    Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
747    Diag(IDecl->getImplementation()->getLocation(),
748          diag::note_implementation_declared);
749  }
750
751  if (CategoryName) {
752    /// Check for duplicate interface declaration for this category
753    ObjCCategoryDecl *CDeclChain;
754    for (CDeclChain = IDecl->getCategoryList(); CDeclChain;
755         CDeclChain = CDeclChain->getNextClassCategory()) {
756      if (CDeclChain->getIdentifier() == CategoryName) {
757        // Class extensions can be declared multiple times.
758        Diag(CategoryLoc, diag::warn_dup_category_def)
759          << ClassName << CategoryName;
760        Diag(CDeclChain->getLocation(), diag::note_previous_definition);
761        break;
762      }
763    }
764  }
765
766  CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
767                                   ClassLoc, CategoryLoc, CategoryName, IDecl);
768  // FIXME: PushOnScopeChains?
769  CurContext->addDecl(CDecl);
770
771  // If the interface is deprecated, warn about it.
772  (void)DiagnoseUseOfDecl(IDecl, ClassLoc);
773
774  if (NumProtoRefs) {
775    CDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
776                           ProtoLocs, Context);
777    // Protocols in the class extension belong to the class.
778    if (CDecl->IsClassExtension())
779     IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl**)ProtoRefs,
780                                            NumProtoRefs, Context);
781  }
782
783  CheckObjCDeclScope(CDecl);
784  return CDecl;
785}
786
787/// ActOnStartCategoryImplementation - Perform semantic checks on the
788/// category implementation declaration and build an ObjCCategoryImplDecl
789/// object.
790Decl *Sema::ActOnStartCategoryImplementation(
791                      SourceLocation AtCatImplLoc,
792                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
793                      IdentifierInfo *CatName, SourceLocation CatLoc) {
794  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
795  ObjCCategoryDecl *CatIDecl = 0;
796  if (IDecl) {
797    CatIDecl = IDecl->FindCategoryDeclaration(CatName);
798    if (!CatIDecl) {
799      // Category @implementation with no corresponding @interface.
800      // Create and install one.
801      CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, SourceLocation(),
802                                          SourceLocation(), SourceLocation(),
803                                          CatName, IDecl);
804    }
805  }
806
807  ObjCCategoryImplDecl *CDecl =
808    ObjCCategoryImplDecl::Create(Context, CurContext, AtCatImplLoc, CatName,
809                                 IDecl);
810  /// Check that class of this category is already completely declared.
811  if (!IDecl || IDecl->isForwardDecl()) {
812    Diag(ClassLoc, diag::err_undef_interface) << ClassName;
813    CDecl->setInvalidDecl();
814  }
815
816  // FIXME: PushOnScopeChains?
817  CurContext->addDecl(CDecl);
818
819  /// Check that CatName, category name, is not used in another implementation.
820  if (CatIDecl) {
821    if (CatIDecl->getImplementation()) {
822      Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
823        << CatName;
824      Diag(CatIDecl->getImplementation()->getLocation(),
825           diag::note_previous_definition);
826    } else {
827      CatIDecl->setImplementation(CDecl);
828      // Warn on implementating category of deprecated class under
829      // -Wdeprecated-implementations flag.
830      DiagnoseObjCImplementedDeprecations(*this,
831                                          dyn_cast<NamedDecl>(IDecl),
832                                          CDecl->getLocation(), 2);
833    }
834  }
835
836  CheckObjCDeclScope(CDecl);
837  return CDecl;
838}
839
840Decl *Sema::ActOnStartClassImplementation(
841                      SourceLocation AtClassImplLoc,
842                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
843                      IdentifierInfo *SuperClassname,
844                      SourceLocation SuperClassLoc) {
845  ObjCInterfaceDecl* IDecl = 0;
846  // Check for another declaration kind with the same name.
847  NamedDecl *PrevDecl
848    = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
849                       ForRedeclaration);
850  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
851    Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
852    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
853  } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
854    // If this is a forward declaration of an interface, warn.
855    if (IDecl->isForwardDecl()) {
856      Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
857      IDecl = 0;
858    }
859  } else {
860    // We did not find anything with the name ClassName; try to correct for
861    // typos in the class name.
862    TypoCorrection Corrected = CorrectTypo(
863        DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope,
864        NULL, NULL, false, CTC_NoKeywords);
865    if ((IDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>())) {
866      // Suggest the (potentially) correct interface name. However, put the
867      // fix-it hint itself in a separate note, since changing the name in
868      // the warning would make the fix-it change semantics.However, don't
869      // provide a code-modification hint or use the typo name for recovery,
870      // because this is just a warning. The program may actually be correct.
871      DeclarationName CorrectedName = Corrected.getCorrection();
872      Diag(ClassLoc, diag::warn_undef_interface_suggest)
873        << ClassName << CorrectedName;
874      Diag(IDecl->getLocation(), diag::note_previous_decl) << CorrectedName
875        << FixItHint::CreateReplacement(ClassLoc, CorrectedName.getAsString());
876      IDecl = 0;
877    } else {
878      Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
879    }
880  }
881
882  // Check that super class name is valid class name
883  ObjCInterfaceDecl* SDecl = 0;
884  if (SuperClassname) {
885    // Check if a different kind of symbol declared in this scope.
886    PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
887                                LookupOrdinaryName);
888    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
889      Diag(SuperClassLoc, diag::err_redefinition_different_kind)
890        << SuperClassname;
891      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
892    } else {
893      SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
894      if (!SDecl)
895        Diag(SuperClassLoc, diag::err_undef_superclass)
896          << SuperClassname << ClassName;
897      else if (IDecl && IDecl->getSuperClass() != SDecl) {
898        // This implementation and its interface do not have the same
899        // super class.
900        Diag(SuperClassLoc, diag::err_conflicting_super_class)
901          << SDecl->getDeclName();
902        Diag(SDecl->getLocation(), diag::note_previous_definition);
903      }
904    }
905  }
906
907  if (!IDecl) {
908    // Legacy case of @implementation with no corresponding @interface.
909    // Build, chain & install the interface decl into the identifier.
910
911    // FIXME: Do we support attributes on the @implementation? If so we should
912    // copy them over.
913    IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
914                                      ClassName, ClassLoc, false, true);
915    IDecl->setSuperClass(SDecl);
916    IDecl->setLocEnd(ClassLoc);
917
918    PushOnScopeChains(IDecl, TUScope);
919  } else {
920    // Mark the interface as being completed, even if it was just as
921    //   @class ....;
922    // declaration; the user cannot reopen it.
923    IDecl->setForwardDecl(false);
924  }
925
926  ObjCImplementationDecl* IMPDecl =
927    ObjCImplementationDecl::Create(Context, CurContext, AtClassImplLoc,
928                                   IDecl, SDecl);
929
930  if (CheckObjCDeclScope(IMPDecl))
931    return IMPDecl;
932
933  // Check that there is no duplicate implementation of this class.
934  if (IDecl->getImplementation()) {
935    // FIXME: Don't leak everything!
936    Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
937    Diag(IDecl->getImplementation()->getLocation(),
938         diag::note_previous_definition);
939  } else { // add it to the list.
940    IDecl->setImplementation(IMPDecl);
941    PushOnScopeChains(IMPDecl, TUScope);
942    // Warn on implementating deprecated class under
943    // -Wdeprecated-implementations flag.
944    DiagnoseObjCImplementedDeprecations(*this,
945                                        dyn_cast<NamedDecl>(IDecl),
946                                        IMPDecl->getLocation(), 1);
947  }
948  return IMPDecl;
949}
950
951void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
952                                    ObjCIvarDecl **ivars, unsigned numIvars,
953                                    SourceLocation RBrace) {
954  assert(ImpDecl && "missing implementation decl");
955  ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
956  if (!IDecl)
957    return;
958  /// Check case of non-existing @interface decl.
959  /// (legacy objective-c @implementation decl without an @interface decl).
960  /// Add implementations's ivar to the synthesize class's ivar list.
961  if (IDecl->isImplicitInterfaceDecl()) {
962    IDecl->setLocEnd(RBrace);
963    // Add ivar's to class's DeclContext.
964    for (unsigned i = 0, e = numIvars; i != e; ++i) {
965      ivars[i]->setLexicalDeclContext(ImpDecl);
966      IDecl->makeDeclVisibleInContext(ivars[i], false);
967      ImpDecl->addDecl(ivars[i]);
968    }
969
970    return;
971  }
972  // If implementation has empty ivar list, just return.
973  if (numIvars == 0)
974    return;
975
976  assert(ivars && "missing @implementation ivars");
977  if (LangOpts.ObjCNonFragileABI2) {
978    if (ImpDecl->getSuperClass())
979      Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
980    for (unsigned i = 0; i < numIvars; i++) {
981      ObjCIvarDecl* ImplIvar = ivars[i];
982      if (const ObjCIvarDecl *ClsIvar =
983            IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
984        Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
985        Diag(ClsIvar->getLocation(), diag::note_previous_definition);
986        continue;
987      }
988      // Instance ivar to Implementation's DeclContext.
989      ImplIvar->setLexicalDeclContext(ImpDecl);
990      IDecl->makeDeclVisibleInContext(ImplIvar, false);
991      ImpDecl->addDecl(ImplIvar);
992    }
993    return;
994  }
995  // Check interface's Ivar list against those in the implementation.
996  // names and types must match.
997  //
998  unsigned j = 0;
999  ObjCInterfaceDecl::ivar_iterator
1000    IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
1001  for (; numIvars > 0 && IVI != IVE; ++IVI) {
1002    ObjCIvarDecl* ImplIvar = ivars[j++];
1003    ObjCIvarDecl* ClsIvar = *IVI;
1004    assert (ImplIvar && "missing implementation ivar");
1005    assert (ClsIvar && "missing class ivar");
1006
1007    // First, make sure the types match.
1008    if (Context.getCanonicalType(ImplIvar->getType()) !=
1009        Context.getCanonicalType(ClsIvar->getType())) {
1010      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
1011        << ImplIvar->getIdentifier()
1012        << ImplIvar->getType() << ClsIvar->getType();
1013      Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1014    } else if (ImplIvar->isBitField() && ClsIvar->isBitField()) {
1015      Expr *ImplBitWidth = ImplIvar->getBitWidth();
1016      Expr *ClsBitWidth = ClsIvar->getBitWidth();
1017      if (ImplBitWidth->EvaluateAsInt(Context).getZExtValue() !=
1018          ClsBitWidth->EvaluateAsInt(Context).getZExtValue()) {
1019        Diag(ImplBitWidth->getLocStart(), diag::err_conflicting_ivar_bitwidth)
1020          << ImplIvar->getIdentifier();
1021        Diag(ClsBitWidth->getLocStart(), diag::note_previous_definition);
1022      }
1023    }
1024    // Make sure the names are identical.
1025    if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
1026      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
1027        << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
1028      Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1029    }
1030    --numIvars;
1031  }
1032
1033  if (numIvars > 0)
1034    Diag(ivars[j]->getLocation(), diag::err_inconsistant_ivar_count);
1035  else if (IVI != IVE)
1036    Diag((*IVI)->getLocation(), diag::err_inconsistant_ivar_count);
1037}
1038
1039void Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
1040                               bool &IncompleteImpl, unsigned DiagID) {
1041  // No point warning no definition of method which is 'unavailable'.
1042  if (method->hasAttr<UnavailableAttr>())
1043    return;
1044  if (!IncompleteImpl) {
1045    Diag(ImpLoc, diag::warn_incomplete_impl);
1046    IncompleteImpl = true;
1047  }
1048  if (DiagID == diag::warn_unimplemented_protocol_method)
1049    Diag(ImpLoc, DiagID) << method->getDeclName();
1050  else
1051    Diag(method->getLocation(), DiagID) << method->getDeclName();
1052}
1053
1054/// Determines if type B can be substituted for type A.  Returns true if we can
1055/// guarantee that anything that the user will do to an object of type A can
1056/// also be done to an object of type B.  This is trivially true if the two
1057/// types are the same, or if B is a subclass of A.  It becomes more complex
1058/// in cases where protocols are involved.
1059///
1060/// Object types in Objective-C describe the minimum requirements for an
1061/// object, rather than providing a complete description of a type.  For
1062/// example, if A is a subclass of B, then B* may refer to an instance of A.
1063/// The principle of substitutability means that we may use an instance of A
1064/// anywhere that we may use an instance of B - it will implement all of the
1065/// ivars of B and all of the methods of B.
1066///
1067/// This substitutability is important when type checking methods, because
1068/// the implementation may have stricter type definitions than the interface.
1069/// The interface specifies minimum requirements, but the implementation may
1070/// have more accurate ones.  For example, a method may privately accept
1071/// instances of B, but only publish that it accepts instances of A.  Any
1072/// object passed to it will be type checked against B, and so will implicitly
1073/// by a valid A*.  Similarly, a method may return a subclass of the class that
1074/// it is declared as returning.
1075///
1076/// This is most important when considering subclassing.  A method in a
1077/// subclass must accept any object as an argument that its superclass's
1078/// implementation accepts.  It may, however, accept a more general type
1079/// without breaking substitutability (i.e. you can still use the subclass
1080/// anywhere that you can use the superclass, but not vice versa).  The
1081/// converse requirement applies to return types: the return type for a
1082/// subclass method must be a valid object of the kind that the superclass
1083/// advertises, but it may be specified more accurately.  This avoids the need
1084/// for explicit down-casting by callers.
1085///
1086/// Note: This is a stricter requirement than for assignment.
1087static bool isObjCTypeSubstitutable(ASTContext &Context,
1088                                    const ObjCObjectPointerType *A,
1089                                    const ObjCObjectPointerType *B,
1090                                    bool rejectId) {
1091  // Reject a protocol-unqualified id.
1092  if (rejectId && B->isObjCIdType()) return false;
1093
1094  // If B is a qualified id, then A must also be a qualified id and it must
1095  // implement all of the protocols in B.  It may not be a qualified class.
1096  // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
1097  // stricter definition so it is not substitutable for id<A>.
1098  if (B->isObjCQualifiedIdType()) {
1099    return A->isObjCQualifiedIdType() &&
1100           Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
1101                                                     QualType(B,0),
1102                                                     false);
1103  }
1104
1105  /*
1106  // id is a special type that bypasses type checking completely.  We want a
1107  // warning when it is used in one place but not another.
1108  if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
1109
1110
1111  // If B is a qualified id, then A must also be a qualified id (which it isn't
1112  // if we've got this far)
1113  if (B->isObjCQualifiedIdType()) return false;
1114  */
1115
1116  // Now we know that A and B are (potentially-qualified) class types.  The
1117  // normal rules for assignment apply.
1118  return Context.canAssignObjCInterfaces(A, B);
1119}
1120
1121static SourceRange getTypeRange(TypeSourceInfo *TSI) {
1122  return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
1123}
1124
1125static bool CheckMethodOverrideReturn(Sema &S,
1126                                      ObjCMethodDecl *MethodImpl,
1127                                      ObjCMethodDecl *MethodDecl,
1128                                      bool IsProtocolMethodDecl,
1129                                      bool IsOverridingMode,
1130                                      bool Warn) {
1131  if (IsProtocolMethodDecl &&
1132      (MethodDecl->getObjCDeclQualifier() !=
1133       MethodImpl->getObjCDeclQualifier())) {
1134    if (Warn) {
1135        S.Diag(MethodImpl->getLocation(),
1136               (IsOverridingMode ?
1137                 diag::warn_conflicting_overriding_ret_type_modifiers
1138                 : diag::warn_conflicting_ret_type_modifiers))
1139          << MethodImpl->getDeclName()
1140          << getTypeRange(MethodImpl->getResultTypeSourceInfo());
1141        S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
1142          << getTypeRange(MethodDecl->getResultTypeSourceInfo());
1143    }
1144    else
1145      return false;
1146  }
1147
1148  if (S.Context.hasSameUnqualifiedType(MethodImpl->getResultType(),
1149                                       MethodDecl->getResultType()))
1150    return true;
1151  if (!Warn)
1152    return false;
1153
1154  unsigned DiagID =
1155    IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
1156                     : diag::warn_conflicting_ret_types;
1157
1158  // Mismatches between ObjC pointers go into a different warning
1159  // category, and sometimes they're even completely whitelisted.
1160  if (const ObjCObjectPointerType *ImplPtrTy =
1161        MethodImpl->getResultType()->getAs<ObjCObjectPointerType>()) {
1162    if (const ObjCObjectPointerType *IfacePtrTy =
1163          MethodDecl->getResultType()->getAs<ObjCObjectPointerType>()) {
1164      // Allow non-matching return types as long as they don't violate
1165      // the principle of substitutability.  Specifically, we permit
1166      // return types that are subclasses of the declared return type,
1167      // or that are more-qualified versions of the declared type.
1168      if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
1169        return false;
1170
1171      DiagID =
1172        IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
1173                          : diag::warn_non_covariant_ret_types;
1174    }
1175  }
1176
1177  S.Diag(MethodImpl->getLocation(), DiagID)
1178    << MethodImpl->getDeclName()
1179    << MethodDecl->getResultType()
1180    << MethodImpl->getResultType()
1181    << getTypeRange(MethodImpl->getResultTypeSourceInfo());
1182  S.Diag(MethodDecl->getLocation(),
1183         IsOverridingMode ? diag::note_previous_declaration
1184                          : diag::note_previous_definition)
1185    << getTypeRange(MethodDecl->getResultTypeSourceInfo());
1186  return false;
1187}
1188
1189static bool CheckMethodOverrideParam(Sema &S,
1190                                     ObjCMethodDecl *MethodImpl,
1191                                     ObjCMethodDecl *MethodDecl,
1192                                     ParmVarDecl *ImplVar,
1193                                     ParmVarDecl *IfaceVar,
1194                                     bool IsProtocolMethodDecl,
1195                                     bool IsOverridingMode,
1196                                     bool Warn) {
1197  if (IsProtocolMethodDecl &&
1198      (ImplVar->getObjCDeclQualifier() !=
1199       IfaceVar->getObjCDeclQualifier())) {
1200    if (Warn) {
1201      if (IsOverridingMode)
1202        S.Diag(ImplVar->getLocation(),
1203               diag::warn_conflicting_overriding_param_modifiers)
1204            << getTypeRange(ImplVar->getTypeSourceInfo())
1205            << MethodImpl->getDeclName();
1206      else S.Diag(ImplVar->getLocation(),
1207             diag::warn_conflicting_param_modifiers)
1208          << getTypeRange(ImplVar->getTypeSourceInfo())
1209          << MethodImpl->getDeclName();
1210      S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
1211          << getTypeRange(IfaceVar->getTypeSourceInfo());
1212    }
1213    else
1214      return false;
1215  }
1216
1217  QualType ImplTy = ImplVar->getType();
1218  QualType IfaceTy = IfaceVar->getType();
1219
1220  if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
1221    return true;
1222
1223  if (!Warn)
1224    return false;
1225  unsigned DiagID =
1226    IsOverridingMode ? diag::warn_conflicting_overriding_param_types
1227                     : diag::warn_conflicting_param_types;
1228
1229  // Mismatches between ObjC pointers go into a different warning
1230  // category, and sometimes they're even completely whitelisted.
1231  if (const ObjCObjectPointerType *ImplPtrTy =
1232        ImplTy->getAs<ObjCObjectPointerType>()) {
1233    if (const ObjCObjectPointerType *IfacePtrTy =
1234          IfaceTy->getAs<ObjCObjectPointerType>()) {
1235      // Allow non-matching argument types as long as they don't
1236      // violate the principle of substitutability.  Specifically, the
1237      // implementation must accept any objects that the superclass
1238      // accepts, however it may also accept others.
1239      if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
1240        return false;
1241
1242      DiagID =
1243      IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
1244                       :  diag::warn_non_contravariant_param_types;
1245    }
1246  }
1247
1248  S.Diag(ImplVar->getLocation(), DiagID)
1249    << getTypeRange(ImplVar->getTypeSourceInfo())
1250    << MethodImpl->getDeclName() << IfaceTy << ImplTy;
1251  S.Diag(IfaceVar->getLocation(),
1252         (IsOverridingMode ? diag::note_previous_declaration
1253                        : diag::note_previous_definition))
1254    << getTypeRange(IfaceVar->getTypeSourceInfo());
1255  return false;
1256}
1257
1258/// In ARC, check whether the conventional meanings of the two methods
1259/// match.  If they don't, it's a hard error.
1260static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
1261                                      ObjCMethodDecl *decl) {
1262  ObjCMethodFamily implFamily = impl->getMethodFamily();
1263  ObjCMethodFamily declFamily = decl->getMethodFamily();
1264  if (implFamily == declFamily) return false;
1265
1266  // Since conventions are sorted by selector, the only possibility is
1267  // that the types differ enough to cause one selector or the other
1268  // to fall out of the family.
1269  assert(implFamily == OMF_None || declFamily == OMF_None);
1270
1271  // No further diagnostics required on invalid declarations.
1272  if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
1273
1274  const ObjCMethodDecl *unmatched = impl;
1275  ObjCMethodFamily family = declFamily;
1276  unsigned errorID = diag::err_arc_lost_method_convention;
1277  unsigned noteID = diag::note_arc_lost_method_convention;
1278  if (declFamily == OMF_None) {
1279    unmatched = decl;
1280    family = implFamily;
1281    errorID = diag::err_arc_gained_method_convention;
1282    noteID = diag::note_arc_gained_method_convention;
1283  }
1284
1285  // Indexes into a %select clause in the diagnostic.
1286  enum FamilySelector {
1287    F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
1288  };
1289  FamilySelector familySelector = FamilySelector();
1290
1291  switch (family) {
1292  case OMF_None: llvm_unreachable("logic error, no method convention");
1293  case OMF_retain:
1294  case OMF_release:
1295  case OMF_autorelease:
1296  case OMF_dealloc:
1297  case OMF_finalize:
1298  case OMF_retainCount:
1299  case OMF_self:
1300  case OMF_performSelector:
1301    // Mismatches for these methods don't change ownership
1302    // conventions, so we don't care.
1303    return false;
1304
1305  case OMF_init: familySelector = F_init; break;
1306  case OMF_alloc: familySelector = F_alloc; break;
1307  case OMF_copy: familySelector = F_copy; break;
1308  case OMF_mutableCopy: familySelector = F_mutableCopy; break;
1309  case OMF_new: familySelector = F_new; break;
1310  }
1311
1312  enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
1313  ReasonSelector reasonSelector;
1314
1315  // The only reason these methods don't fall within their families is
1316  // due to unusual result types.
1317  if (unmatched->getResultType()->isObjCObjectPointerType()) {
1318    reasonSelector = R_UnrelatedReturn;
1319  } else {
1320    reasonSelector = R_NonObjectReturn;
1321  }
1322
1323  S.Diag(impl->getLocation(), errorID) << familySelector << reasonSelector;
1324  S.Diag(decl->getLocation(), noteID) << familySelector << reasonSelector;
1325
1326  return true;
1327}
1328
1329void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
1330                                       ObjCMethodDecl *MethodDecl,
1331                                       bool IsProtocolMethodDecl,
1332                                       bool IsOverridingMode) {
1333  if (getLangOptions().ObjCAutoRefCount &&
1334      !IsOverridingMode &&
1335      checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
1336    return;
1337
1338  CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
1339                            IsProtocolMethodDecl, IsOverridingMode,
1340                            true);
1341
1342  for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
1343       IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end();
1344       IM != EM; ++IM, ++IF) {
1345    CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
1346                             IsProtocolMethodDecl, IsOverridingMode, true);
1347  }
1348
1349  if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
1350    if (IsOverridingMode)
1351      Diag(ImpMethodDecl->getLocation(),
1352           diag::warn_conflicting_overriding_variadic);
1353    else
1354      Diag(ImpMethodDecl->getLocation(), diag::warn_conflicting_variadic);
1355    Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
1356  }
1357}
1358
1359/// WarnExactTypedMethods - This routine issues a warning if method
1360/// implementation declaration matches exactly that of its declaration.
1361void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
1362                                 ObjCMethodDecl *MethodDecl,
1363                                 bool IsProtocolMethodDecl) {
1364  // don't issue warning when protocol method is optional because primary
1365  // class is not required to implement it and it is safe for protocol
1366  // to implement it.
1367  if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
1368    return;
1369  // don't issue warning when primary class's method is
1370  // depecated/unavailable.
1371  if (MethodDecl->hasAttr<UnavailableAttr>() ||
1372      MethodDecl->hasAttr<DeprecatedAttr>())
1373    return;
1374
1375  bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
1376                                      IsProtocolMethodDecl, false, false);
1377  if (match)
1378    for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
1379         IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end();
1380         IM != EM; ++IM, ++IF) {
1381      match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
1382                                       *IM, *IF,
1383                                       IsProtocolMethodDecl, false, false);
1384      if (!match)
1385        break;
1386    }
1387  if (match)
1388    match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
1389  if (match)
1390    match = !(MethodDecl->isClassMethod() &&
1391              MethodDecl->getSelector() == GetNullarySelector("load", Context));
1392
1393  if (match) {
1394    Diag(ImpMethodDecl->getLocation(),
1395         diag::warn_category_method_impl_match);
1396    Diag(MethodDecl->getLocation(), diag::note_method_declared_at);
1397  }
1398}
1399
1400/// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
1401/// improve the efficiency of selector lookups and type checking by associating
1402/// with each protocol / interface / category the flattened instance tables. If
1403/// we used an immutable set to keep the table then it wouldn't add significant
1404/// memory cost and it would be handy for lookups.
1405
1406/// CheckProtocolMethodDefs - This routine checks unimplemented methods
1407/// Declared in protocol, and those referenced by it.
1408void Sema::CheckProtocolMethodDefs(SourceLocation ImpLoc,
1409                                   ObjCProtocolDecl *PDecl,
1410                                   bool& IncompleteImpl,
1411                                   const llvm::DenseSet<Selector> &InsMap,
1412                                   const llvm::DenseSet<Selector> &ClsMap,
1413                                   ObjCContainerDecl *CDecl) {
1414  ObjCInterfaceDecl *IDecl;
1415  if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl))
1416    IDecl = C->getClassInterface();
1417  else
1418    IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
1419  assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
1420
1421  ObjCInterfaceDecl *Super = IDecl->getSuperClass();
1422  ObjCInterfaceDecl *NSIDecl = 0;
1423  if (getLangOptions().NeXTRuntime) {
1424    // check to see if class implements forwardInvocation method and objects
1425    // of this class are derived from 'NSProxy' so that to forward requests
1426    // from one object to another.
1427    // Under such conditions, which means that every method possible is
1428    // implemented in the class, we should not issue "Method definition not
1429    // found" warnings.
1430    // FIXME: Use a general GetUnarySelector method for this.
1431    IdentifierInfo* II = &Context.Idents.get("forwardInvocation");
1432    Selector fISelector = Context.Selectors.getSelector(1, &II);
1433    if (InsMap.count(fISelector))
1434      // Is IDecl derived from 'NSProxy'? If so, no instance methods
1435      // need be implemented in the implementation.
1436      NSIDecl = IDecl->lookupInheritedClass(&Context.Idents.get("NSProxy"));
1437  }
1438
1439  // If a method lookup fails locally we still need to look and see if
1440  // the method was implemented by a base class or an inherited
1441  // protocol. This lookup is slow, but occurs rarely in correct code
1442  // and otherwise would terminate in a warning.
1443
1444  // check unimplemented instance methods.
1445  if (!NSIDecl)
1446    for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
1447         E = PDecl->instmeth_end(); I != E; ++I) {
1448      ObjCMethodDecl *method = *I;
1449      if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1450          !method->isSynthesized() && !InsMap.count(method->getSelector()) &&
1451          (!Super ||
1452           !Super->lookupInstanceMethod(method->getSelector()))) {
1453            // Ugly, but necessary. Method declared in protcol might have
1454            // have been synthesized due to a property declared in the class which
1455            // uses the protocol.
1456            ObjCMethodDecl *MethodInClass =
1457            IDecl->lookupInstanceMethod(method->getSelector());
1458            if (!MethodInClass || !MethodInClass->isSynthesized()) {
1459              unsigned DIAG = diag::warn_unimplemented_protocol_method;
1460              if (Diags.getDiagnosticLevel(DIAG, ImpLoc)
1461                      != DiagnosticsEngine::Ignored) {
1462                WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
1463                Diag(method->getLocation(), diag::note_method_declared_at);
1464                Diag(CDecl->getLocation(), diag::note_required_for_protocol_at)
1465                  << PDecl->getDeclName();
1466              }
1467            }
1468          }
1469    }
1470  // check unimplemented class methods
1471  for (ObjCProtocolDecl::classmeth_iterator
1472         I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1473       I != E; ++I) {
1474    ObjCMethodDecl *method = *I;
1475    if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1476        !ClsMap.count(method->getSelector()) &&
1477        (!Super || !Super->lookupClassMethod(method->getSelector()))) {
1478      unsigned DIAG = diag::warn_unimplemented_protocol_method;
1479      if (Diags.getDiagnosticLevel(DIAG, ImpLoc) !=
1480            DiagnosticsEngine::Ignored) {
1481        WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
1482        Diag(method->getLocation(), diag::note_method_declared_at);
1483        Diag(IDecl->getLocation(), diag::note_required_for_protocol_at) <<
1484          PDecl->getDeclName();
1485      }
1486    }
1487  }
1488  // Check on this protocols's referenced protocols, recursively.
1489  for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
1490       E = PDecl->protocol_end(); PI != E; ++PI)
1491    CheckProtocolMethodDefs(ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap, IDecl);
1492}
1493
1494/// MatchAllMethodDeclarations - Check methods declared in interface
1495/// or protocol against those declared in their implementations.
1496///
1497void Sema::MatchAllMethodDeclarations(const llvm::DenseSet<Selector> &InsMap,
1498                                      const llvm::DenseSet<Selector> &ClsMap,
1499                                      llvm::DenseSet<Selector> &InsMapSeen,
1500                                      llvm::DenseSet<Selector> &ClsMapSeen,
1501                                      ObjCImplDecl* IMPDecl,
1502                                      ObjCContainerDecl* CDecl,
1503                                      bool &IncompleteImpl,
1504                                      bool ImmediateClass,
1505                                      bool WarnExactMatch) {
1506  // Check and see if instance methods in class interface have been
1507  // implemented in the implementation class. If so, their types match.
1508  for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(),
1509       E = CDecl->instmeth_end(); I != E; ++I) {
1510    if (InsMapSeen.count((*I)->getSelector()))
1511        continue;
1512    InsMapSeen.insert((*I)->getSelector());
1513    if (!(*I)->isSynthesized() &&
1514        !InsMap.count((*I)->getSelector())) {
1515      if (ImmediateClass)
1516        WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl,
1517                            diag::note_undef_method_impl);
1518      continue;
1519    } else {
1520      ObjCMethodDecl *ImpMethodDecl =
1521        IMPDecl->getInstanceMethod((*I)->getSelector());
1522      assert(CDecl->getInstanceMethod((*I)->getSelector()) &&
1523             "Expected to find the method through lookup as well");
1524      ObjCMethodDecl *MethodDecl = *I;
1525      // ImpMethodDecl may be null as in a @dynamic property.
1526      if (ImpMethodDecl) {
1527        if (!WarnExactMatch)
1528          WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl,
1529                                      isa<ObjCProtocolDecl>(CDecl));
1530        else if (!MethodDecl->isSynthesized())
1531          WarnExactTypedMethods(ImpMethodDecl, MethodDecl,
1532                               isa<ObjCProtocolDecl>(CDecl));
1533      }
1534    }
1535  }
1536
1537  // Check and see if class methods in class interface have been
1538  // implemented in the implementation class. If so, their types match.
1539   for (ObjCInterfaceDecl::classmeth_iterator
1540       I = CDecl->classmeth_begin(), E = CDecl->classmeth_end(); I != E; ++I) {
1541     if (ClsMapSeen.count((*I)->getSelector()))
1542       continue;
1543     ClsMapSeen.insert((*I)->getSelector());
1544    if (!ClsMap.count((*I)->getSelector())) {
1545      if (ImmediateClass)
1546        WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl,
1547                            diag::note_undef_method_impl);
1548    } else {
1549      ObjCMethodDecl *ImpMethodDecl =
1550        IMPDecl->getClassMethod((*I)->getSelector());
1551      assert(CDecl->getClassMethod((*I)->getSelector()) &&
1552             "Expected to find the method through lookup as well");
1553      ObjCMethodDecl *MethodDecl = *I;
1554      if (!WarnExactMatch)
1555        WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl,
1556                                    isa<ObjCProtocolDecl>(CDecl));
1557      else
1558        WarnExactTypedMethods(ImpMethodDecl, MethodDecl,
1559                             isa<ObjCProtocolDecl>(CDecl));
1560    }
1561  }
1562
1563  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
1564    // Also methods in class extensions need be looked at next.
1565    for (const ObjCCategoryDecl *ClsExtDecl = I->getFirstClassExtension();
1566         ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension())
1567      MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1568                                 IMPDecl,
1569                                 const_cast<ObjCCategoryDecl *>(ClsExtDecl),
1570                                 IncompleteImpl, false, WarnExactMatch);
1571
1572    // Check for any implementation of a methods declared in protocol.
1573    for (ObjCInterfaceDecl::all_protocol_iterator
1574          PI = I->all_referenced_protocol_begin(),
1575          E = I->all_referenced_protocol_end(); PI != E; ++PI)
1576      MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1577                                 IMPDecl,
1578                                 (*PI), IncompleteImpl, false, WarnExactMatch);
1579
1580    // FIXME. For now, we are not checking for extact match of methods
1581    // in category implementation and its primary class's super class.
1582    if (!WarnExactMatch && I->getSuperClass())
1583      MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1584                                 IMPDecl,
1585                                 I->getSuperClass(), IncompleteImpl, false);
1586  }
1587}
1588
1589/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
1590/// category matches with those implemented in its primary class and
1591/// warns each time an exact match is found.
1592void Sema::CheckCategoryVsClassMethodMatches(
1593                                  ObjCCategoryImplDecl *CatIMPDecl) {
1594  llvm::DenseSet<Selector> InsMap, ClsMap;
1595
1596  for (ObjCImplementationDecl::instmeth_iterator
1597       I = CatIMPDecl->instmeth_begin(),
1598       E = CatIMPDecl->instmeth_end(); I!=E; ++I)
1599    InsMap.insert((*I)->getSelector());
1600
1601  for (ObjCImplementationDecl::classmeth_iterator
1602       I = CatIMPDecl->classmeth_begin(),
1603       E = CatIMPDecl->classmeth_end(); I != E; ++I)
1604    ClsMap.insert((*I)->getSelector());
1605  if (InsMap.empty() && ClsMap.empty())
1606    return;
1607
1608  // Get category's primary class.
1609  ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
1610  if (!CatDecl)
1611    return;
1612  ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
1613  if (!IDecl)
1614    return;
1615  llvm::DenseSet<Selector> InsMapSeen, ClsMapSeen;
1616  bool IncompleteImpl = false;
1617  MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1618                             CatIMPDecl, IDecl,
1619                             IncompleteImpl, false, true /*WarnExactMatch*/);
1620}
1621
1622void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
1623                                     ObjCContainerDecl* CDecl,
1624                                     bool IncompleteImpl) {
1625  llvm::DenseSet<Selector> InsMap;
1626  // Check and see if instance methods in class interface have been
1627  // implemented in the implementation class.
1628  for (ObjCImplementationDecl::instmeth_iterator
1629         I = IMPDecl->instmeth_begin(), E = IMPDecl->instmeth_end(); I!=E; ++I)
1630    InsMap.insert((*I)->getSelector());
1631
1632  // Check and see if properties declared in the interface have either 1)
1633  // an implementation or 2) there is a @synthesize/@dynamic implementation
1634  // of the property in the @implementation.
1635  if (isa<ObjCInterfaceDecl>(CDecl) &&
1636        !(LangOpts.ObjCDefaultSynthProperties && LangOpts.ObjCNonFragileABI2))
1637    DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap);
1638
1639  llvm::DenseSet<Selector> ClsMap;
1640  for (ObjCImplementationDecl::classmeth_iterator
1641       I = IMPDecl->classmeth_begin(),
1642       E = IMPDecl->classmeth_end(); I != E; ++I)
1643    ClsMap.insert((*I)->getSelector());
1644
1645  // Check for type conflict of methods declared in a class/protocol and
1646  // its implementation; if any.
1647  llvm::DenseSet<Selector> InsMapSeen, ClsMapSeen;
1648  MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1649                             IMPDecl, CDecl,
1650                             IncompleteImpl, true);
1651
1652  // check all methods implemented in category against those declared
1653  // in its primary class.
1654  if (ObjCCategoryImplDecl *CatDecl =
1655        dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
1656    CheckCategoryVsClassMethodMatches(CatDecl);
1657
1658  // Check the protocol list for unimplemented methods in the @implementation
1659  // class.
1660  // Check and see if class methods in class interface have been
1661  // implemented in the implementation class.
1662
1663  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
1664    for (ObjCInterfaceDecl::all_protocol_iterator
1665          PI = I->all_referenced_protocol_begin(),
1666          E = I->all_referenced_protocol_end(); PI != E; ++PI)
1667      CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
1668                              InsMap, ClsMap, I);
1669    // Check class extensions (unnamed categories)
1670    for (const ObjCCategoryDecl *Categories = I->getFirstClassExtension();
1671         Categories; Categories = Categories->getNextClassExtension())
1672      ImplMethodsVsClassMethods(S, IMPDecl,
1673                                const_cast<ObjCCategoryDecl*>(Categories),
1674                                IncompleteImpl);
1675  } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1676    // For extended class, unimplemented methods in its protocols will
1677    // be reported in the primary class.
1678    if (!C->IsClassExtension()) {
1679      for (ObjCCategoryDecl::protocol_iterator PI = C->protocol_begin(),
1680           E = C->protocol_end(); PI != E; ++PI)
1681        CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
1682                                InsMap, ClsMap, CDecl);
1683      // Report unimplemented properties in the category as well.
1684      // When reporting on missing setter/getters, do not report when
1685      // setter/getter is implemented in category's primary class
1686      // implementation.
1687      if (ObjCInterfaceDecl *ID = C->getClassInterface())
1688        if (ObjCImplDecl *IMP = ID->getImplementation()) {
1689          for (ObjCImplementationDecl::instmeth_iterator
1690               I = IMP->instmeth_begin(), E = IMP->instmeth_end(); I!=E; ++I)
1691            InsMap.insert((*I)->getSelector());
1692        }
1693      DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap);
1694    }
1695  } else
1696    llvm_unreachable("invalid ObjCContainerDecl type.");
1697}
1698
1699/// ActOnForwardClassDeclaration -
1700Sema::DeclGroupPtrTy
1701Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
1702                                   IdentifierInfo **IdentList,
1703                                   SourceLocation *IdentLocs,
1704                                   unsigned NumElts) {
1705  SmallVector<Decl *, 8> DeclsInGroup;
1706  for (unsigned i = 0; i != NumElts; ++i) {
1707    // Check for another declaration kind with the same name.
1708    NamedDecl *PrevDecl
1709      = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
1710                         LookupOrdinaryName, ForRedeclaration);
1711    if (PrevDecl && PrevDecl->isTemplateParameter()) {
1712      // Maybe we will complain about the shadowed template parameter.
1713      DiagnoseTemplateParameterShadow(AtClassLoc, PrevDecl);
1714      // Just pretend that we didn't see the previous declaration.
1715      PrevDecl = 0;
1716    }
1717
1718    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1719      // GCC apparently allows the following idiom:
1720      //
1721      // typedef NSObject < XCElementTogglerP > XCElementToggler;
1722      // @class XCElementToggler;
1723      //
1724      // FIXME: Make an extension?
1725      TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
1726      if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
1727        Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
1728        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1729      } else {
1730        // a forward class declaration matching a typedef name of a class refers
1731        // to the underlying class.
1732        if (const ObjCObjectType *OI =
1733              TDD->getUnderlyingType()->getAs<ObjCObjectType>())
1734          PrevDecl = OI->getInterface();
1735      }
1736    }
1737    ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
1738    if (!IDecl) {  // Not already seen?  Make a forward decl.
1739      IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
1740                                        IdentList[i], IdentLocs[i], true);
1741
1742      // Push the ObjCInterfaceDecl on the scope chain but do *not* add it to
1743      // the current DeclContext.  This prevents clients that walk DeclContext
1744      // from seeing the imaginary ObjCInterfaceDecl until it is actually
1745      // declared later (if at all).  We also take care to explicitly make
1746      // sure this declaration is visible for name lookup.
1747      PushOnScopeChains(IDecl, TUScope, false);
1748      CurContext->makeDeclVisibleInContext(IDecl, true);
1749    }
1750    ObjCClassDecl *CDecl = ObjCClassDecl::Create(Context, CurContext, AtClassLoc,
1751                                                 IDecl, IdentLocs[i]);
1752    CurContext->addDecl(CDecl);
1753    CheckObjCDeclScope(CDecl);
1754    DeclsInGroup.push_back(CDecl);
1755  }
1756
1757  return BuildDeclaratorGroup(DeclsInGroup.data(), DeclsInGroup.size(), false);
1758}
1759
1760static bool tryMatchRecordTypes(ASTContext &Context,
1761                                Sema::MethodMatchStrategy strategy,
1762                                const Type *left, const Type *right);
1763
1764static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
1765                       QualType leftQT, QualType rightQT) {
1766  const Type *left =
1767    Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
1768  const Type *right =
1769    Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
1770
1771  if (left == right) return true;
1772
1773  // If we're doing a strict match, the types have to match exactly.
1774  if (strategy == Sema::MMS_strict) return false;
1775
1776  if (left->isIncompleteType() || right->isIncompleteType()) return false;
1777
1778  // Otherwise, use this absurdly complicated algorithm to try to
1779  // validate the basic, low-level compatibility of the two types.
1780
1781  // As a minimum, require the sizes and alignments to match.
1782  if (Context.getTypeInfo(left) != Context.getTypeInfo(right))
1783    return false;
1784
1785  // Consider all the kinds of non-dependent canonical types:
1786  // - functions and arrays aren't possible as return and parameter types
1787
1788  // - vector types of equal size can be arbitrarily mixed
1789  if (isa<VectorType>(left)) return isa<VectorType>(right);
1790  if (isa<VectorType>(right)) return false;
1791
1792  // - references should only match references of identical type
1793  // - structs, unions, and Objective-C objects must match more-or-less
1794  //   exactly
1795  // - everything else should be a scalar
1796  if (!left->isScalarType() || !right->isScalarType())
1797    return tryMatchRecordTypes(Context, strategy, left, right);
1798
1799  // Make scalars agree in kind, except count bools as chars, and group
1800  // all non-member pointers together.
1801  Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
1802  Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
1803  if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
1804  if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
1805  if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
1806    leftSK = Type::STK_ObjCObjectPointer;
1807  if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
1808    rightSK = Type::STK_ObjCObjectPointer;
1809
1810  // Note that data member pointers and function member pointers don't
1811  // intermix because of the size differences.
1812
1813  return (leftSK == rightSK);
1814}
1815
1816static bool tryMatchRecordTypes(ASTContext &Context,
1817                                Sema::MethodMatchStrategy strategy,
1818                                const Type *lt, const Type *rt) {
1819  assert(lt && rt && lt != rt);
1820
1821  if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
1822  RecordDecl *left = cast<RecordType>(lt)->getDecl();
1823  RecordDecl *right = cast<RecordType>(rt)->getDecl();
1824
1825  // Require union-hood to match.
1826  if (left->isUnion() != right->isUnion()) return false;
1827
1828  // Require an exact match if either is non-POD.
1829  if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
1830      (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
1831    return false;
1832
1833  // Require size and alignment to match.
1834  if (Context.getTypeInfo(lt) != Context.getTypeInfo(rt)) return false;
1835
1836  // Require fields to match.
1837  RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
1838  RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
1839  for (; li != le && ri != re; ++li, ++ri) {
1840    if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
1841      return false;
1842  }
1843  return (li == le && ri == re);
1844}
1845
1846/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
1847/// returns true, or false, accordingly.
1848/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
1849bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
1850                                      const ObjCMethodDecl *right,
1851                                      MethodMatchStrategy strategy) {
1852  if (!matchTypes(Context, strategy,
1853                  left->getResultType(), right->getResultType()))
1854    return false;
1855
1856  if (getLangOptions().ObjCAutoRefCount &&
1857      (left->hasAttr<NSReturnsRetainedAttr>()
1858         != right->hasAttr<NSReturnsRetainedAttr>() ||
1859       left->hasAttr<NSConsumesSelfAttr>()
1860         != right->hasAttr<NSConsumesSelfAttr>()))
1861    return false;
1862
1863  ObjCMethodDecl::param_iterator
1864    li = left->param_begin(), le = left->param_end(), ri = right->param_begin();
1865
1866  for (; li != le; ++li, ++ri) {
1867    assert(ri != right->param_end() && "Param mismatch");
1868    ParmVarDecl *lparm = *li, *rparm = *ri;
1869
1870    if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
1871      return false;
1872
1873    if (getLangOptions().ObjCAutoRefCount &&
1874        lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
1875      return false;
1876  }
1877  return true;
1878}
1879
1880/// \brief Read the contents of the method pool for a given selector from
1881/// external storage.
1882///
1883/// This routine should only be called once, when the method pool has no entry
1884/// for this selector.
1885Sema::GlobalMethodPool::iterator Sema::ReadMethodPool(Selector Sel) {
1886  assert(ExternalSource && "We need an external AST source");
1887  assert(MethodPool.find(Sel) == MethodPool.end() &&
1888         "Selector data already loaded into the method pool");
1889
1890  // Read the method list from the external source.
1891  GlobalMethods Methods = ExternalSource->ReadMethodPool(Sel);
1892
1893  return MethodPool.insert(std::make_pair(Sel, Methods)).first;
1894}
1895
1896void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
1897                                 bool instance) {
1898  GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
1899  if (Pos == MethodPool.end()) {
1900    if (ExternalSource)
1901      Pos = ReadMethodPool(Method->getSelector());
1902    else
1903      Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
1904                                             GlobalMethods())).first;
1905  }
1906  Method->setDefined(impl);
1907  ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
1908  if (Entry.Method == 0) {
1909    // Haven't seen a method with this selector name yet - add it.
1910    Entry.Method = Method;
1911    Entry.Next = 0;
1912    return;
1913  }
1914
1915  // We've seen a method with this name, see if we have already seen this type
1916  // signature.
1917  for (ObjCMethodList *List = &Entry; List; List = List->Next) {
1918    bool match = MatchTwoMethodDeclarations(Method, List->Method);
1919
1920    if (match) {
1921      ObjCMethodDecl *PrevObjCMethod = List->Method;
1922      PrevObjCMethod->setDefined(impl);
1923      // If a method is deprecated, push it in the global pool.
1924      // This is used for better diagnostics.
1925      if (Method->isDeprecated()) {
1926        if (!PrevObjCMethod->isDeprecated())
1927          List->Method = Method;
1928      }
1929      // If new method is unavailable, push it into global pool
1930      // unless previous one is deprecated.
1931      if (Method->isUnavailable()) {
1932        if (PrevObjCMethod->getAvailability() < AR_Deprecated)
1933          List->Method = Method;
1934      }
1935      return;
1936    }
1937  }
1938
1939  // We have a new signature for an existing method - add it.
1940  // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
1941  ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
1942  Entry.Next = new (Mem) ObjCMethodList(Method, Entry.Next);
1943}
1944
1945/// Determines if this is an "acceptable" loose mismatch in the global
1946/// method pool.  This exists mostly as a hack to get around certain
1947/// global mismatches which we can't afford to make warnings / errors.
1948/// Really, what we want is a way to take a method out of the global
1949/// method pool.
1950static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
1951                                       ObjCMethodDecl *other) {
1952  if (!chosen->isInstanceMethod())
1953    return false;
1954
1955  Selector sel = chosen->getSelector();
1956  if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
1957    return false;
1958
1959  // Don't complain about mismatches for -length if the method we
1960  // chose has an integral result type.
1961  return (chosen->getResultType()->isIntegerType());
1962}
1963
1964ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
1965                                               bool receiverIdOrClass,
1966                                               bool warn, bool instance) {
1967  GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
1968  if (Pos == MethodPool.end()) {
1969    if (ExternalSource)
1970      Pos = ReadMethodPool(Sel);
1971    else
1972      return 0;
1973  }
1974
1975  ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
1976
1977  if (warn && MethList.Method && MethList.Next) {
1978    bool issueDiagnostic = false, issueError = false;
1979
1980    // We support a warning which complains about *any* difference in
1981    // method signature.
1982    bool strictSelectorMatch =
1983      (receiverIdOrClass && warn &&
1984       (Diags.getDiagnosticLevel(diag::warn_strict_multiple_method_decl,
1985                                 R.getBegin()) !=
1986      DiagnosticsEngine::Ignored));
1987    if (strictSelectorMatch)
1988      for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next) {
1989        if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method,
1990                                        MMS_strict)) {
1991          issueDiagnostic = true;
1992          break;
1993        }
1994      }
1995
1996    // If we didn't see any strict differences, we won't see any loose
1997    // differences.  In ARC, however, we also need to check for loose
1998    // mismatches, because most of them are errors.
1999    if (!strictSelectorMatch ||
2000        (issueDiagnostic && getLangOptions().ObjCAutoRefCount))
2001      for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next) {
2002        // This checks if the methods differ in type mismatch.
2003        if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method,
2004                                        MMS_loose) &&
2005            !isAcceptableMethodMismatch(MethList.Method, Next->Method)) {
2006          issueDiagnostic = true;
2007          if (getLangOptions().ObjCAutoRefCount)
2008            issueError = true;
2009          break;
2010        }
2011      }
2012
2013    if (issueDiagnostic) {
2014      if (issueError)
2015        Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
2016      else if (strictSelectorMatch)
2017        Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
2018      else
2019        Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
2020
2021      Diag(MethList.Method->getLocStart(),
2022           issueError ? diag::note_possibility : diag::note_using)
2023        << MethList.Method->getSourceRange();
2024      for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
2025        Diag(Next->Method->getLocStart(), diag::note_also_found)
2026          << Next->Method->getSourceRange();
2027    }
2028  }
2029  return MethList.Method;
2030}
2031
2032ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
2033  GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2034  if (Pos == MethodPool.end())
2035    return 0;
2036
2037  GlobalMethods &Methods = Pos->second;
2038
2039  if (Methods.first.Method && Methods.first.Method->isDefined())
2040    return Methods.first.Method;
2041  if (Methods.second.Method && Methods.second.Method->isDefined())
2042    return Methods.second.Method;
2043  return 0;
2044}
2045
2046/// CompareMethodParamsInBaseAndSuper - This routine compares methods with
2047/// identical selector names in current and its super classes and issues
2048/// a warning if any of their argument types are incompatible.
2049void Sema::CompareMethodParamsInBaseAndSuper(Decl *ClassDecl,
2050                                             ObjCMethodDecl *Method,
2051                                             bool IsInstance)  {
2052  ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
2053  if (ID == 0) return;
2054
2055  while (ObjCInterfaceDecl *SD = ID->getSuperClass()) {
2056    ObjCMethodDecl *SuperMethodDecl =
2057        SD->lookupMethod(Method->getSelector(), IsInstance);
2058    if (SuperMethodDecl == 0) {
2059      ID = SD;
2060      continue;
2061    }
2062    ObjCMethodDecl::param_iterator ParamI = Method->param_begin(),
2063      E = Method->param_end();
2064    ObjCMethodDecl::param_iterator PrevI = SuperMethodDecl->param_begin();
2065    for (; ParamI != E; ++ParamI, ++PrevI) {
2066      // Number of parameters are the same and is guaranteed by selector match.
2067      assert(PrevI != SuperMethodDecl->param_end() && "Param mismatch");
2068      QualType T1 = Context.getCanonicalType((*ParamI)->getType());
2069      QualType T2 = Context.getCanonicalType((*PrevI)->getType());
2070      // If type of argument of method in this class does not match its
2071      // respective argument type in the super class method, issue warning;
2072      if (!Context.typesAreCompatible(T1, T2)) {
2073        Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
2074          << T1 << T2;
2075        Diag(SuperMethodDecl->getLocation(), diag::note_previous_declaration);
2076        return;
2077      }
2078    }
2079    ID = SD;
2080  }
2081}
2082
2083/// DiagnoseDuplicateIvars -
2084/// Check for duplicate ivars in the entire class at the start of
2085/// @implementation. This becomes necesssary because class extension can
2086/// add ivars to a class in random order which will not be known until
2087/// class's @implementation is seen.
2088void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
2089                                  ObjCInterfaceDecl *SID) {
2090  for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
2091       IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
2092    ObjCIvarDecl* Ivar = (*IVI);
2093    if (Ivar->isInvalidDecl())
2094      continue;
2095    if (IdentifierInfo *II = Ivar->getIdentifier()) {
2096      ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
2097      if (prevIvar) {
2098        Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
2099        Diag(prevIvar->getLocation(), diag::note_previous_declaration);
2100        Ivar->setInvalidDecl();
2101      }
2102    }
2103  }
2104}
2105
2106// Note: For class/category implemenations, allMethods/allProperties is
2107// always null.
2108void Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd,
2109                      Decl **allMethods, unsigned allNum,
2110                      Decl **allProperties, unsigned pNum,
2111                      DeclGroupPtrTy *allTUVars, unsigned tuvNum) {
2112
2113  if (!CurContext->isObjCContainer())
2114    return;
2115  ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
2116  Decl *ClassDecl = cast<Decl>(OCD);
2117
2118  bool isInterfaceDeclKind =
2119        isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
2120         || isa<ObjCProtocolDecl>(ClassDecl);
2121  bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
2122
2123  if (!isInterfaceDeclKind && AtEnd.isInvalid()) {
2124    // FIXME: This is wrong.  We shouldn't be pretending that there is
2125    //  an '@end' in the declaration.
2126    SourceLocation L = ClassDecl->getLocation();
2127    AtEnd.setBegin(L);
2128    AtEnd.setEnd(L);
2129    Diag(L, diag::err_missing_atend);
2130  }
2131
2132  // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
2133  llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
2134  llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
2135
2136  for (unsigned i = 0; i < allNum; i++ ) {
2137    ObjCMethodDecl *Method =
2138      cast_or_null<ObjCMethodDecl>(allMethods[i]);
2139
2140    if (!Method) continue;  // Already issued a diagnostic.
2141    if (Method->isInstanceMethod()) {
2142      /// Check for instance method of the same name with incompatible types
2143      const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
2144      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
2145                              : false;
2146      if ((isInterfaceDeclKind && PrevMethod && !match)
2147          || (checkIdenticalMethods && match)) {
2148          Diag(Method->getLocation(), diag::err_duplicate_method_decl)
2149            << Method->getDeclName();
2150          Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2151        Method->setInvalidDecl();
2152      } else {
2153        InsMap[Method->getSelector()] = Method;
2154        /// The following allows us to typecheck messages to "id".
2155        AddInstanceMethodToGlobalPool(Method);
2156        // verify that the instance method conforms to the same definition of
2157        // parent methods if it shadows one.
2158        CompareMethodParamsInBaseAndSuper(ClassDecl, Method, true);
2159      }
2160    } else {
2161      /// Check for class method of the same name with incompatible types
2162      const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
2163      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
2164                              : false;
2165      if ((isInterfaceDeclKind && PrevMethod && !match)
2166          || (checkIdenticalMethods && match)) {
2167        Diag(Method->getLocation(), diag::err_duplicate_method_decl)
2168          << Method->getDeclName();
2169        Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2170        Method->setInvalidDecl();
2171      } else {
2172        ClsMap[Method->getSelector()] = Method;
2173        /// The following allows us to typecheck messages to "Class".
2174        AddFactoryMethodToGlobalPool(Method);
2175        // verify that the class method conforms to the same definition of
2176        // parent methods if it shadows one.
2177        CompareMethodParamsInBaseAndSuper(ClassDecl, Method, false);
2178      }
2179    }
2180  }
2181  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
2182    // Compares properties declared in this class to those of its
2183    // super class.
2184    ComparePropertiesInBaseAndSuper(I);
2185    CompareProperties(I, I);
2186  } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
2187    // Categories are used to extend the class by declaring new methods.
2188    // By the same token, they are also used to add new properties. No
2189    // need to compare the added property to those in the class.
2190
2191    // Compare protocol properties with those in category
2192    CompareProperties(C, C);
2193    if (C->IsClassExtension()) {
2194      ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
2195      DiagnoseClassExtensionDupMethods(C, CCPrimary);
2196    }
2197  }
2198  if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
2199    if (CDecl->getIdentifier())
2200      // ProcessPropertyDecl is responsible for diagnosing conflicts with any
2201      // user-defined setter/getter. It also synthesizes setter/getter methods
2202      // and adds them to the DeclContext and global method pools.
2203      for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
2204                                            E = CDecl->prop_end();
2205           I != E; ++I)
2206        ProcessPropertyDecl(*I, CDecl);
2207    CDecl->setAtEndRange(AtEnd);
2208  }
2209  if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
2210    IC->setAtEndRange(AtEnd);
2211    if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
2212      // Any property declared in a class extension might have user
2213      // declared setter or getter in current class extension or one
2214      // of the other class extensions. Mark them as synthesized as
2215      // property will be synthesized when property with same name is
2216      // seen in the @implementation.
2217      for (const ObjCCategoryDecl *ClsExtDecl =
2218           IDecl->getFirstClassExtension();
2219           ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
2220        for (ObjCContainerDecl::prop_iterator I = ClsExtDecl->prop_begin(),
2221             E = ClsExtDecl->prop_end(); I != E; ++I) {
2222          ObjCPropertyDecl *Property = (*I);
2223          // Skip over properties declared @dynamic
2224          if (const ObjCPropertyImplDecl *PIDecl
2225              = IC->FindPropertyImplDecl(Property->getIdentifier()))
2226            if (PIDecl->getPropertyImplementation()
2227                  == ObjCPropertyImplDecl::Dynamic)
2228              continue;
2229
2230          for (const ObjCCategoryDecl *CExtDecl =
2231               IDecl->getFirstClassExtension();
2232               CExtDecl; CExtDecl = CExtDecl->getNextClassExtension()) {
2233            if (ObjCMethodDecl *GetterMethod =
2234                CExtDecl->getInstanceMethod(Property->getGetterName()))
2235              GetterMethod->setSynthesized(true);
2236            if (!Property->isReadOnly())
2237              if (ObjCMethodDecl *SetterMethod =
2238                  CExtDecl->getInstanceMethod(Property->getSetterName()))
2239                SetterMethod->setSynthesized(true);
2240          }
2241        }
2242      }
2243      ImplMethodsVsClassMethods(S, IC, IDecl);
2244      AtomicPropertySetterGetterRules(IC, IDecl);
2245      DiagnoseOwningPropertyGetterSynthesis(IC);
2246
2247      if (LangOpts.ObjCNonFragileABI2)
2248        while (IDecl->getSuperClass()) {
2249          DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
2250          IDecl = IDecl->getSuperClass();
2251        }
2252    }
2253    SetIvarInitializers(IC);
2254  } else if (ObjCCategoryImplDecl* CatImplClass =
2255                                   dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
2256    CatImplClass->setAtEndRange(AtEnd);
2257
2258    // Find category interface decl and then check that all methods declared
2259    // in this interface are implemented in the category @implementation.
2260    if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
2261      for (ObjCCategoryDecl *Categories = IDecl->getCategoryList();
2262           Categories; Categories = Categories->getNextClassCategory()) {
2263        if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
2264          ImplMethodsVsClassMethods(S, CatImplClass, Categories);
2265          break;
2266        }
2267      }
2268    }
2269  }
2270  if (isInterfaceDeclKind) {
2271    // Reject invalid vardecls.
2272    for (unsigned i = 0; i != tuvNum; i++) {
2273      DeclGroupRef DG = allTUVars[i].getAsVal<DeclGroupRef>();
2274      for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
2275        if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
2276          if (!VDecl->hasExternalStorage())
2277            Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
2278        }
2279    }
2280  }
2281  ActOnObjCContainerFinishDefinition();
2282}
2283
2284
2285/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
2286/// objective-c's type qualifier from the parser version of the same info.
2287static Decl::ObjCDeclQualifier
2288CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
2289  return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
2290}
2291
2292static inline
2293bool containsInvalidMethodImplAttribute(const AttrVec &A) {
2294  // The 'ibaction' attribute is allowed on method definitions because of
2295  // how the IBAction macro is used on both method declarations and definitions.
2296  // If the method definitions contains any other attributes, return true.
2297  for (AttrVec::const_iterator i = A.begin(), e = A.end(); i != e; ++i)
2298    if ((*i)->getKind() != attr::IBAction)
2299      return true;
2300  return false;
2301}
2302
2303namespace  {
2304  /// \brief Describes the compatibility of a result type with its method.
2305  enum ResultTypeCompatibilityKind {
2306    RTC_Compatible,
2307    RTC_Incompatible,
2308    RTC_Unknown
2309  };
2310}
2311
2312/// \brief Check whether the declared result type of the given Objective-C
2313/// method declaration is compatible with the method's class.
2314///
2315static ResultTypeCompatibilityKind
2316CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
2317                                    ObjCInterfaceDecl *CurrentClass) {
2318  QualType ResultType = Method->getResultType();
2319
2320  // If an Objective-C method inherits its related result type, then its
2321  // declared result type must be compatible with its own class type. The
2322  // declared result type is compatible if:
2323  if (const ObjCObjectPointerType *ResultObjectType
2324                                = ResultType->getAs<ObjCObjectPointerType>()) {
2325    //   - it is id or qualified id, or
2326    if (ResultObjectType->isObjCIdType() ||
2327        ResultObjectType->isObjCQualifiedIdType())
2328      return RTC_Compatible;
2329
2330    if (CurrentClass) {
2331      if (ObjCInterfaceDecl *ResultClass
2332                                      = ResultObjectType->getInterfaceDecl()) {
2333        //   - it is the same as the method's class type, or
2334        if (CurrentClass == ResultClass)
2335          return RTC_Compatible;
2336
2337        //   - it is a superclass of the method's class type
2338        if (ResultClass->isSuperClassOf(CurrentClass))
2339          return RTC_Compatible;
2340      }
2341    } else {
2342      // Any Objective-C pointer type might be acceptable for a protocol
2343      // method; we just don't know.
2344      return RTC_Unknown;
2345    }
2346  }
2347
2348  return RTC_Incompatible;
2349}
2350
2351namespace {
2352/// A helper class for searching for methods which a particular method
2353/// overrides.
2354class OverrideSearch {
2355  Sema &S;
2356  ObjCMethodDecl *Method;
2357  llvm::SmallPtrSet<ObjCContainerDecl*, 8> Searched;
2358  llvm::SmallPtrSet<ObjCMethodDecl*, 8> Overridden;
2359  bool Recursive;
2360
2361public:
2362  OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
2363    Selector selector = method->getSelector();
2364
2365    // Bypass this search if we've never seen an instance/class method
2366    // with this selector before.
2367    Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
2368    if (it == S.MethodPool.end()) {
2369      if (!S.ExternalSource) return;
2370      it = S.ReadMethodPool(selector);
2371    }
2372    ObjCMethodList &list =
2373      method->isInstanceMethod() ? it->second.first : it->second.second;
2374    if (!list.Method) return;
2375
2376    ObjCContainerDecl *container
2377      = cast<ObjCContainerDecl>(method->getDeclContext());
2378
2379    // Prevent the search from reaching this container again.  This is
2380    // important with categories, which override methods from the
2381    // interface and each other.
2382    Searched.insert(container);
2383    searchFromContainer(container);
2384  }
2385
2386  typedef llvm::SmallPtrSet<ObjCMethodDecl*,8>::iterator iterator;
2387  iterator begin() const { return Overridden.begin(); }
2388  iterator end() const { return Overridden.end(); }
2389
2390private:
2391  void searchFromContainer(ObjCContainerDecl *container) {
2392    if (container->isInvalidDecl()) return;
2393
2394    switch (container->getDeclKind()) {
2395#define OBJCCONTAINER(type, base) \
2396    case Decl::type: \
2397      searchFrom(cast<type##Decl>(container)); \
2398      break;
2399#define ABSTRACT_DECL(expansion)
2400#define DECL(type, base) \
2401    case Decl::type:
2402#include "clang/AST/DeclNodes.inc"
2403      llvm_unreachable("not an ObjC container!");
2404    }
2405  }
2406
2407  void searchFrom(ObjCProtocolDecl *protocol) {
2408    // A method in a protocol declaration overrides declarations from
2409    // referenced ("parent") protocols.
2410    search(protocol->getReferencedProtocols());
2411  }
2412
2413  void searchFrom(ObjCCategoryDecl *category) {
2414    // A method in a category declaration overrides declarations from
2415    // the main class and from protocols the category references.
2416    search(category->getClassInterface());
2417    search(category->getReferencedProtocols());
2418  }
2419
2420  void searchFrom(ObjCCategoryImplDecl *impl) {
2421    // A method in a category definition that has a category
2422    // declaration overrides declarations from the category
2423    // declaration.
2424    if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
2425      search(category);
2426
2427    // Otherwise it overrides declarations from the class.
2428    } else {
2429      search(impl->getClassInterface());
2430    }
2431  }
2432
2433  void searchFrom(ObjCInterfaceDecl *iface) {
2434    // A method in a class declaration overrides declarations from
2435
2436    //   - categories,
2437    for (ObjCCategoryDecl *category = iface->getCategoryList();
2438           category; category = category->getNextClassCategory())
2439      search(category);
2440
2441    //   - the super class, and
2442    if (ObjCInterfaceDecl *super = iface->getSuperClass())
2443      search(super);
2444
2445    //   - any referenced protocols.
2446    search(iface->getReferencedProtocols());
2447  }
2448
2449  void searchFrom(ObjCImplementationDecl *impl) {
2450    // A method in a class implementation overrides declarations from
2451    // the class interface.
2452    search(impl->getClassInterface());
2453  }
2454
2455
2456  void search(const ObjCProtocolList &protocols) {
2457    for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
2458         i != e; ++i)
2459      search(*i);
2460  }
2461
2462  void search(ObjCContainerDecl *container) {
2463    // Abort if we've already searched this container.
2464    if (!Searched.insert(container)) return;
2465
2466    // Check for a method in this container which matches this selector.
2467    ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
2468                                                Method->isInstanceMethod());
2469
2470    // If we find one, record it and bail out.
2471    if (meth) {
2472      Overridden.insert(meth);
2473      return;
2474    }
2475
2476    // Otherwise, search for methods that a hypothetical method here
2477    // would have overridden.
2478
2479    // Note that we're now in a recursive case.
2480    Recursive = true;
2481
2482    searchFromContainer(container);
2483  }
2484};
2485}
2486
2487Decl *Sema::ActOnMethodDeclaration(
2488    Scope *S,
2489    SourceLocation MethodLoc, SourceLocation EndLoc,
2490    tok::TokenKind MethodType,
2491    ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
2492    SourceLocation SelectorStartLoc,
2493    Selector Sel,
2494    // optional arguments. The number of types/arguments is obtained
2495    // from the Sel.getNumArgs().
2496    ObjCArgInfo *ArgInfo,
2497    DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
2498    AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
2499    bool isVariadic, bool MethodDefinition) {
2500  // Make sure we can establish a context for the method.
2501  if (!CurContext->isObjCContainer()) {
2502    Diag(MethodLoc, diag::error_missing_method_context);
2503    return 0;
2504  }
2505  ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
2506  Decl *ClassDecl = cast<Decl>(OCD);
2507  QualType resultDeclType;
2508
2509  bool HasRelatedResultType = false;
2510  TypeSourceInfo *ResultTInfo = 0;
2511  if (ReturnType) {
2512    resultDeclType = GetTypeFromParser(ReturnType, &ResultTInfo);
2513
2514    // Methods cannot return interface types. All ObjC objects are
2515    // passed by reference.
2516    if (resultDeclType->isObjCObjectType()) {
2517      Diag(MethodLoc, diag::err_object_cannot_be_passed_returned_by_value)
2518        << 0 << resultDeclType;
2519      return 0;
2520    }
2521
2522    HasRelatedResultType = (resultDeclType == Context.getObjCInstanceType());
2523  } else { // get the type for "id".
2524    resultDeclType = Context.getObjCIdType();
2525    Diag(MethodLoc, diag::warn_missing_method_return_type)
2526      << FixItHint::CreateInsertion(SelectorStartLoc, "(id)");
2527  }
2528
2529  ObjCMethodDecl* ObjCMethod =
2530    ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel, resultDeclType,
2531                           ResultTInfo,
2532                           CurContext,
2533                           MethodType == tok::minus, isVariadic,
2534                           /*isSynthesized=*/false,
2535                           /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
2536                           MethodDeclKind == tok::objc_optional
2537                             ? ObjCMethodDecl::Optional
2538                             : ObjCMethodDecl::Required,
2539                           HasRelatedResultType);
2540
2541  SmallVector<ParmVarDecl*, 16> Params;
2542
2543  for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
2544    QualType ArgType;
2545    TypeSourceInfo *DI;
2546
2547    if (ArgInfo[i].Type == 0) {
2548      ArgType = Context.getObjCIdType();
2549      DI = 0;
2550    } else {
2551      ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
2552      // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
2553      ArgType = Context.getAdjustedParameterType(ArgType);
2554    }
2555
2556    LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
2557                   LookupOrdinaryName, ForRedeclaration);
2558    LookupName(R, S);
2559    if (R.isSingleResult()) {
2560      NamedDecl *PrevDecl = R.getFoundDecl();
2561      if (S->isDeclScope(PrevDecl)) {
2562        Diag(ArgInfo[i].NameLoc,
2563             (MethodDefinition ? diag::warn_method_param_redefinition
2564                               : diag::warn_method_param_declaration))
2565          << ArgInfo[i].Name;
2566        Diag(PrevDecl->getLocation(),
2567             diag::note_previous_declaration);
2568      }
2569    }
2570
2571    SourceLocation StartLoc = DI
2572      ? DI->getTypeLoc().getBeginLoc()
2573      : ArgInfo[i].NameLoc;
2574
2575    ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
2576                                        ArgInfo[i].NameLoc, ArgInfo[i].Name,
2577                                        ArgType, DI, SC_None, SC_None);
2578
2579    Param->setObjCMethodScopeInfo(i);
2580
2581    Param->setObjCDeclQualifier(
2582      CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
2583
2584    // Apply the attributes to the parameter.
2585    ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
2586
2587    S->AddDecl(Param);
2588    IdResolver.AddDecl(Param);
2589
2590    Params.push_back(Param);
2591  }
2592
2593  for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
2594    ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
2595    QualType ArgType = Param->getType();
2596    if (ArgType.isNull())
2597      ArgType = Context.getObjCIdType();
2598    else
2599      // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
2600      ArgType = Context.getAdjustedParameterType(ArgType);
2601    if (ArgType->isObjCObjectType()) {
2602      Diag(Param->getLocation(),
2603           diag::err_object_cannot_be_passed_returned_by_value)
2604      << 1 << ArgType;
2605      Param->setInvalidDecl();
2606    }
2607    Param->setDeclContext(ObjCMethod);
2608
2609    Params.push_back(Param);
2610  }
2611
2612  ObjCMethod->setMethodParams(Context, Params.data(), Params.size());
2613  ObjCMethod->setObjCDeclQualifier(
2614    CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
2615
2616  if (AttrList)
2617    ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
2618
2619  // Add the method now.
2620  const ObjCMethodDecl *PrevMethod = 0;
2621  if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
2622    if (MethodType == tok::minus) {
2623      PrevMethod = ImpDecl->getInstanceMethod(Sel);
2624      ImpDecl->addInstanceMethod(ObjCMethod);
2625    } else {
2626      PrevMethod = ImpDecl->getClassMethod(Sel);
2627      ImpDecl->addClassMethod(ObjCMethod);
2628    }
2629
2630    if (ObjCMethod->hasAttrs() &&
2631        containsInvalidMethodImplAttribute(ObjCMethod->getAttrs()))
2632      Diag(EndLoc, diag::warn_attribute_method_def);
2633  } else {
2634    cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
2635  }
2636
2637  if (PrevMethod) {
2638    // You can never have two method definitions with the same name.
2639    Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
2640      << ObjCMethod->getDeclName();
2641    Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2642  }
2643
2644  // If this Objective-C method does not have a related result type, but we
2645  // are allowed to infer related result types, try to do so based on the
2646  // method family.
2647  ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
2648  if (!CurrentClass) {
2649    if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
2650      CurrentClass = Cat->getClassInterface();
2651    else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
2652      CurrentClass = Impl->getClassInterface();
2653    else if (ObjCCategoryImplDecl *CatImpl
2654                                   = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
2655      CurrentClass = CatImpl->getClassInterface();
2656  }
2657
2658  ResultTypeCompatibilityKind RTC
2659    = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
2660
2661  // Search for overridden methods and merge information down from them.
2662  OverrideSearch overrides(*this, ObjCMethod);
2663  for (OverrideSearch::iterator
2664         i = overrides.begin(), e = overrides.end(); i != e; ++i) {
2665    ObjCMethodDecl *overridden = *i;
2666
2667    // Propagate down the 'related result type' bit from overridden methods.
2668    if (RTC != RTC_Incompatible && overridden->hasRelatedResultType())
2669      ObjCMethod->SetRelatedResultType();
2670
2671    // Then merge the declarations.
2672    mergeObjCMethodDecls(ObjCMethod, overridden);
2673
2674    // Check for overriding methods
2675    if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
2676        isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext())) {
2677      WarnConflictingTypedMethods(ObjCMethod, overridden,
2678              isa<ObjCProtocolDecl>(overridden->getDeclContext()), true);
2679    }
2680  }
2681
2682  bool ARCError = false;
2683  if (getLangOptions().ObjCAutoRefCount)
2684    ARCError = CheckARCMethodDecl(*this, ObjCMethod);
2685
2686  // Infer the related result type when possible.
2687  if (!ARCError && RTC == RTC_Compatible &&
2688      !ObjCMethod->hasRelatedResultType() &&
2689      LangOpts.ObjCInferRelatedResultType) {
2690    bool InferRelatedResultType = false;
2691    switch (ObjCMethod->getMethodFamily()) {
2692    case OMF_None:
2693    case OMF_copy:
2694    case OMF_dealloc:
2695    case OMF_finalize:
2696    case OMF_mutableCopy:
2697    case OMF_release:
2698    case OMF_retainCount:
2699    case OMF_performSelector:
2700      break;
2701
2702    case OMF_alloc:
2703    case OMF_new:
2704      InferRelatedResultType = ObjCMethod->isClassMethod();
2705      break;
2706
2707    case OMF_init:
2708    case OMF_autorelease:
2709    case OMF_retain:
2710    case OMF_self:
2711      InferRelatedResultType = ObjCMethod->isInstanceMethod();
2712      break;
2713    }
2714
2715    if (InferRelatedResultType)
2716      ObjCMethod->SetRelatedResultType();
2717  }
2718
2719  return ObjCMethod;
2720}
2721
2722bool Sema::CheckObjCDeclScope(Decl *D) {
2723  if (isa<TranslationUnitDecl>(CurContext->getRedeclContext()))
2724    return false;
2725  // Following is also an error. But it is caused by a missing @end
2726  // and diagnostic is issued elsewhere.
2727  if (isa<ObjCContainerDecl>(CurContext->getRedeclContext())) {
2728    return false;
2729  }
2730
2731  Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
2732  D->setInvalidDecl();
2733
2734  return true;
2735}
2736
2737/// Called whenever @defs(ClassName) is encountered in the source.  Inserts the
2738/// instance variables of ClassName into Decls.
2739void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2740                     IdentifierInfo *ClassName,
2741                     SmallVectorImpl<Decl*> &Decls) {
2742  // Check that ClassName is a valid class
2743  ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
2744  if (!Class) {
2745    Diag(DeclStart, diag::err_undef_interface) << ClassName;
2746    return;
2747  }
2748  if (LangOpts.ObjCNonFragileABI) {
2749    Diag(DeclStart, diag::err_atdef_nonfragile_interface);
2750    return;
2751  }
2752
2753  // Collect the instance variables
2754  SmallVector<const ObjCIvarDecl*, 32> Ivars;
2755  Context.DeepCollectObjCIvars(Class, true, Ivars);
2756  // For each ivar, create a fresh ObjCAtDefsFieldDecl.
2757  for (unsigned i = 0; i < Ivars.size(); i++) {
2758    const FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
2759    RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
2760    Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
2761                                           /*FIXME: StartL=*/ID->getLocation(),
2762                                           ID->getLocation(),
2763                                           ID->getIdentifier(), ID->getType(),
2764                                           ID->getBitWidth());
2765    Decls.push_back(FD);
2766  }
2767
2768  // Introduce all of these fields into the appropriate scope.
2769  for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
2770       D != Decls.end(); ++D) {
2771    FieldDecl *FD = cast<FieldDecl>(*D);
2772    if (getLangOptions().CPlusPlus)
2773      PushOnScopeChains(cast<FieldDecl>(FD), S);
2774    else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
2775      Record->addDecl(FD);
2776  }
2777}
2778
2779/// \brief Build a type-check a new Objective-C exception variable declaration.
2780VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
2781                                      SourceLocation StartLoc,
2782                                      SourceLocation IdLoc,
2783                                      IdentifierInfo *Id,
2784                                      bool Invalid) {
2785  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
2786  // duration shall not be qualified by an address-space qualifier."
2787  // Since all parameters have automatic store duration, they can not have
2788  // an address space.
2789  if (T.getAddressSpace() != 0) {
2790    Diag(IdLoc, diag::err_arg_with_address_space);
2791    Invalid = true;
2792  }
2793
2794  // An @catch parameter must be an unqualified object pointer type;
2795  // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
2796  if (Invalid) {
2797    // Don't do any further checking.
2798  } else if (T->isDependentType()) {
2799    // Okay: we don't know what this type will instantiate to.
2800  } else if (!T->isObjCObjectPointerType()) {
2801    Invalid = true;
2802    Diag(IdLoc ,diag::err_catch_param_not_objc_type);
2803  } else if (T->isObjCQualifiedIdType()) {
2804    Invalid = true;
2805    Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
2806  }
2807
2808  VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
2809                                 T, TInfo, SC_None, SC_None);
2810  New->setExceptionVariable(true);
2811
2812  if (Invalid)
2813    New->setInvalidDecl();
2814  return New;
2815}
2816
2817Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
2818  const DeclSpec &DS = D.getDeclSpec();
2819
2820  // We allow the "register" storage class on exception variables because
2821  // GCC did, but we drop it completely. Any other storage class is an error.
2822  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2823    Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
2824      << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
2825  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
2826    Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
2827      << DS.getStorageClassSpec();
2828  }
2829  if (D.getDeclSpec().isThreadSpecified())
2830    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2831  D.getMutableDeclSpec().ClearStorageClassSpecs();
2832
2833  DiagnoseFunctionSpecifiers(D);
2834
2835  // Check that there are no default arguments inside the type of this
2836  // exception object (C++ only).
2837  if (getLangOptions().CPlusPlus)
2838    CheckExtraCXXDefaultArguments(D);
2839
2840  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
2841  QualType ExceptionType = TInfo->getType();
2842
2843  VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
2844                                        D.getSourceRange().getBegin(),
2845                                        D.getIdentifierLoc(),
2846                                        D.getIdentifier(),
2847                                        D.isInvalidType());
2848
2849  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2850  if (D.getCXXScopeSpec().isSet()) {
2851    Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
2852      << D.getCXXScopeSpec().getRange();
2853    New->setInvalidDecl();
2854  }
2855
2856  // Add the parameter declaration into this scope.
2857  S->AddDecl(New);
2858  if (D.getIdentifier())
2859    IdResolver.AddDecl(New);
2860
2861  ProcessDeclAttributes(S, New, D);
2862
2863  if (New->hasAttr<BlocksAttr>())
2864    Diag(New->getLocation(), diag::err_block_on_nonlocal);
2865  return New;
2866}
2867
2868/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
2869/// initialization.
2870void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
2871                                SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
2872  for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
2873       Iv= Iv->getNextIvar()) {
2874    QualType QT = Context.getBaseElementType(Iv->getType());
2875    if (QT->isRecordType())
2876      Ivars.push_back(Iv);
2877  }
2878}
2879
2880void Sema::DiagnoseUseOfUnimplementedSelectors() {
2881  // Load referenced selectors from the external source.
2882  if (ExternalSource) {
2883    SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
2884    ExternalSource->ReadReferencedSelectors(Sels);
2885    for (unsigned I = 0, N = Sels.size(); I != N; ++I)
2886      ReferencedSelectors[Sels[I].first] = Sels[I].second;
2887  }
2888
2889  // Warning will be issued only when selector table is
2890  // generated (which means there is at lease one implementation
2891  // in the TU). This is to match gcc's behavior.
2892  if (ReferencedSelectors.empty() ||
2893      !Context.AnyObjCImplementation())
2894    return;
2895  for (llvm::DenseMap<Selector, SourceLocation>::iterator S =
2896        ReferencedSelectors.begin(),
2897       E = ReferencedSelectors.end(); S != E; ++S) {
2898    Selector Sel = (*S).first;
2899    if (!LookupImplementedMethodInGlobalPool(Sel))
2900      Diag((*S).second, diag::warn_unimplemented_selector) << Sel;
2901  }
2902  return;
2903}
2904