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