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