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