clang API Documentation

SemaDeclObjC.cpp
Go to the documentation of this file.
00001 //===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file implements semantic analysis for Objective C declarations.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/Sema/SemaInternal.h"
00015 #include "clang/Sema/Lookup.h"
00016 #include "clang/Sema/ExternalSemaSource.h"
00017 #include "clang/Sema/Scope.h"
00018 #include "clang/Sema/ScopeInfo.h"
00019 #include "clang/AST/ASTConsumer.h"
00020 #include "clang/AST/Expr.h"
00021 #include "clang/AST/ExprObjC.h"
00022 #include "clang/AST/ASTContext.h"
00023 #include "clang/AST/DeclObjC.h"
00024 #include "clang/AST/ASTMutationListener.h"
00025 #include "clang/Basic/SourceManager.h"
00026 #include "clang/Sema/DeclSpec.h"
00027 #include "clang/Lex/Preprocessor.h"
00028 #include "llvm/ADT/DenseSet.h"
00029 
00030 using namespace clang;
00031 
00032 /// Check whether the given method, which must be in the 'init'
00033 /// family, is a valid member of that family.
00034 ///
00035 /// \param receiverTypeIfCall - if null, check this as if declaring it;
00036 ///   if non-null, check this as if making a call to it with the given
00037 ///   receiver type
00038 ///
00039 /// \return true to indicate that there was an error and appropriate
00040 ///   actions were taken
00041 bool Sema::checkInitMethod(ObjCMethodDecl *method,
00042                            QualType receiverTypeIfCall) {
00043   if (method->isInvalidDecl()) return true;
00044 
00045   // This castAs is safe: methods that don't return an object
00046   // pointer won't be inferred as inits and will reject an explicit
00047   // objc_method_family(init).
00048 
00049   // We ignore protocols here.  Should we?  What about Class?
00050 
00051   const ObjCObjectType *result = method->getResultType()
00052     ->castAs<ObjCObjectPointerType>()->getObjectType();
00053 
00054   if (result->isObjCId()) {
00055     return false;
00056   } else if (result->isObjCClass()) {
00057     // fall through: always an error
00058   } else {
00059     ObjCInterfaceDecl *resultClass = result->getInterface();
00060     assert(resultClass && "unexpected object type!");
00061 
00062     // It's okay for the result type to still be a forward declaration
00063     // if we're checking an interface declaration.
00064     if (!resultClass->hasDefinition()) {
00065       if (receiverTypeIfCall.isNull() &&
00066           !isa<ObjCImplementationDecl>(method->getDeclContext()))
00067         return false;
00068 
00069     // Otherwise, we try to compare class types.
00070     } else {
00071       // If this method was declared in a protocol, we can't check
00072       // anything unless we have a receiver type that's an interface.
00073       const ObjCInterfaceDecl *receiverClass = 0;
00074       if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
00075         if (receiverTypeIfCall.isNull())
00076           return false;
00077 
00078         receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
00079           ->getInterfaceDecl();
00080 
00081         // This can be null for calls to e.g. id<Foo>.
00082         if (!receiverClass) return false;
00083       } else {
00084         receiverClass = method->getClassInterface();
00085         assert(receiverClass && "method not associated with a class!");
00086       }
00087 
00088       // If either class is a subclass of the other, it's fine.
00089       if (receiverClass->isSuperClassOf(resultClass) ||
00090           resultClass->isSuperClassOf(receiverClass))
00091         return false;
00092     }
00093   }
00094 
00095   SourceLocation loc = method->getLocation();
00096 
00097   // If we're in a system header, and this is not a call, just make
00098   // the method unusable.
00099   if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
00100     method->addAttr(new (Context) UnavailableAttr(loc, Context,
00101                 "init method returns a type unrelated to its receiver type"));
00102     return true;
00103   }
00104 
00105   // Otherwise, it's an error.
00106   Diag(loc, diag::err_arc_init_method_unrelated_result_type);
00107   method->setInvalidDecl();
00108   return true;
00109 }
00110 
00111 void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, 
00112                                    const ObjCMethodDecl *Overridden,
00113                                    bool IsImplementation) {
00114   if (Overridden->hasRelatedResultType() && 
00115       !NewMethod->hasRelatedResultType()) {
00116     // This can only happen when the method follows a naming convention that
00117     // implies a related result type, and the original (overridden) method has
00118     // a suitable return type, but the new (overriding) method does not have
00119     // a suitable return type.
00120     QualType ResultType = NewMethod->getResultType();
00121     SourceRange ResultTypeRange;
00122     if (const TypeSourceInfo *ResultTypeInfo 
00123                                         = NewMethod->getResultTypeSourceInfo())
00124       ResultTypeRange = ResultTypeInfo->getTypeLoc().getSourceRange();
00125     
00126     // Figure out which class this method is part of, if any.
00127     ObjCInterfaceDecl *CurrentClass 
00128       = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
00129     if (!CurrentClass) {
00130       DeclContext *DC = NewMethod->getDeclContext();
00131       if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
00132         CurrentClass = Cat->getClassInterface();
00133       else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
00134         CurrentClass = Impl->getClassInterface();
00135       else if (ObjCCategoryImplDecl *CatImpl
00136                = dyn_cast<ObjCCategoryImplDecl>(DC))
00137         CurrentClass = CatImpl->getClassInterface();
00138     }
00139     
00140     if (CurrentClass) {
00141       Diag(NewMethod->getLocation(), 
00142            diag::warn_related_result_type_compatibility_class)
00143         << Context.getObjCInterfaceType(CurrentClass)
00144         << ResultType
00145         << ResultTypeRange;
00146     } else {
00147       Diag(NewMethod->getLocation(), 
00148            diag::warn_related_result_type_compatibility_protocol)
00149         << ResultType
00150         << ResultTypeRange;
00151     }
00152     
00153     if (ObjCMethodFamily Family = Overridden->getMethodFamily())
00154       Diag(Overridden->getLocation(), 
00155            diag::note_related_result_type_overridden_family)
00156         << Family;
00157     else
00158       Diag(Overridden->getLocation(), 
00159            diag::note_related_result_type_overridden);
00160   }
00161   if (getLangOpts().ObjCAutoRefCount) {
00162     if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
00163          Overridden->hasAttr<NSReturnsRetainedAttr>())) {
00164         Diag(NewMethod->getLocation(),
00165              diag::err_nsreturns_retained_attribute_mismatch) << 1;
00166         Diag(Overridden->getLocation(), diag::note_previous_decl) 
00167         << "method";
00168     }
00169     if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
00170               Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
00171         Diag(NewMethod->getLocation(),
00172              diag::err_nsreturns_retained_attribute_mismatch) << 0;
00173         Diag(Overridden->getLocation(), diag::note_previous_decl) 
00174         << "method";
00175     }
00176     ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
00177                                          oe = Overridden->param_end();
00178     for (ObjCMethodDecl::param_iterator
00179            ni = NewMethod->param_begin(), ne = NewMethod->param_end();
00180          ni != ne && oi != oe; ++ni, ++oi) {
00181       const ParmVarDecl *oldDecl = (*oi);
00182       ParmVarDecl *newDecl = (*ni);
00183       if (newDecl->hasAttr<NSConsumedAttr>() != 
00184           oldDecl->hasAttr<NSConsumedAttr>()) {
00185         Diag(newDecl->getLocation(),
00186              diag::err_nsconsumed_attribute_mismatch);
00187         Diag(oldDecl->getLocation(), diag::note_previous_decl) 
00188           << "parameter";
00189       }
00190     }
00191   }
00192 }
00193 
00194 /// \brief Check a method declaration for compatibility with the Objective-C
00195 /// ARC conventions.
00196 static bool CheckARCMethodDecl(Sema &S, ObjCMethodDecl *method) {
00197   ObjCMethodFamily family = method->getMethodFamily();
00198   switch (family) {
00199   case OMF_None:
00200   case OMF_dealloc:
00201   case OMF_finalize:
00202   case OMF_retain:
00203   case OMF_release:
00204   case OMF_autorelease:
00205   case OMF_retainCount:
00206   case OMF_self:
00207   case OMF_performSelector:
00208     return false;
00209 
00210   case OMF_init:
00211     // If the method doesn't obey the init rules, don't bother annotating it.
00212     if (S.checkInitMethod(method, QualType()))
00213       return true;
00214 
00215     method->addAttr(new (S.Context) NSConsumesSelfAttr(SourceLocation(),
00216                                                        S.Context));
00217 
00218     // Don't add a second copy of this attribute, but otherwise don't
00219     // let it be suppressed.
00220     if (method->hasAttr<NSReturnsRetainedAttr>())
00221       return false;
00222     break;
00223 
00224   case OMF_alloc:
00225   case OMF_copy:
00226   case OMF_mutableCopy:
00227   case OMF_new:
00228     if (method->hasAttr<NSReturnsRetainedAttr>() ||
00229         method->hasAttr<NSReturnsNotRetainedAttr>() ||
00230         method->hasAttr<NSReturnsAutoreleasedAttr>())
00231       return false;
00232     break;
00233   }
00234 
00235   method->addAttr(new (S.Context) NSReturnsRetainedAttr(SourceLocation(),
00236                                                         S.Context));
00237   return false;
00238 }
00239 
00240 static void DiagnoseObjCImplementedDeprecations(Sema &S,
00241                                                 NamedDecl *ND,
00242                                                 SourceLocation ImplLoc,
00243                                                 int select) {
00244   if (ND && ND->isDeprecated()) {
00245     S.Diag(ImplLoc, diag::warn_deprecated_def) << select;
00246     if (select == 0)
00247       S.Diag(ND->getLocation(), diag::note_method_declared_at)
00248         << ND->getDeclName();
00249     else
00250       S.Diag(ND->getLocation(), diag::note_previous_decl) << "class";
00251   }
00252 }
00253 
00254 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
00255 /// pool.
00256 void Sema::AddAnyMethodToGlobalPool(Decl *D) {
00257   ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
00258     
00259   // If we don't have a valid method decl, simply return.
00260   if (!MDecl)
00261     return;
00262   if (MDecl->isInstanceMethod())
00263     AddInstanceMethodToGlobalPool(MDecl, true);
00264   else
00265     AddFactoryMethodToGlobalPool(MDecl, true);
00266 }
00267 
00268 /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
00269 /// and user declared, in the method definition's AST.
00270 void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
00271   assert(getCurMethodDecl() == 0 && "Method parsing confused");
00272   ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
00273 
00274   // If we don't have a valid method decl, simply return.
00275   if (!MDecl)
00276     return;
00277 
00278   // Allow all of Sema to see that we are entering a method definition.
00279   PushDeclContext(FnBodyScope, MDecl);
00280   PushFunctionScope();
00281   
00282   // Create Decl objects for each parameter, entrring them in the scope for
00283   // binding to their use.
00284 
00285   // Insert the invisible arguments, self and _cmd!
00286   MDecl->createImplicitParams(Context, MDecl->getClassInterface());
00287 
00288   PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
00289   PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
00290 
00291   // Introduce all of the other parameters into this scope.
00292   for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
00293        E = MDecl->param_end(); PI != E; ++PI) {
00294     ParmVarDecl *Param = (*PI);
00295     if (!Param->isInvalidDecl() &&
00296         RequireCompleteType(Param->getLocation(), Param->getType(),
00297                             diag::err_typecheck_decl_incomplete_type))
00298           Param->setInvalidDecl();
00299     if ((*PI)->getIdentifier())
00300       PushOnScopeChains(*PI, FnBodyScope);
00301   }
00302 
00303   // In ARC, disallow definition of retain/release/autorelease/retainCount
00304   if (getLangOpts().ObjCAutoRefCount) {
00305     switch (MDecl->getMethodFamily()) {
00306     case OMF_retain:
00307     case OMF_retainCount:
00308     case OMF_release:
00309     case OMF_autorelease:
00310       Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
00311         << MDecl->getSelector();
00312       break;
00313 
00314     case OMF_None:
00315     case OMF_dealloc:
00316     case OMF_finalize:
00317     case OMF_alloc:
00318     case OMF_init:
00319     case OMF_mutableCopy:
00320     case OMF_copy:
00321     case OMF_new:
00322     case OMF_self:
00323     case OMF_performSelector:
00324       break;
00325     }
00326   }
00327 
00328   // Warn on deprecated methods under -Wdeprecated-implementations,
00329   // and prepare for warning on missing super calls.
00330   if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
00331     if (ObjCMethodDecl *IMD = 
00332           IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod()))
00333       DiagnoseObjCImplementedDeprecations(*this, 
00334                                           dyn_cast<NamedDecl>(IMD), 
00335                                           MDecl->getLocation(), 0);
00336 
00337     // If this is "dealloc" or "finalize", set some bit here.
00338     // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
00339     // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
00340     // Only do this if the current class actually has a superclass.
00341     if (IC->getSuperClass()) {
00342       ObjCShouldCallSuperDealloc = 
00343         !(Context.getLangOpts().ObjCAutoRefCount ||
00344           Context.getLangOpts().getGC() == LangOptions::GCOnly) &&
00345         MDecl->getMethodFamily() == OMF_dealloc;
00346       ObjCShouldCallSuperFinalize =
00347         Context.getLangOpts().getGC() != LangOptions::NonGC &&
00348         MDecl->getMethodFamily() == OMF_finalize;
00349     }
00350   }
00351 }
00352 
00353 namespace {
00354 
00355 // Callback to only accept typo corrections that are Objective-C classes.
00356 // If an ObjCInterfaceDecl* is given to the constructor, then the validation
00357 // function will reject corrections to that class.
00358 class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback {
00359  public:
00360   ObjCInterfaceValidatorCCC() : CurrentIDecl(0) {}
00361   explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
00362       : CurrentIDecl(IDecl) {}
00363 
00364   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
00365     ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
00366     return ID && !declaresSameEntity(ID, CurrentIDecl);
00367   }
00368 
00369  private:
00370   ObjCInterfaceDecl *CurrentIDecl;
00371 };
00372 
00373 }
00374 
00375 Decl *Sema::
00376 ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
00377                          IdentifierInfo *ClassName, SourceLocation ClassLoc,
00378                          IdentifierInfo *SuperName, SourceLocation SuperLoc,
00379                          Decl * const *ProtoRefs, unsigned NumProtoRefs,
00380                          const SourceLocation *ProtoLocs, 
00381                          SourceLocation EndProtoLoc, AttributeList *AttrList) {
00382   assert(ClassName && "Missing class identifier");
00383 
00384   // Check for another declaration kind with the same name.
00385   NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
00386                                          LookupOrdinaryName, ForRedeclaration);
00387 
00388   if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
00389     Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
00390     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
00391   }
00392 
00393   // Create a declaration to describe this @interface.
00394   ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
00395   ObjCInterfaceDecl *IDecl
00396     = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
00397                                 PrevIDecl, ClassLoc);
00398   
00399   if (PrevIDecl) {
00400     // Class already seen. Was it a definition?
00401     if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
00402       Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
00403         << PrevIDecl->getDeclName();
00404       Diag(Def->getLocation(), diag::note_previous_definition);
00405       IDecl->setInvalidDecl();
00406     }
00407   }
00408   
00409   if (AttrList)
00410     ProcessDeclAttributeList(TUScope, IDecl, AttrList);
00411   PushOnScopeChains(IDecl, TUScope);
00412 
00413   // Start the definition of this class. If we're in a redefinition case, there 
00414   // may already be a definition, so we'll end up adding to it.
00415   if (!IDecl->hasDefinition())
00416     IDecl->startDefinition();
00417   
00418   if (SuperName) {
00419     // Check if a different kind of symbol declared in this scope.
00420     PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
00421                                 LookupOrdinaryName);
00422 
00423     if (!PrevDecl) {
00424       // Try to correct for a typo in the superclass name without correcting
00425       // to the class we're defining.
00426       ObjCInterfaceValidatorCCC Validator(IDecl);
00427       if (TypoCorrection Corrected = CorrectTypo(
00428           DeclarationNameInfo(SuperName, SuperLoc), LookupOrdinaryName, TUScope,
00429           NULL, Validator)) {
00430         PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
00431         Diag(SuperLoc, diag::err_undef_superclass_suggest)
00432           << SuperName << ClassName << PrevDecl->getDeclName();
00433         Diag(PrevDecl->getLocation(), diag::note_previous_decl)
00434           << PrevDecl->getDeclName();
00435       }
00436     }
00437 
00438     if (declaresSameEntity(PrevDecl, IDecl)) {
00439       Diag(SuperLoc, diag::err_recursive_superclass)
00440         << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
00441       IDecl->setEndOfDefinitionLoc(ClassLoc);
00442     } else {
00443       ObjCInterfaceDecl *SuperClassDecl =
00444                                 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
00445 
00446       // Diagnose classes that inherit from deprecated classes.
00447       if (SuperClassDecl)
00448         (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
00449 
00450       if (PrevDecl && SuperClassDecl == 0) {
00451         // The previous declaration was not a class decl. Check if we have a
00452         // typedef. If we do, get the underlying class type.
00453         if (const TypedefNameDecl *TDecl =
00454               dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
00455           QualType T = TDecl->getUnderlyingType();
00456           if (T->isObjCObjectType()) {
00457             if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface())
00458               SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
00459           }
00460         }
00461 
00462         // This handles the following case:
00463         //
00464         // typedef int SuperClass;
00465         // @interface MyClass : SuperClass {} @end
00466         //
00467         if (!SuperClassDecl) {
00468           Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
00469           Diag(PrevDecl->getLocation(), diag::note_previous_definition);
00470         }
00471       }
00472 
00473       if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
00474         if (!SuperClassDecl)
00475           Diag(SuperLoc, diag::err_undef_superclass)
00476             << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
00477         else if (RequireCompleteType(SuperLoc, 
00478                                   Context.getObjCInterfaceType(SuperClassDecl),
00479                                      diag::err_forward_superclass,
00480                                      SuperClassDecl->getDeclName(),
00481                                      ClassName,
00482                                      SourceRange(AtInterfaceLoc, ClassLoc))) {
00483           SuperClassDecl = 0;
00484         }
00485       }
00486       IDecl->setSuperClass(SuperClassDecl);
00487       IDecl->setSuperClassLoc(SuperLoc);
00488       IDecl->setEndOfDefinitionLoc(SuperLoc);
00489     }
00490   } else { // we have a root class.
00491     IDecl->setEndOfDefinitionLoc(ClassLoc);
00492   }
00493 
00494   // Check then save referenced protocols.
00495   if (NumProtoRefs) {
00496     IDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
00497                            ProtoLocs, Context);
00498     IDecl->setEndOfDefinitionLoc(EndProtoLoc);
00499   }
00500 
00501   CheckObjCDeclScope(IDecl);
00502   return ActOnObjCContainerStartDefinition(IDecl);
00503 }
00504 
00505 /// ActOnCompatiblityAlias - this action is called after complete parsing of
00506 /// @compatibility_alias declaration. It sets up the alias relationships.
00507 Decl *Sema::ActOnCompatiblityAlias(SourceLocation AtLoc,
00508                                         IdentifierInfo *AliasName,
00509                                         SourceLocation AliasLocation,
00510                                         IdentifierInfo *ClassName,
00511                                         SourceLocation ClassLocation) {
00512   // Look for previous declaration of alias name
00513   NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
00514                                       LookupOrdinaryName, ForRedeclaration);
00515   if (ADecl) {
00516     if (isa<ObjCCompatibleAliasDecl>(ADecl))
00517       Diag(AliasLocation, diag::warn_previous_alias_decl);
00518     else
00519       Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
00520     Diag(ADecl->getLocation(), diag::note_previous_declaration);
00521     return 0;
00522   }
00523   // Check for class declaration
00524   NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
00525                                        LookupOrdinaryName, ForRedeclaration);
00526   if (const TypedefNameDecl *TDecl =
00527         dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
00528     QualType T = TDecl->getUnderlyingType();
00529     if (T->isObjCObjectType()) {
00530       if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
00531         ClassName = IDecl->getIdentifier();
00532         CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
00533                                   LookupOrdinaryName, ForRedeclaration);
00534       }
00535     }
00536   }
00537   ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
00538   if (CDecl == 0) {
00539     Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
00540     if (CDeclU)
00541       Diag(CDeclU->getLocation(), diag::note_previous_declaration);
00542     return 0;
00543   }
00544 
00545   // Everything checked out, instantiate a new alias declaration AST.
00546   ObjCCompatibleAliasDecl *AliasDecl =
00547     ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
00548 
00549   if (!CheckObjCDeclScope(AliasDecl))
00550     PushOnScopeChains(AliasDecl, TUScope);
00551 
00552   return AliasDecl;
00553 }
00554 
00555 bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
00556   IdentifierInfo *PName,
00557   SourceLocation &Ploc, SourceLocation PrevLoc,
00558   const ObjCList<ObjCProtocolDecl> &PList) {
00559   
00560   bool res = false;
00561   for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
00562        E = PList.end(); I != E; ++I) {
00563     if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
00564                                                  Ploc)) {
00565       if (PDecl->getIdentifier() == PName) {
00566         Diag(Ploc, diag::err_protocol_has_circular_dependency);
00567         Diag(PrevLoc, diag::note_previous_definition);
00568         res = true;
00569       }
00570       
00571       if (!PDecl->hasDefinition())
00572         continue;
00573       
00574       if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
00575             PDecl->getLocation(), PDecl->getReferencedProtocols()))
00576         res = true;
00577     }
00578   }
00579   return res;
00580 }
00581 
00582 Decl *
00583 Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
00584                                   IdentifierInfo *ProtocolName,
00585                                   SourceLocation ProtocolLoc,
00586                                   Decl * const *ProtoRefs,
00587                                   unsigned NumProtoRefs,
00588                                   const SourceLocation *ProtoLocs,
00589                                   SourceLocation EndProtoLoc,
00590                                   AttributeList *AttrList) {
00591   bool err = false;
00592   // FIXME: Deal with AttrList.
00593   assert(ProtocolName && "Missing protocol identifier");
00594   ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
00595                                               ForRedeclaration);
00596   ObjCProtocolDecl *PDecl = 0;
00597   if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : 0) {
00598     // If we already have a definition, complain.
00599     Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
00600     Diag(Def->getLocation(), diag::note_previous_definition);
00601 
00602     // Create a new protocol that is completely distinct from previous
00603     // declarations, and do not make this protocol available for name lookup.
00604     // That way, we'll end up completely ignoring the duplicate.
00605     // FIXME: Can we turn this into an error?
00606     PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
00607                                      ProtocolLoc, AtProtoInterfaceLoc,
00608                                      /*PrevDecl=*/0);
00609     PDecl->startDefinition();
00610   } else {
00611     if (PrevDecl) {
00612       // Check for circular dependencies among protocol declarations. This can
00613       // only happen if this protocol was forward-declared.
00614       ObjCList<ObjCProtocolDecl> PList;
00615       PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
00616       err = CheckForwardProtocolDeclarationForCircularDependency(
00617               ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
00618     }
00619 
00620     // Create the new declaration.
00621     PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
00622                                      ProtocolLoc, AtProtoInterfaceLoc,
00623                                      /*PrevDecl=*/PrevDecl);
00624     
00625     PushOnScopeChains(PDecl, TUScope);
00626     PDecl->startDefinition();
00627   }
00628   
00629   if (AttrList)
00630     ProcessDeclAttributeList(TUScope, PDecl, AttrList);
00631   
00632   // Merge attributes from previous declarations.
00633   if (PrevDecl)
00634     mergeDeclAttributes(PDecl, PrevDecl);
00635 
00636   if (!err && NumProtoRefs ) {
00637     /// Check then save referenced protocols.
00638     PDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
00639                            ProtoLocs, Context);
00640   }
00641 
00642   CheckObjCDeclScope(PDecl);
00643   return ActOnObjCContainerStartDefinition(PDecl);
00644 }
00645 
00646 /// FindProtocolDeclaration - This routine looks up protocols and
00647 /// issues an error if they are not declared. It returns list of
00648 /// protocol declarations in its 'Protocols' argument.
00649 void
00650 Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
00651                               const IdentifierLocPair *ProtocolId,
00652                               unsigned NumProtocols,
00653                               SmallVectorImpl<Decl *> &Protocols) {
00654   for (unsigned i = 0; i != NumProtocols; ++i) {
00655     ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first,
00656                                              ProtocolId[i].second);
00657     if (!PDecl) {
00658       DeclFilterCCC<ObjCProtocolDecl> Validator;
00659       TypoCorrection Corrected = CorrectTypo(
00660           DeclarationNameInfo(ProtocolId[i].first, ProtocolId[i].second),
00661           LookupObjCProtocolName, TUScope, NULL, Validator);
00662       if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>())) {
00663         Diag(ProtocolId[i].second, diag::err_undeclared_protocol_suggest)
00664           << ProtocolId[i].first << Corrected.getCorrection();
00665         Diag(PDecl->getLocation(), diag::note_previous_decl)
00666           << PDecl->getDeclName();
00667       }
00668     }
00669 
00670     if (!PDecl) {
00671       Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
00672         << ProtocolId[i].first;
00673       continue;
00674     }
00675 
00676     (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
00677 
00678     // If this is a forward declaration and we are supposed to warn in this
00679     // case, do it.
00680     if (WarnOnDeclarations && !PDecl->hasDefinition())
00681       Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
00682         << ProtocolId[i].first;
00683     Protocols.push_back(PDecl);
00684   }
00685 }
00686 
00687 /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
00688 /// a class method in its extension.
00689 ///
00690 void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
00691                                             ObjCInterfaceDecl *ID) {
00692   if (!ID)
00693     return;  // Possibly due to previous error
00694 
00695   llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
00696   for (ObjCInterfaceDecl::method_iterator i = ID->meth_begin(),
00697        e =  ID->meth_end(); i != e; ++i) {
00698     ObjCMethodDecl *MD = &*i;
00699     MethodMap[MD->getSelector()] = MD;
00700   }
00701 
00702   if (MethodMap.empty())
00703     return;
00704   for (ObjCCategoryDecl::method_iterator i = CAT->meth_begin(),
00705        e =  CAT->meth_end(); i != e; ++i) {
00706     ObjCMethodDecl *Method = &*i;
00707     const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
00708     if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
00709       Diag(Method->getLocation(), diag::err_duplicate_method_decl)
00710             << Method->getDeclName();
00711       Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
00712     }
00713   }
00714 }
00715 
00716 /// ActOnForwardProtocolDeclaration - Handle @protocol foo;
00717 Sema::DeclGroupPtrTy
00718 Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
00719                                       const IdentifierLocPair *IdentList,
00720                                       unsigned NumElts,
00721                                       AttributeList *attrList) {
00722   SmallVector<Decl *, 8> DeclsInGroup;
00723   for (unsigned i = 0; i != NumElts; ++i) {
00724     IdentifierInfo *Ident = IdentList[i].first;
00725     ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentList[i].second,
00726                                                 ForRedeclaration);
00727     ObjCProtocolDecl *PDecl
00728       = ObjCProtocolDecl::Create(Context, CurContext, Ident, 
00729                                  IdentList[i].second, AtProtocolLoc,
00730                                  PrevDecl);
00731         
00732     PushOnScopeChains(PDecl, TUScope);
00733     CheckObjCDeclScope(PDecl);
00734     
00735     if (attrList)
00736       ProcessDeclAttributeList(TUScope, PDecl, attrList);
00737     
00738     if (PrevDecl)
00739       mergeDeclAttributes(PDecl, PrevDecl);
00740 
00741     DeclsInGroup.push_back(PDecl);
00742   }
00743 
00744   return BuildDeclaratorGroup(DeclsInGroup.data(), DeclsInGroup.size(), false);
00745 }
00746 
00747 Decl *Sema::
00748 ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
00749                             IdentifierInfo *ClassName, SourceLocation ClassLoc,
00750                             IdentifierInfo *CategoryName,
00751                             SourceLocation CategoryLoc,
00752                             Decl * const *ProtoRefs,
00753                             unsigned NumProtoRefs,
00754                             const SourceLocation *ProtoLocs,
00755                             SourceLocation EndProtoLoc) {
00756   ObjCCategoryDecl *CDecl;
00757   ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
00758 
00759   /// Check that class of this category is already completely declared.
00760 
00761   if (!IDecl 
00762       || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
00763                              diag::err_category_forward_interface,
00764                              CategoryName == 0)) {
00765     // Create an invalid ObjCCategoryDecl to serve as context for
00766     // the enclosing method declarations.  We mark the decl invalid
00767     // to make it clear that this isn't a valid AST.
00768     CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
00769                                      ClassLoc, CategoryLoc, CategoryName,IDecl);
00770     CDecl->setInvalidDecl();
00771     CurContext->addDecl(CDecl);
00772         
00773     if (!IDecl)
00774       Diag(ClassLoc, diag::err_undef_interface) << ClassName;
00775     return ActOnObjCContainerStartDefinition(CDecl);
00776   }
00777 
00778   if (!CategoryName && IDecl->getImplementation()) {
00779     Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
00780     Diag(IDecl->getImplementation()->getLocation(), 
00781           diag::note_implementation_declared);
00782   }
00783 
00784   if (CategoryName) {
00785     /// Check for duplicate interface declaration for this category
00786     ObjCCategoryDecl *CDeclChain;
00787     for (CDeclChain = IDecl->getCategoryList(); CDeclChain;
00788          CDeclChain = CDeclChain->getNextClassCategory()) {
00789       if (CDeclChain->getIdentifier() == CategoryName) {
00790         // Class extensions can be declared multiple times.
00791         Diag(CategoryLoc, diag::warn_dup_category_def)
00792           << ClassName << CategoryName;
00793         Diag(CDeclChain->getLocation(), diag::note_previous_definition);
00794         break;
00795       }
00796     }
00797   }
00798 
00799   CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
00800                                    ClassLoc, CategoryLoc, CategoryName, IDecl);
00801   // FIXME: PushOnScopeChains?
00802   CurContext->addDecl(CDecl);
00803 
00804   if (NumProtoRefs) {
00805     CDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs, 
00806                            ProtoLocs, Context);
00807     // Protocols in the class extension belong to the class.
00808     if (CDecl->IsClassExtension())
00809      IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl**)ProtoRefs, 
00810                                             NumProtoRefs, Context); 
00811   }
00812 
00813   CheckObjCDeclScope(CDecl);
00814   return ActOnObjCContainerStartDefinition(CDecl);
00815 }
00816 
00817 /// ActOnStartCategoryImplementation - Perform semantic checks on the
00818 /// category implementation declaration and build an ObjCCategoryImplDecl
00819 /// object.
00820 Decl *Sema::ActOnStartCategoryImplementation(
00821                       SourceLocation AtCatImplLoc,
00822                       IdentifierInfo *ClassName, SourceLocation ClassLoc,
00823                       IdentifierInfo *CatName, SourceLocation CatLoc) {
00824   ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
00825   ObjCCategoryDecl *CatIDecl = 0;
00826   if (IDecl && IDecl->hasDefinition()) {
00827     CatIDecl = IDecl->FindCategoryDeclaration(CatName);
00828     if (!CatIDecl) {
00829       // Category @implementation with no corresponding @interface.
00830       // Create and install one.
00831       CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
00832                                           ClassLoc, CatLoc,
00833                                           CatName, IDecl);
00834       CatIDecl->setImplicit();
00835     }
00836   }
00837 
00838   ObjCCategoryImplDecl *CDecl =
00839     ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
00840                                  ClassLoc, AtCatImplLoc, CatLoc);
00841   /// Check that class of this category is already completely declared.
00842   if (!IDecl) {
00843     Diag(ClassLoc, diag::err_undef_interface) << ClassName;
00844     CDecl->setInvalidDecl();
00845   } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
00846                                  diag::err_undef_interface)) {
00847     CDecl->setInvalidDecl();
00848   }
00849 
00850   // FIXME: PushOnScopeChains?
00851   CurContext->addDecl(CDecl);
00852 
00853   // If the interface is deprecated/unavailable, warn/error about it.
00854   if (IDecl)
00855     DiagnoseUseOfDecl(IDecl, ClassLoc);
00856 
00857   /// Check that CatName, category name, is not used in another implementation.
00858   if (CatIDecl) {
00859     if (CatIDecl->getImplementation()) {
00860       Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
00861         << CatName;
00862       Diag(CatIDecl->getImplementation()->getLocation(),
00863            diag::note_previous_definition);
00864     } else {
00865       CatIDecl->setImplementation(CDecl);
00866       // Warn on implementating category of deprecated class under 
00867       // -Wdeprecated-implementations flag.
00868       DiagnoseObjCImplementedDeprecations(*this, 
00869                                           dyn_cast<NamedDecl>(IDecl), 
00870                                           CDecl->getLocation(), 2);
00871     }
00872   }
00873 
00874   CheckObjCDeclScope(CDecl);
00875   return ActOnObjCContainerStartDefinition(CDecl);
00876 }
00877 
00878 Decl *Sema::ActOnStartClassImplementation(
00879                       SourceLocation AtClassImplLoc,
00880                       IdentifierInfo *ClassName, SourceLocation ClassLoc,
00881                       IdentifierInfo *SuperClassname,
00882                       SourceLocation SuperClassLoc) {
00883   ObjCInterfaceDecl* IDecl = 0;
00884   // Check for another declaration kind with the same name.
00885   NamedDecl *PrevDecl
00886     = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
00887                        ForRedeclaration);
00888   if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
00889     Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
00890     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
00891   } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
00892     RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
00893                         diag::warn_undef_interface);
00894   } else {
00895     // We did not find anything with the name ClassName; try to correct for 
00896     // typos in the class name.
00897     ObjCInterfaceValidatorCCC Validator;
00898     if (TypoCorrection Corrected = CorrectTypo(
00899         DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope,
00900         NULL, Validator)) {
00901       // Suggest the (potentially) correct interface name. However, put the
00902       // fix-it hint itself in a separate note, since changing the name in 
00903       // the warning would make the fix-it change semantics.However, don't
00904       // provide a code-modification hint or use the typo name for recovery,
00905       // because this is just a warning. The program may actually be correct.
00906       IDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
00907       DeclarationName CorrectedName = Corrected.getCorrection();
00908       Diag(ClassLoc, diag::warn_undef_interface_suggest)
00909         << ClassName << CorrectedName;
00910       Diag(IDecl->getLocation(), diag::note_previous_decl) << CorrectedName
00911         << FixItHint::CreateReplacement(ClassLoc, CorrectedName.getAsString());
00912       IDecl = 0;
00913     } else {
00914       Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
00915     }
00916   }
00917 
00918   // Check that super class name is valid class name
00919   ObjCInterfaceDecl* SDecl = 0;
00920   if (SuperClassname) {
00921     // Check if a different kind of symbol declared in this scope.
00922     PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
00923                                 LookupOrdinaryName);
00924     if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
00925       Diag(SuperClassLoc, diag::err_redefinition_different_kind)
00926         << SuperClassname;
00927       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
00928     } else {
00929       SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
00930       if (SDecl && !SDecl->hasDefinition())
00931         SDecl = 0;
00932       if (!SDecl)
00933         Diag(SuperClassLoc, diag::err_undef_superclass)
00934           << SuperClassname << ClassName;
00935       else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
00936         // This implementation and its interface do not have the same
00937         // super class.
00938         Diag(SuperClassLoc, diag::err_conflicting_super_class)
00939           << SDecl->getDeclName();
00940         Diag(SDecl->getLocation(), diag::note_previous_definition);
00941       }
00942     }
00943   }
00944 
00945   if (!IDecl) {
00946     // Legacy case of @implementation with no corresponding @interface.
00947     // Build, chain & install the interface decl into the identifier.
00948 
00949     // FIXME: Do we support attributes on the @implementation? If so we should
00950     // copy them over.
00951     IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
00952                                       ClassName, /*PrevDecl=*/0, ClassLoc, 
00953                                       true);
00954     IDecl->startDefinition();
00955     if (SDecl) {
00956       IDecl->setSuperClass(SDecl);
00957       IDecl->setSuperClassLoc(SuperClassLoc);
00958       IDecl->setEndOfDefinitionLoc(SuperClassLoc);
00959     } else {
00960       IDecl->setEndOfDefinitionLoc(ClassLoc);
00961     }
00962     
00963     PushOnScopeChains(IDecl, TUScope);
00964   } else {
00965     // Mark the interface as being completed, even if it was just as
00966     //   @class ....;
00967     // declaration; the user cannot reopen it.
00968     if (!IDecl->hasDefinition())
00969       IDecl->startDefinition();
00970   }
00971 
00972   ObjCImplementationDecl* IMPDecl =
00973     ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
00974                                    ClassLoc, AtClassImplLoc);
00975 
00976   if (CheckObjCDeclScope(IMPDecl))
00977     return ActOnObjCContainerStartDefinition(IMPDecl);
00978 
00979   // Check that there is no duplicate implementation of this class.
00980   if (IDecl->getImplementation()) {
00981     // FIXME: Don't leak everything!
00982     Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
00983     Diag(IDecl->getImplementation()->getLocation(),
00984          diag::note_previous_definition);
00985   } else { // add it to the list.
00986     IDecl->setImplementation(IMPDecl);
00987     PushOnScopeChains(IMPDecl, TUScope);
00988     // Warn on implementating deprecated class under 
00989     // -Wdeprecated-implementations flag.
00990     DiagnoseObjCImplementedDeprecations(*this, 
00991                                         dyn_cast<NamedDecl>(IDecl), 
00992                                         IMPDecl->getLocation(), 1);
00993   }
00994   return ActOnObjCContainerStartDefinition(IMPDecl);
00995 }
00996 
00997 Sema::DeclGroupPtrTy
00998 Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
00999   SmallVector<Decl *, 64> DeclsInGroup;
01000   DeclsInGroup.reserve(Decls.size() + 1);
01001 
01002   for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
01003     Decl *Dcl = Decls[i];
01004     if (!Dcl)
01005       continue;
01006     if (Dcl->getDeclContext()->isFileContext())
01007       Dcl->setTopLevelDeclInObjCContainer();
01008     DeclsInGroup.push_back(Dcl);
01009   }
01010 
01011   DeclsInGroup.push_back(ObjCImpDecl);
01012 
01013   return BuildDeclaratorGroup(DeclsInGroup.data(), DeclsInGroup.size(), false);
01014 }
01015 
01016 void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
01017                                     ObjCIvarDecl **ivars, unsigned numIvars,
01018                                     SourceLocation RBrace) {
01019   assert(ImpDecl && "missing implementation decl");
01020   ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
01021   if (!IDecl)
01022     return;
01023   /// Check case of non-existing @interface decl.
01024   /// (legacy objective-c @implementation decl without an @interface decl).
01025   /// Add implementations's ivar to the synthesize class's ivar list.
01026   if (IDecl->isImplicitInterfaceDecl()) {
01027     IDecl->setEndOfDefinitionLoc(RBrace);
01028     // Add ivar's to class's DeclContext.
01029     for (unsigned i = 0, e = numIvars; i != e; ++i) {
01030       ivars[i]->setLexicalDeclContext(ImpDecl);
01031       IDecl->makeDeclVisibleInContext(ivars[i]);
01032       ImpDecl->addDecl(ivars[i]);
01033     }
01034     
01035     return;
01036   }
01037   // If implementation has empty ivar list, just return.
01038   if (numIvars == 0)
01039     return;
01040 
01041   assert(ivars && "missing @implementation ivars");
01042   if (LangOpts.ObjCNonFragileABI2) {
01043     if (ImpDecl->getSuperClass())
01044       Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
01045     for (unsigned i = 0; i < numIvars; i++) {
01046       ObjCIvarDecl* ImplIvar = ivars[i];
01047       if (const ObjCIvarDecl *ClsIvar = 
01048             IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
01049         Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration); 
01050         Diag(ClsIvar->getLocation(), diag::note_previous_definition);
01051         continue;
01052       }
01053       // Instance ivar to Implementation's DeclContext.
01054       ImplIvar->setLexicalDeclContext(ImpDecl);
01055       IDecl->makeDeclVisibleInContext(ImplIvar);
01056       ImpDecl->addDecl(ImplIvar);
01057     }
01058     return;
01059   }
01060   // Check interface's Ivar list against those in the implementation.
01061   // names and types must match.
01062   //
01063   unsigned j = 0;
01064   ObjCInterfaceDecl::ivar_iterator
01065     IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
01066   for (; numIvars > 0 && IVI != IVE; ++IVI) {
01067     ObjCIvarDecl* ImplIvar = ivars[j++];
01068     ObjCIvarDecl* ClsIvar = &*IVI;
01069     assert (ImplIvar && "missing implementation ivar");
01070     assert (ClsIvar && "missing class ivar");
01071 
01072     // First, make sure the types match.
01073     if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
01074       Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
01075         << ImplIvar->getIdentifier()
01076         << ImplIvar->getType() << ClsIvar->getType();
01077       Diag(ClsIvar->getLocation(), diag::note_previous_definition);
01078     } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
01079                ImplIvar->getBitWidthValue(Context) !=
01080                ClsIvar->getBitWidthValue(Context)) {
01081       Diag(ImplIvar->getBitWidth()->getLocStart(),
01082            diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier();
01083       Diag(ClsIvar->getBitWidth()->getLocStart(),
01084            diag::note_previous_definition);
01085     }
01086     // Make sure the names are identical.
01087     if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
01088       Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
01089         << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
01090       Diag(ClsIvar->getLocation(), diag::note_previous_definition);
01091     }
01092     --numIvars;
01093   }
01094 
01095   if (numIvars > 0)
01096     Diag(ivars[j]->getLocation(), diag::err_inconsistant_ivar_count);
01097   else if (IVI != IVE)
01098     Diag(IVI->getLocation(), diag::err_inconsistant_ivar_count);
01099 }
01100 
01101 void Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
01102                                bool &IncompleteImpl, unsigned DiagID) {
01103   // No point warning no definition of method which is 'unavailable'.
01104   if (method->hasAttr<UnavailableAttr>())
01105     return;
01106   if (!IncompleteImpl) {
01107     Diag(ImpLoc, diag::warn_incomplete_impl);
01108     IncompleteImpl = true;
01109   }
01110   if (DiagID == diag::warn_unimplemented_protocol_method)
01111     Diag(ImpLoc, DiagID) << method->getDeclName();
01112   else
01113     Diag(method->getLocation(), DiagID) << method->getDeclName();
01114 }
01115 
01116 /// Determines if type B can be substituted for type A.  Returns true if we can
01117 /// guarantee that anything that the user will do to an object of type A can 
01118 /// also be done to an object of type B.  This is trivially true if the two 
01119 /// types are the same, or if B is a subclass of A.  It becomes more complex
01120 /// in cases where protocols are involved.
01121 ///
01122 /// Object types in Objective-C describe the minimum requirements for an
01123 /// object, rather than providing a complete description of a type.  For
01124 /// example, if A is a subclass of B, then B* may refer to an instance of A.
01125 /// The principle of substitutability means that we may use an instance of A
01126 /// anywhere that we may use an instance of B - it will implement all of the
01127 /// ivars of B and all of the methods of B.  
01128 ///
01129 /// This substitutability is important when type checking methods, because 
01130 /// the implementation may have stricter type definitions than the interface.
01131 /// The interface specifies minimum requirements, but the implementation may
01132 /// have more accurate ones.  For example, a method may privately accept 
01133 /// instances of B, but only publish that it accepts instances of A.  Any
01134 /// object passed to it will be type checked against B, and so will implicitly
01135 /// by a valid A*.  Similarly, a method may return a subclass of the class that
01136 /// it is declared as returning.
01137 ///
01138 /// This is most important when considering subclassing.  A method in a
01139 /// subclass must accept any object as an argument that its superclass's
01140 /// implementation accepts.  It may, however, accept a more general type
01141 /// without breaking substitutability (i.e. you can still use the subclass
01142 /// anywhere that you can use the superclass, but not vice versa).  The
01143 /// converse requirement applies to return types: the return type for a
01144 /// subclass method must be a valid object of the kind that the superclass
01145 /// advertises, but it may be specified more accurately.  This avoids the need
01146 /// for explicit down-casting by callers.
01147 ///
01148 /// Note: This is a stricter requirement than for assignment.  
01149 static bool isObjCTypeSubstitutable(ASTContext &Context,
01150                                     const ObjCObjectPointerType *A,
01151                                     const ObjCObjectPointerType *B,
01152                                     bool rejectId) {
01153   // Reject a protocol-unqualified id.
01154   if (rejectId && B->isObjCIdType()) return false;
01155 
01156   // If B is a qualified id, then A must also be a qualified id and it must
01157   // implement all of the protocols in B.  It may not be a qualified class.
01158   // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
01159   // stricter definition so it is not substitutable for id<A>.
01160   if (B->isObjCQualifiedIdType()) {
01161     return A->isObjCQualifiedIdType() &&
01162            Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
01163                                                      QualType(B,0),
01164                                                      false);
01165   }
01166 
01167   /*
01168   // id is a special type that bypasses type checking completely.  We want a
01169   // warning when it is used in one place but not another.
01170   if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
01171 
01172 
01173   // If B is a qualified id, then A must also be a qualified id (which it isn't
01174   // if we've got this far)
01175   if (B->isObjCQualifiedIdType()) return false;
01176   */
01177 
01178   // Now we know that A and B are (potentially-qualified) class types.  The
01179   // normal rules for assignment apply.
01180   return Context.canAssignObjCInterfaces(A, B);
01181 }
01182 
01183 static SourceRange getTypeRange(TypeSourceInfo *TSI) {
01184   return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
01185 }
01186 
01187 static bool CheckMethodOverrideReturn(Sema &S,
01188                                       ObjCMethodDecl *MethodImpl,
01189                                       ObjCMethodDecl *MethodDecl,
01190                                       bool IsProtocolMethodDecl,
01191                                       bool IsOverridingMode,
01192                                       bool Warn) {
01193   if (IsProtocolMethodDecl &&
01194       (MethodDecl->getObjCDeclQualifier() !=
01195        MethodImpl->getObjCDeclQualifier())) {
01196     if (Warn) {
01197         S.Diag(MethodImpl->getLocation(), 
01198                (IsOverridingMode ? 
01199                  diag::warn_conflicting_overriding_ret_type_modifiers 
01200                  : diag::warn_conflicting_ret_type_modifiers))
01201           << MethodImpl->getDeclName()
01202           << getTypeRange(MethodImpl->getResultTypeSourceInfo());
01203         S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
01204           << getTypeRange(MethodDecl->getResultTypeSourceInfo());
01205     }
01206     else
01207       return false;
01208   }
01209   
01210   if (S.Context.hasSameUnqualifiedType(MethodImpl->getResultType(),
01211                                        MethodDecl->getResultType()))
01212     return true;
01213   if (!Warn)
01214     return false;
01215 
01216   unsigned DiagID = 
01217     IsOverridingMode ? diag::warn_conflicting_overriding_ret_types 
01218                      : diag::warn_conflicting_ret_types;
01219 
01220   // Mismatches between ObjC pointers go into a different warning
01221   // category, and sometimes they're even completely whitelisted.
01222   if (const ObjCObjectPointerType *ImplPtrTy =
01223         MethodImpl->getResultType()->getAs<ObjCObjectPointerType>()) {
01224     if (const ObjCObjectPointerType *IfacePtrTy =
01225           MethodDecl->getResultType()->getAs<ObjCObjectPointerType>()) {
01226       // Allow non-matching return types as long as they don't violate
01227       // the principle of substitutability.  Specifically, we permit
01228       // return types that are subclasses of the declared return type,
01229       // or that are more-qualified versions of the declared type.
01230       if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
01231         return false;
01232 
01233       DiagID = 
01234         IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types 
01235                           : diag::warn_non_covariant_ret_types;
01236     }
01237   }
01238 
01239   S.Diag(MethodImpl->getLocation(), DiagID)
01240     << MethodImpl->getDeclName()
01241     << MethodDecl->getResultType()
01242     << MethodImpl->getResultType()
01243     << getTypeRange(MethodImpl->getResultTypeSourceInfo());
01244   S.Diag(MethodDecl->getLocation(), 
01245          IsOverridingMode ? diag::note_previous_declaration 
01246                           : diag::note_previous_definition)
01247     << getTypeRange(MethodDecl->getResultTypeSourceInfo());
01248   return false;
01249 }
01250 
01251 static bool CheckMethodOverrideParam(Sema &S,
01252                                      ObjCMethodDecl *MethodImpl,
01253                                      ObjCMethodDecl *MethodDecl,
01254                                      ParmVarDecl *ImplVar,
01255                                      ParmVarDecl *IfaceVar,
01256                                      bool IsProtocolMethodDecl,
01257                                      bool IsOverridingMode,
01258                                      bool Warn) {
01259   if (IsProtocolMethodDecl &&
01260       (ImplVar->getObjCDeclQualifier() !=
01261        IfaceVar->getObjCDeclQualifier())) {
01262     if (Warn) {
01263       if (IsOverridingMode)
01264         S.Diag(ImplVar->getLocation(), 
01265                diag::warn_conflicting_overriding_param_modifiers)
01266             << getTypeRange(ImplVar->getTypeSourceInfo())
01267             << MethodImpl->getDeclName();
01268       else S.Diag(ImplVar->getLocation(), 
01269              diag::warn_conflicting_param_modifiers)
01270           << getTypeRange(ImplVar->getTypeSourceInfo())
01271           << MethodImpl->getDeclName();
01272       S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
01273           << getTypeRange(IfaceVar->getTypeSourceInfo());   
01274     }
01275     else
01276       return false;
01277   }
01278       
01279   QualType ImplTy = ImplVar->getType();
01280   QualType IfaceTy = IfaceVar->getType();
01281   
01282   if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
01283     return true;
01284   
01285   if (!Warn)
01286     return false;
01287   unsigned DiagID = 
01288     IsOverridingMode ? diag::warn_conflicting_overriding_param_types 
01289                      : diag::warn_conflicting_param_types;
01290 
01291   // Mismatches between ObjC pointers go into a different warning
01292   // category, and sometimes they're even completely whitelisted.
01293   if (const ObjCObjectPointerType *ImplPtrTy =
01294         ImplTy->getAs<ObjCObjectPointerType>()) {
01295     if (const ObjCObjectPointerType *IfacePtrTy =
01296           IfaceTy->getAs<ObjCObjectPointerType>()) {
01297       // Allow non-matching argument types as long as they don't
01298       // violate the principle of substitutability.  Specifically, the
01299       // implementation must accept any objects that the superclass
01300       // accepts, however it may also accept others.
01301       if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
01302         return false;
01303 
01304       DiagID = 
01305       IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types 
01306                        :  diag::warn_non_contravariant_param_types;
01307     }
01308   }
01309 
01310   S.Diag(ImplVar->getLocation(), DiagID)
01311     << getTypeRange(ImplVar->getTypeSourceInfo())
01312     << MethodImpl->getDeclName() << IfaceTy << ImplTy;
01313   S.Diag(IfaceVar->getLocation(), 
01314          (IsOverridingMode ? diag::note_previous_declaration 
01315                         : diag::note_previous_definition))
01316     << getTypeRange(IfaceVar->getTypeSourceInfo());
01317   return false;
01318 }
01319 
01320 /// In ARC, check whether the conventional meanings of the two methods
01321 /// match.  If they don't, it's a hard error.
01322 static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
01323                                       ObjCMethodDecl *decl) {
01324   ObjCMethodFamily implFamily = impl->getMethodFamily();
01325   ObjCMethodFamily declFamily = decl->getMethodFamily();
01326   if (implFamily == declFamily) return false;
01327 
01328   // Since conventions are sorted by selector, the only possibility is
01329   // that the types differ enough to cause one selector or the other
01330   // to fall out of the family.
01331   assert(implFamily == OMF_None || declFamily == OMF_None);
01332 
01333   // No further diagnostics required on invalid declarations.
01334   if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
01335 
01336   const ObjCMethodDecl *unmatched = impl;
01337   ObjCMethodFamily family = declFamily;
01338   unsigned errorID = diag::err_arc_lost_method_convention;
01339   unsigned noteID = diag::note_arc_lost_method_convention;
01340   if (declFamily == OMF_None) {
01341     unmatched = decl;
01342     family = implFamily;
01343     errorID = diag::err_arc_gained_method_convention;
01344     noteID = diag::note_arc_gained_method_convention;
01345   }
01346 
01347   // Indexes into a %select clause in the diagnostic.
01348   enum FamilySelector {
01349     F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
01350   };
01351   FamilySelector familySelector = FamilySelector();
01352 
01353   switch (family) {
01354   case OMF_None: llvm_unreachable("logic error, no method convention");
01355   case OMF_retain:
01356   case OMF_release:
01357   case OMF_autorelease:
01358   case OMF_dealloc:
01359   case OMF_finalize:
01360   case OMF_retainCount:
01361   case OMF_self:
01362   case OMF_performSelector:
01363     // Mismatches for these methods don't change ownership
01364     // conventions, so we don't care.
01365     return false;
01366 
01367   case OMF_init: familySelector = F_init; break;
01368   case OMF_alloc: familySelector = F_alloc; break;
01369   case OMF_copy: familySelector = F_copy; break;
01370   case OMF_mutableCopy: familySelector = F_mutableCopy; break;
01371   case OMF_new: familySelector = F_new; break;
01372   }
01373 
01374   enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
01375   ReasonSelector reasonSelector;
01376 
01377   // The only reason these methods don't fall within their families is
01378   // due to unusual result types.
01379   if (unmatched->getResultType()->isObjCObjectPointerType()) {
01380     reasonSelector = R_UnrelatedReturn;
01381   } else {
01382     reasonSelector = R_NonObjectReturn;
01383   }
01384 
01385   S.Diag(impl->getLocation(), errorID) << familySelector << reasonSelector;
01386   S.Diag(decl->getLocation(), noteID) << familySelector << reasonSelector;
01387 
01388   return true;
01389 }
01390 
01391 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
01392                                        ObjCMethodDecl *MethodDecl,
01393                                        bool IsProtocolMethodDecl) {
01394   if (getLangOpts().ObjCAutoRefCount &&
01395       checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
01396     return;
01397 
01398   CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, 
01399                             IsProtocolMethodDecl, false, 
01400                             true);
01401 
01402   for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
01403        IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
01404        EF = MethodDecl->param_end();
01405        IM != EM && IF != EF; ++IM, ++IF) {
01406     CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
01407                              IsProtocolMethodDecl, false, true);
01408   }
01409 
01410   if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
01411     Diag(ImpMethodDecl->getLocation(), 
01412          diag::warn_conflicting_variadic);
01413     Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
01414   }
01415 }
01416 
01417 void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
01418                                        ObjCMethodDecl *Overridden,
01419                                        bool IsProtocolMethodDecl) {
01420   
01421   CheckMethodOverrideReturn(*this, Method, Overridden, 
01422                             IsProtocolMethodDecl, true, 
01423                             true);
01424   
01425   for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
01426        IF = Overridden->param_begin(), EM = Method->param_end(),
01427        EF = Overridden->param_end();
01428        IM != EM && IF != EF; ++IM, ++IF) {
01429     CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
01430                              IsProtocolMethodDecl, true, true);
01431   }
01432   
01433   if (Method->isVariadic() != Overridden->isVariadic()) {
01434     Diag(Method->getLocation(), 
01435          diag::warn_conflicting_overriding_variadic);
01436     Diag(Overridden->getLocation(), diag::note_previous_declaration);
01437   }
01438 }
01439 
01440 /// WarnExactTypedMethods - This routine issues a warning if method
01441 /// implementation declaration matches exactly that of its declaration.
01442 void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
01443                                  ObjCMethodDecl *MethodDecl,
01444                                  bool IsProtocolMethodDecl) {
01445   // don't issue warning when protocol method is optional because primary
01446   // class is not required to implement it and it is safe for protocol
01447   // to implement it.
01448   if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
01449     return;
01450   // don't issue warning when primary class's method is 
01451   // depecated/unavailable.
01452   if (MethodDecl->hasAttr<UnavailableAttr>() ||
01453       MethodDecl->hasAttr<DeprecatedAttr>())
01454     return;
01455   
01456   bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, 
01457                                       IsProtocolMethodDecl, false, false);
01458   if (match)
01459     for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
01460          IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
01461          EF = MethodDecl->param_end();
01462          IM != EM && IF != EF; ++IM, ++IF) {
01463       match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, 
01464                                        *IM, *IF,
01465                                        IsProtocolMethodDecl, false, false);
01466       if (!match)
01467         break;
01468     }
01469   if (match)
01470     match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
01471   if (match)
01472     match = !(MethodDecl->isClassMethod() &&
01473               MethodDecl->getSelector() == GetNullarySelector("load", Context));
01474   
01475   if (match) {
01476     Diag(ImpMethodDecl->getLocation(), 
01477          diag::warn_category_method_impl_match);
01478     Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
01479       << MethodDecl->getDeclName();
01480   }
01481 }
01482 
01483 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
01484 /// improve the efficiency of selector lookups and type checking by associating
01485 /// with each protocol / interface / category the flattened instance tables. If
01486 /// we used an immutable set to keep the table then it wouldn't add significant
01487 /// memory cost and it would be handy for lookups.
01488 
01489 /// CheckProtocolMethodDefs - This routine checks unimplemented methods
01490 /// Declared in protocol, and those referenced by it.
01491 void Sema::CheckProtocolMethodDefs(SourceLocation ImpLoc,
01492                                    ObjCProtocolDecl *PDecl,
01493                                    bool& IncompleteImpl,
01494                                    const llvm::DenseSet<Selector> &InsMap,
01495                                    const llvm::DenseSet<Selector> &ClsMap,
01496                                    ObjCContainerDecl *CDecl) {
01497   ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
01498   ObjCInterfaceDecl *IDecl = C ? C->getClassInterface() 
01499                                : dyn_cast<ObjCInterfaceDecl>(CDecl);
01500   assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
01501   
01502   ObjCInterfaceDecl *Super = IDecl->getSuperClass();
01503   ObjCInterfaceDecl *NSIDecl = 0;
01504   if (getLangOpts().NeXTRuntime) {
01505     // check to see if class implements forwardInvocation method and objects
01506     // of this class are derived from 'NSProxy' so that to forward requests
01507     // from one object to another.
01508     // Under such conditions, which means that every method possible is
01509     // implemented in the class, we should not issue "Method definition not
01510     // found" warnings.
01511     // FIXME: Use a general GetUnarySelector method for this.
01512     IdentifierInfo* II = &Context.Idents.get("forwardInvocation");
01513     Selector fISelector = Context.Selectors.getSelector(1, &II);
01514     if (InsMap.count(fISelector))
01515       // Is IDecl derived from 'NSProxy'? If so, no instance methods
01516       // need be implemented in the implementation.
01517       NSIDecl = IDecl->lookupInheritedClass(&Context.Idents.get("NSProxy"));
01518   }
01519 
01520   // If a method lookup fails locally we still need to look and see if
01521   // the method was implemented by a base class or an inherited
01522   // protocol. This lookup is slow, but occurs rarely in correct code
01523   // and otherwise would terminate in a warning.
01524 
01525   // check unimplemented instance methods.
01526   if (!NSIDecl)
01527     for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
01528          E = PDecl->instmeth_end(); I != E; ++I) {
01529       ObjCMethodDecl *method = *I;
01530       if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
01531           !method->isSynthesized() && !InsMap.count(method->getSelector()) &&
01532           (!Super ||
01533            !Super->lookupInstanceMethod(method->getSelector()))) {
01534             // If a method is not implemented in the category implementation but
01535             // has been declared in its primary class, superclass,
01536             // or in one of their protocols, no need to issue the warning. 
01537             // This is because method will be implemented in the primary class 
01538             // or one of its super class implementation.
01539             
01540             // Ugly, but necessary. Method declared in protcol might have
01541             // have been synthesized due to a property declared in the class which
01542             // uses the protocol.
01543             if (ObjCMethodDecl *MethodInClass =
01544                   IDecl->lookupInstanceMethod(method->getSelector(), 
01545                                               true /*shallowCategoryLookup*/))
01546               if (C || MethodInClass->isSynthesized())
01547                 continue;
01548             unsigned DIAG = diag::warn_unimplemented_protocol_method;
01549             if (Diags.getDiagnosticLevel(DIAG, ImpLoc)
01550                 != DiagnosticsEngine::Ignored) {
01551               WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
01552               Diag(method->getLocation(), diag::note_method_declared_at)
01553                 << method->getDeclName();
01554               Diag(CDecl->getLocation(), diag::note_required_for_protocol_at)
01555                 << PDecl->getDeclName();
01556             }
01557           }
01558     }
01559   // check unimplemented class methods
01560   for (ObjCProtocolDecl::classmeth_iterator
01561          I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
01562        I != E; ++I) {
01563     ObjCMethodDecl *method = *I;
01564     if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
01565         !ClsMap.count(method->getSelector()) &&
01566         (!Super || !Super->lookupClassMethod(method->getSelector()))) {
01567       // See above comment for instance method lookups.
01568       if (C && IDecl->lookupClassMethod(method->getSelector(), 
01569                                         true /*shallowCategoryLookup*/))
01570         continue;
01571       unsigned DIAG = diag::warn_unimplemented_protocol_method;
01572       if (Diags.getDiagnosticLevel(DIAG, ImpLoc) !=
01573             DiagnosticsEngine::Ignored) {
01574         WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
01575         Diag(method->getLocation(), diag::note_method_declared_at)
01576           << method->getDeclName();
01577         Diag(IDecl->getLocation(), diag::note_required_for_protocol_at) <<
01578           PDecl->getDeclName();
01579       }
01580     }
01581   }
01582   // Check on this protocols's referenced protocols, recursively.
01583   for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
01584        E = PDecl->protocol_end(); PI != E; ++PI)
01585     CheckProtocolMethodDefs(ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap, CDecl);
01586 }
01587 
01588 /// MatchAllMethodDeclarations - Check methods declared in interface
01589 /// or protocol against those declared in their implementations.
01590 ///
01591 void Sema::MatchAllMethodDeclarations(const llvm::DenseSet<Selector> &InsMap,
01592                                       const llvm::DenseSet<Selector> &ClsMap,
01593                                       llvm::DenseSet<Selector> &InsMapSeen,
01594                                       llvm::DenseSet<Selector> &ClsMapSeen,
01595                                       ObjCImplDecl* IMPDecl,
01596                                       ObjCContainerDecl* CDecl,
01597                                       bool &IncompleteImpl,
01598                                       bool ImmediateClass,
01599                                       bool WarnCategoryMethodImpl) {
01600   // Check and see if instance methods in class interface have been
01601   // implemented in the implementation class. If so, their types match.
01602   for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(),
01603        E = CDecl->instmeth_end(); I != E; ++I) {
01604     if (InsMapSeen.count((*I)->getSelector()))
01605         continue;
01606     InsMapSeen.insert((*I)->getSelector());
01607     if (!(*I)->isSynthesized() &&
01608         !InsMap.count((*I)->getSelector())) {
01609       if (ImmediateClass)
01610         WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl,
01611                             diag::note_undef_method_impl);
01612       continue;
01613     } else {
01614       ObjCMethodDecl *ImpMethodDecl =
01615         IMPDecl->getInstanceMethod((*I)->getSelector());
01616       assert(CDecl->getInstanceMethod((*I)->getSelector()) &&
01617              "Expected to find the method through lookup as well");
01618       ObjCMethodDecl *MethodDecl = *I;
01619       // ImpMethodDecl may be null as in a @dynamic property.
01620       if (ImpMethodDecl) {
01621         if (!WarnCategoryMethodImpl)
01622           WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl,
01623                                       isa<ObjCProtocolDecl>(CDecl));
01624         else if (!MethodDecl->isSynthesized())
01625           WarnExactTypedMethods(ImpMethodDecl, MethodDecl,
01626                                 isa<ObjCProtocolDecl>(CDecl));
01627       }
01628     }
01629   }
01630 
01631   // Check and see if class methods in class interface have been
01632   // implemented in the implementation class. If so, their types match.
01633    for (ObjCInterfaceDecl::classmeth_iterator
01634        I = CDecl->classmeth_begin(), E = CDecl->classmeth_end(); I != E; ++I) {
01635      if (ClsMapSeen.count((*I)->getSelector()))
01636        continue;
01637      ClsMapSeen.insert((*I)->getSelector());
01638     if (!ClsMap.count((*I)->getSelector())) {
01639       if (ImmediateClass)
01640         WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl,
01641                             diag::note_undef_method_impl);
01642     } else {
01643       ObjCMethodDecl *ImpMethodDecl =
01644         IMPDecl->getClassMethod((*I)->getSelector());
01645       assert(CDecl->getClassMethod((*I)->getSelector()) &&
01646              "Expected to find the method through lookup as well");
01647       ObjCMethodDecl *MethodDecl = *I;
01648       if (!WarnCategoryMethodImpl)
01649         WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl, 
01650                                     isa<ObjCProtocolDecl>(CDecl));
01651       else
01652         WarnExactTypedMethods(ImpMethodDecl, MethodDecl,
01653                               isa<ObjCProtocolDecl>(CDecl));
01654     }
01655   }
01656   
01657   if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
01658     // Also methods in class extensions need be looked at next.
01659     for (const ObjCCategoryDecl *ClsExtDecl = I->getFirstClassExtension(); 
01660          ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension())
01661       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
01662                                  IMPDecl,
01663                                  const_cast<ObjCCategoryDecl *>(ClsExtDecl), 
01664                                  IncompleteImpl, false, 
01665                                  WarnCategoryMethodImpl);
01666     
01667     // Check for any implementation of a methods declared in protocol.
01668     for (ObjCInterfaceDecl::all_protocol_iterator
01669           PI = I->all_referenced_protocol_begin(),
01670           E = I->all_referenced_protocol_end(); PI != E; ++PI)
01671       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
01672                                  IMPDecl,
01673                                  (*PI), IncompleteImpl, false, 
01674                                  WarnCategoryMethodImpl);
01675     
01676     // FIXME. For now, we are not checking for extact match of methods 
01677     // in category implementation and its primary class's super class. 
01678     if (!WarnCategoryMethodImpl && I->getSuperClass())
01679       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
01680                                  IMPDecl,
01681                                  I->getSuperClass(), IncompleteImpl, false);
01682   }
01683 }
01684 
01685 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
01686 /// category matches with those implemented in its primary class and
01687 /// warns each time an exact match is found. 
01688 void Sema::CheckCategoryVsClassMethodMatches(
01689                                   ObjCCategoryImplDecl *CatIMPDecl) {
01690   llvm::DenseSet<Selector> InsMap, ClsMap;
01691   
01692   for (ObjCImplementationDecl::instmeth_iterator
01693        I = CatIMPDecl->instmeth_begin(), 
01694        E = CatIMPDecl->instmeth_end(); I!=E; ++I)
01695     InsMap.insert((*I)->getSelector());
01696   
01697   for (ObjCImplementationDecl::classmeth_iterator
01698        I = CatIMPDecl->classmeth_begin(),
01699        E = CatIMPDecl->classmeth_end(); I != E; ++I)
01700     ClsMap.insert((*I)->getSelector());
01701   if (InsMap.empty() && ClsMap.empty())
01702     return;
01703   
01704   // Get category's primary class.
01705   ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
01706   if (!CatDecl)
01707     return;
01708   ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
01709   if (!IDecl)
01710     return;
01711   llvm::DenseSet<Selector> InsMapSeen, ClsMapSeen;
01712   bool IncompleteImpl = false;
01713   MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
01714                              CatIMPDecl, IDecl,
01715                              IncompleteImpl, false, 
01716                              true /*WarnCategoryMethodImpl*/);
01717 }
01718 
01719 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
01720                                      ObjCContainerDecl* CDecl,
01721                                      bool IncompleteImpl) {
01722   llvm::DenseSet<Selector> InsMap;
01723   // Check and see if instance methods in class interface have been
01724   // implemented in the implementation class.
01725   for (ObjCImplementationDecl::instmeth_iterator
01726          I = IMPDecl->instmeth_begin(), E = IMPDecl->instmeth_end(); I!=E; ++I)
01727     InsMap.insert((*I)->getSelector());
01728 
01729   // Check and see if properties declared in the interface have either 1)
01730   // an implementation or 2) there is a @synthesize/@dynamic implementation
01731   // of the property in the @implementation.
01732   if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl))
01733     if  (!(LangOpts.ObjCDefaultSynthProperties && LangOpts.ObjCNonFragileABI2) ||
01734       IDecl->isObjCRequiresPropertyDefs())
01735       DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap);
01736       
01737   llvm::DenseSet<Selector> ClsMap;
01738   for (ObjCImplementationDecl::classmeth_iterator
01739        I = IMPDecl->classmeth_begin(),
01740        E = IMPDecl->classmeth_end(); I != E; ++I)
01741     ClsMap.insert((*I)->getSelector());
01742 
01743   // Check for type conflict of methods declared in a class/protocol and
01744   // its implementation; if any.
01745   llvm::DenseSet<Selector> InsMapSeen, ClsMapSeen;
01746   MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
01747                              IMPDecl, CDecl,
01748                              IncompleteImpl, true);
01749   
01750   // check all methods implemented in category against those declared
01751   // in its primary class.
01752   if (ObjCCategoryImplDecl *CatDecl = 
01753         dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
01754     CheckCategoryVsClassMethodMatches(CatDecl);
01755 
01756   // Check the protocol list for unimplemented methods in the @implementation
01757   // class.
01758   // Check and see if class methods in class interface have been
01759   // implemented in the implementation class.
01760 
01761   if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
01762     for (ObjCInterfaceDecl::all_protocol_iterator
01763           PI = I->all_referenced_protocol_begin(),
01764           E = I->all_referenced_protocol_end(); PI != E; ++PI)
01765       CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
01766                               InsMap, ClsMap, I);
01767     // Check class extensions (unnamed categories)
01768     for (const ObjCCategoryDecl *Categories = I->getFirstClassExtension();
01769          Categories; Categories = Categories->getNextClassExtension())
01770       ImplMethodsVsClassMethods(S, IMPDecl, 
01771                                 const_cast<ObjCCategoryDecl*>(Categories), 
01772                                 IncompleteImpl);
01773   } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
01774     // For extended class, unimplemented methods in its protocols will
01775     // be reported in the primary class.
01776     if (!C->IsClassExtension()) {
01777       for (ObjCCategoryDecl::protocol_iterator PI = C->protocol_begin(),
01778            E = C->protocol_end(); PI != E; ++PI)
01779         CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
01780                                 InsMap, ClsMap, CDecl);
01781       // Report unimplemented properties in the category as well.
01782       // When reporting on missing setter/getters, do not report when
01783       // setter/getter is implemented in category's primary class 
01784       // implementation.
01785       if (ObjCInterfaceDecl *ID = C->getClassInterface())
01786         if (ObjCImplDecl *IMP = ID->getImplementation()) {
01787           for (ObjCImplementationDecl::instmeth_iterator
01788                I = IMP->instmeth_begin(), E = IMP->instmeth_end(); I!=E; ++I)
01789             InsMap.insert((*I)->getSelector());
01790         }
01791       DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap);      
01792     } 
01793   } else
01794     llvm_unreachable("invalid ObjCContainerDecl type.");
01795 }
01796 
01797 /// ActOnForwardClassDeclaration -
01798 Sema::DeclGroupPtrTy
01799 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
01800                                    IdentifierInfo **IdentList,
01801                                    SourceLocation *IdentLocs,
01802                                    unsigned NumElts) {
01803   SmallVector<Decl *, 8> DeclsInGroup;
01804   for (unsigned i = 0; i != NumElts; ++i) {
01805     // Check for another declaration kind with the same name.
01806     NamedDecl *PrevDecl
01807       = LookupSingleName(TUScope, IdentList[i], IdentLocs[i], 
01808                          LookupOrdinaryName, ForRedeclaration);
01809     if (PrevDecl && PrevDecl->isTemplateParameter()) {
01810       // Maybe we will complain about the shadowed template parameter.
01811       DiagnoseTemplateParameterShadow(AtClassLoc, PrevDecl);
01812       // Just pretend that we didn't see the previous declaration.
01813       PrevDecl = 0;
01814     }
01815 
01816     if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
01817       // GCC apparently allows the following idiom:
01818       //
01819       // typedef NSObject < XCElementTogglerP > XCElementToggler;
01820       // @class XCElementToggler;
01821       //
01822       // Here we have chosen to ignore the forward class declaration
01823       // with a warning. Since this is the implied behavior.
01824       TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
01825       if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
01826         Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
01827         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
01828       } else {
01829         // a forward class declaration matching a typedef name of a class refers
01830         // to the underlying class. Just ignore the forward class with a warning
01831         // as this will force the intended behavior which is to lookup the typedef
01832         // name.
01833         if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
01834           Diag(AtClassLoc, diag::warn_forward_class_redefinition) << IdentList[i];
01835           Diag(PrevDecl->getLocation(), diag::note_previous_definition);
01836           continue;
01837         }
01838       }
01839     }
01840     
01841     // Create a declaration to describe this forward declaration.
01842     ObjCInterfaceDecl *PrevIDecl
01843       = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
01844     ObjCInterfaceDecl *IDecl
01845       = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
01846                                   IdentList[i], PrevIDecl, IdentLocs[i]);
01847     IDecl->setAtEndRange(IdentLocs[i]);
01848     
01849     PushOnScopeChains(IDecl, TUScope);
01850     CheckObjCDeclScope(IDecl);
01851     DeclsInGroup.push_back(IDecl);
01852   }
01853   
01854   return BuildDeclaratorGroup(DeclsInGroup.data(), DeclsInGroup.size(), false);
01855 }
01856 
01857 static bool tryMatchRecordTypes(ASTContext &Context,
01858                                 Sema::MethodMatchStrategy strategy,
01859                                 const Type *left, const Type *right);
01860 
01861 static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
01862                        QualType leftQT, QualType rightQT) {
01863   const Type *left =
01864     Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
01865   const Type *right =
01866     Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
01867 
01868   if (left == right) return true;
01869 
01870   // If we're doing a strict match, the types have to match exactly.
01871   if (strategy == Sema::MMS_strict) return false;
01872 
01873   if (left->isIncompleteType() || right->isIncompleteType()) return false;
01874 
01875   // Otherwise, use this absurdly complicated algorithm to try to
01876   // validate the basic, low-level compatibility of the two types.
01877 
01878   // As a minimum, require the sizes and alignments to match.
01879   if (Context.getTypeInfo(left) != Context.getTypeInfo(right))
01880     return false;
01881 
01882   // Consider all the kinds of non-dependent canonical types:
01883   // - functions and arrays aren't possible as return and parameter types
01884   
01885   // - vector types of equal size can be arbitrarily mixed
01886   if (isa<VectorType>(left)) return isa<VectorType>(right);
01887   if (isa<VectorType>(right)) return false;
01888 
01889   // - references should only match references of identical type
01890   // - structs, unions, and Objective-C objects must match more-or-less
01891   //   exactly
01892   // - everything else should be a scalar
01893   if (!left->isScalarType() || !right->isScalarType())
01894     return tryMatchRecordTypes(Context, strategy, left, right);
01895 
01896   // Make scalars agree in kind, except count bools as chars, and group
01897   // all non-member pointers together.
01898   Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
01899   Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
01900   if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
01901   if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
01902   if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
01903     leftSK = Type::STK_ObjCObjectPointer;
01904   if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
01905     rightSK = Type::STK_ObjCObjectPointer;
01906 
01907   // Note that data member pointers and function member pointers don't
01908   // intermix because of the size differences.
01909 
01910   return (leftSK == rightSK);
01911 }
01912 
01913 static bool tryMatchRecordTypes(ASTContext &Context,
01914                                 Sema::MethodMatchStrategy strategy,
01915                                 const Type *lt, const Type *rt) {
01916   assert(lt && rt && lt != rt);
01917 
01918   if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
01919   RecordDecl *left = cast<RecordType>(lt)->getDecl();
01920   RecordDecl *right = cast<RecordType>(rt)->getDecl();
01921 
01922   // Require union-hood to match.
01923   if (left->isUnion() != right->isUnion()) return false;
01924 
01925   // Require an exact match if either is non-POD.
01926   if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
01927       (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
01928     return false;
01929 
01930   // Require size and alignment to match.
01931   if (Context.getTypeInfo(lt) != Context.getTypeInfo(rt)) return false;
01932 
01933   // Require fields to match.
01934   RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
01935   RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
01936   for (; li != le && ri != re; ++li, ++ri) {
01937     if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
01938       return false;
01939   }
01940   return (li == le && ri == re);
01941 }
01942 
01943 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and
01944 /// returns true, or false, accordingly.
01945 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
01946 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
01947                                       const ObjCMethodDecl *right,
01948                                       MethodMatchStrategy strategy) {
01949   if (!matchTypes(Context, strategy,
01950                   left->getResultType(), right->getResultType()))
01951     return false;
01952 
01953   if (getLangOpts().ObjCAutoRefCount &&
01954       (left->hasAttr<NSReturnsRetainedAttr>()
01955          != right->hasAttr<NSReturnsRetainedAttr>() ||
01956        left->hasAttr<NSConsumesSelfAttr>()
01957          != right->hasAttr<NSConsumesSelfAttr>()))
01958     return false;
01959 
01960   ObjCMethodDecl::param_const_iterator
01961     li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
01962     re = right->param_end();
01963 
01964   for (; li != le && ri != re; ++li, ++ri) {
01965     assert(ri != right->param_end() && "Param mismatch");
01966     const ParmVarDecl *lparm = *li, *rparm = *ri;
01967 
01968     if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
01969       return false;
01970 
01971     if (getLangOpts().ObjCAutoRefCount &&
01972         lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
01973       return false;
01974   }
01975   return true;
01976 }
01977 
01978 void Sema::addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method) {
01979   // If the list is empty, make it a singleton list.
01980   if (List->Method == 0) {
01981     List->Method = Method;
01982     List->Next = 0;
01983     return;
01984   }
01985   
01986   // We've seen a method with this name, see if we have already seen this type
01987   // signature.
01988   ObjCMethodList *Previous = List;
01989   for (; List; Previous = List, List = List->Next) {
01990     if (!MatchTwoMethodDeclarations(Method, List->Method))
01991       continue;
01992     
01993     ObjCMethodDecl *PrevObjCMethod = List->Method;
01994 
01995     // Propagate the 'defined' bit.
01996     if (Method->isDefined())
01997       PrevObjCMethod->setDefined(true);
01998     
01999     // If a method is deprecated, push it in the global pool.
02000     // This is used for better diagnostics.
02001     if (Method->isDeprecated()) {
02002       if (!PrevObjCMethod->isDeprecated())
02003         List->Method = Method;
02004     }
02005     // If new method is unavailable, push it into global pool
02006     // unless previous one is deprecated.
02007     if (Method->isUnavailable()) {
02008       if (PrevObjCMethod->getAvailability() < AR_Deprecated)
02009         List->Method = Method;
02010     }
02011     
02012     return;
02013   }
02014   
02015   // We have a new signature for an existing method - add it.
02016   // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
02017   ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
02018   Previous->Next = new (Mem) ObjCMethodList(Method, 0);
02019 }
02020 
02021 /// \brief Read the contents of the method pool for a given selector from
02022 /// external storage.
02023 void Sema::ReadMethodPool(Selector Sel) {
02024   assert(ExternalSource && "We need an external AST source");
02025   ExternalSource->ReadMethodPool(Sel);
02026 }
02027 
02028 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
02029                                  bool instance) {
02030   // Ignore methods of invalid containers.
02031   if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
02032     return;
02033 
02034   if (ExternalSource)
02035     ReadMethodPool(Method->getSelector());
02036   
02037   GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
02038   if (Pos == MethodPool.end())
02039     Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
02040                                            GlobalMethods())).first;
02041   
02042   Method->setDefined(impl);
02043   
02044   ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
02045   addMethodToGlobalList(&Entry, Method);
02046 }
02047 
02048 /// Determines if this is an "acceptable" loose mismatch in the global
02049 /// method pool.  This exists mostly as a hack to get around certain
02050 /// global mismatches which we can't afford to make warnings / errors.
02051 /// Really, what we want is a way to take a method out of the global
02052 /// method pool.
02053 static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
02054                                        ObjCMethodDecl *other) {
02055   if (!chosen->isInstanceMethod())
02056     return false;
02057 
02058   Selector sel = chosen->getSelector();
02059   if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
02060     return false;
02061 
02062   // Don't complain about mismatches for -length if the method we
02063   // chose has an integral result type.
02064   return (chosen->getResultType()->isIntegerType());
02065 }
02066 
02067 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
02068                                                bool receiverIdOrClass,
02069                                                bool warn, bool instance) {
02070   if (ExternalSource)
02071     ReadMethodPool(Sel);
02072     
02073   GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
02074   if (Pos == MethodPool.end())
02075     return 0;
02076 
02077   ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
02078 
02079   if (warn && MethList.Method && MethList.Next) {
02080     bool issueDiagnostic = false, issueError = false;
02081 
02082     // We support a warning which complains about *any* difference in
02083     // method signature.
02084     bool strictSelectorMatch =
02085       (receiverIdOrClass && warn &&
02086        (Diags.getDiagnosticLevel(diag::warn_strict_multiple_method_decl,
02087                                  R.getBegin()) != 
02088       DiagnosticsEngine::Ignored));
02089     if (strictSelectorMatch)
02090       for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next) {
02091         if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method,
02092                                         MMS_strict)) {
02093           issueDiagnostic = true;
02094           break;
02095         }
02096       }
02097 
02098     // If we didn't see any strict differences, we won't see any loose
02099     // differences.  In ARC, however, we also need to check for loose
02100     // mismatches, because most of them are errors.
02101     if (!strictSelectorMatch ||
02102         (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
02103       for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next) {
02104         // This checks if the methods differ in type mismatch.
02105         if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method,
02106                                         MMS_loose) &&
02107             !isAcceptableMethodMismatch(MethList.Method, Next->Method)) {
02108           issueDiagnostic = true;
02109           if (getLangOpts().ObjCAutoRefCount)
02110             issueError = true;
02111           break;
02112         }
02113       }
02114 
02115     if (issueDiagnostic) {
02116       if (issueError)
02117         Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
02118       else if (strictSelectorMatch)
02119         Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
02120       else
02121         Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
02122 
02123       Diag(MethList.Method->getLocStart(), 
02124            issueError ? diag::note_possibility : diag::note_using)
02125         << MethList.Method->getSourceRange();
02126       for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
02127         Diag(Next->Method->getLocStart(), diag::note_also_found)
02128           << Next->Method->getSourceRange();
02129     }
02130   }
02131   return MethList.Method;
02132 }
02133 
02134 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
02135   GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
02136   if (Pos == MethodPool.end())
02137     return 0;
02138 
02139   GlobalMethods &Methods = Pos->second;
02140 
02141   if (Methods.first.Method && Methods.first.Method->isDefined())
02142     return Methods.first.Method;
02143   if (Methods.second.Method && Methods.second.Method->isDefined())
02144     return Methods.second.Method;
02145   return 0;
02146 }
02147 
02148 /// DiagnoseDuplicateIvars - 
02149 /// Check for duplicate ivars in the entire class at the start of 
02150 /// @implementation. This becomes necesssary because class extension can
02151 /// add ivars to a class in random order which will not be known until
02152 /// class's @implementation is seen.
02153 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, 
02154                                   ObjCInterfaceDecl *SID) {
02155   for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
02156        IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
02157     ObjCIvarDecl* Ivar = &*IVI;
02158     if (Ivar->isInvalidDecl())
02159       continue;
02160     if (IdentifierInfo *II = Ivar->getIdentifier()) {
02161       ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
02162       if (prevIvar) {
02163         Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
02164         Diag(prevIvar->getLocation(), diag::note_previous_declaration);
02165         Ivar->setInvalidDecl();
02166       }
02167     }
02168   }
02169 }
02170 
02171 Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
02172   switch (CurContext->getDeclKind()) {
02173     case Decl::ObjCInterface:
02174       return Sema::OCK_Interface;
02175     case Decl::ObjCProtocol:
02176       return Sema::OCK_Protocol;
02177     case Decl::ObjCCategory:
02178       if (dyn_cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
02179         return Sema::OCK_ClassExtension;
02180       else
02181         return Sema::OCK_Category;
02182     case Decl::ObjCImplementation:
02183       return Sema::OCK_Implementation;
02184     case Decl::ObjCCategoryImpl:
02185       return Sema::OCK_CategoryImplementation;
02186 
02187     default:
02188       return Sema::OCK_None;
02189   }
02190 }
02191 
02192 // Note: For class/category implemenations, allMethods/allProperties is
02193 // always null.
02194 Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd,
02195                        Decl **allMethods, unsigned allNum,
02196                        Decl **allProperties, unsigned pNum,
02197                        DeclGroupPtrTy *allTUVars, unsigned tuvNum) {
02198 
02199   if (getObjCContainerKind() == Sema::OCK_None)
02200     return 0;
02201 
02202   assert(AtEnd.isValid() && "Invalid location for '@end'");
02203 
02204   ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
02205   Decl *ClassDecl = cast<Decl>(OCD);
02206   
02207   bool isInterfaceDeclKind =
02208         isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
02209          || isa<ObjCProtocolDecl>(ClassDecl);
02210   bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
02211 
02212   // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
02213   llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
02214   llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
02215 
02216   for (unsigned i = 0; i < allNum; i++ ) {
02217     ObjCMethodDecl *Method =
02218       cast_or_null<ObjCMethodDecl>(allMethods[i]);
02219 
02220     if (!Method) continue;  // Already issued a diagnostic.
02221     if (Method->isInstanceMethod()) {
02222       /// Check for instance method of the same name with incompatible types
02223       const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
02224       bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
02225                               : false;
02226       if ((isInterfaceDeclKind && PrevMethod && !match)
02227           || (checkIdenticalMethods && match)) {
02228           Diag(Method->getLocation(), diag::err_duplicate_method_decl)
02229             << Method->getDeclName();
02230           Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
02231         Method->setInvalidDecl();
02232       } else {
02233         if (PrevMethod) {
02234           Method->setAsRedeclaration(PrevMethod);
02235           if (!Context.getSourceManager().isInSystemHeader(
02236                  Method->getLocation()))
02237             Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
02238               << Method->getDeclName();
02239           Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
02240         }
02241         InsMap[Method->getSelector()] = Method;
02242         /// The following allows us to typecheck messages to "id".
02243         AddInstanceMethodToGlobalPool(Method);
02244       }
02245     } else {
02246       /// Check for class method of the same name with incompatible types
02247       const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
02248       bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
02249                               : false;
02250       if ((isInterfaceDeclKind && PrevMethod && !match)
02251           || (checkIdenticalMethods && match)) {
02252         Diag(Method->getLocation(), diag::err_duplicate_method_decl)
02253           << Method->getDeclName();
02254         Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
02255         Method->setInvalidDecl();
02256       } else {
02257         if (PrevMethod) {
02258           Method->setAsRedeclaration(PrevMethod);
02259           if (!Context.getSourceManager().isInSystemHeader(
02260                  Method->getLocation()))
02261             Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
02262               << Method->getDeclName();
02263           Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
02264         }
02265         ClsMap[Method->getSelector()] = Method;
02266         AddFactoryMethodToGlobalPool(Method);
02267       }
02268     }
02269   }
02270   if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
02271     // Compares properties declared in this class to those of its
02272     // super class.
02273     ComparePropertiesInBaseAndSuper(I);
02274     CompareProperties(I, I);
02275   } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
02276     // Categories are used to extend the class by declaring new methods.
02277     // By the same token, they are also used to add new properties. No
02278     // need to compare the added property to those in the class.
02279 
02280     // Compare protocol properties with those in category
02281     CompareProperties(C, C);
02282     if (C->IsClassExtension()) {
02283       ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
02284       DiagnoseClassExtensionDupMethods(C, CCPrimary);
02285     }
02286   }
02287   if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
02288     if (CDecl->getIdentifier())
02289       // ProcessPropertyDecl is responsible for diagnosing conflicts with any
02290       // user-defined setter/getter. It also synthesizes setter/getter methods
02291       // and adds them to the DeclContext and global method pools.
02292       for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
02293                                             E = CDecl->prop_end();
02294            I != E; ++I)
02295         ProcessPropertyDecl(&*I, CDecl);
02296     CDecl->setAtEndRange(AtEnd);
02297   }
02298   if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
02299     IC->setAtEndRange(AtEnd);
02300     if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
02301       // Any property declared in a class extension might have user
02302       // declared setter or getter in current class extension or one
02303       // of the other class extensions. Mark them as synthesized as
02304       // property will be synthesized when property with same name is
02305       // seen in the @implementation.
02306       for (const ObjCCategoryDecl *ClsExtDecl =
02307            IDecl->getFirstClassExtension();
02308            ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
02309         for (ObjCContainerDecl::prop_iterator I = ClsExtDecl->prop_begin(),
02310              E = ClsExtDecl->prop_end(); I != E; ++I) {
02311           ObjCPropertyDecl *Property = &*I;
02312           // Skip over properties declared @dynamic
02313           if (const ObjCPropertyImplDecl *PIDecl
02314               = IC->FindPropertyImplDecl(Property->getIdentifier()))
02315             if (PIDecl->getPropertyImplementation() 
02316                   == ObjCPropertyImplDecl::Dynamic)
02317               continue;
02318           
02319           for (const ObjCCategoryDecl *CExtDecl =
02320                IDecl->getFirstClassExtension();
02321                CExtDecl; CExtDecl = CExtDecl->getNextClassExtension()) {
02322             if (ObjCMethodDecl *GetterMethod =
02323                 CExtDecl->getInstanceMethod(Property->getGetterName()))
02324               GetterMethod->setSynthesized(true);
02325             if (!Property->isReadOnly())
02326               if (ObjCMethodDecl *SetterMethod =
02327                   CExtDecl->getInstanceMethod(Property->getSetterName()))
02328                 SetterMethod->setSynthesized(true);
02329           }        
02330         }
02331       }
02332       ImplMethodsVsClassMethods(S, IC, IDecl);
02333       AtomicPropertySetterGetterRules(IC, IDecl);
02334       DiagnoseOwningPropertyGetterSynthesis(IC);
02335   
02336       bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
02337       if (IDecl->getSuperClass() == NULL) {
02338         // This class has no superclass, so check that it has been marked with
02339         // __attribute((objc_root_class)).
02340         if (!HasRootClassAttr) {
02341           SourceLocation DeclLoc(IDecl->getLocation());
02342           SourceLocation SuperClassLoc(PP.getLocForEndOfToken(DeclLoc));
02343           Diag(DeclLoc, diag::warn_objc_root_class_missing)
02344             << IDecl->getIdentifier();
02345           // See if NSObject is in the current scope, and if it is, suggest
02346           // adding " : NSObject " to the class declaration.
02347           NamedDecl *IF = LookupSingleName(TUScope,
02348                                            NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
02349                                            DeclLoc, LookupOrdinaryName);
02350           ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
02351           if (NSObjectDecl && NSObjectDecl->getDefinition()) {
02352             Diag(SuperClassLoc, diag::note_objc_needs_superclass)
02353               << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
02354           } else {
02355             Diag(SuperClassLoc, diag::note_objc_needs_superclass);
02356           }
02357         }
02358       } else if (HasRootClassAttr) {
02359         // Complain that only root classes may have this attribute.
02360         Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
02361       }
02362 
02363       if (LangOpts.ObjCNonFragileABI2) {
02364         while (IDecl->getSuperClass()) {
02365           DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
02366           IDecl = IDecl->getSuperClass();
02367         }
02368       }
02369     }
02370     SetIvarInitializers(IC);
02371   } else if (ObjCCategoryImplDecl* CatImplClass =
02372                                    dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
02373     CatImplClass->setAtEndRange(AtEnd);
02374 
02375     // Find category interface decl and then check that all methods declared
02376     // in this interface are implemented in the category @implementation.
02377     if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
02378       for (ObjCCategoryDecl *Categories = IDecl->getCategoryList();
02379            Categories; Categories = Categories->getNextClassCategory()) {
02380         if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
02381           ImplMethodsVsClassMethods(S, CatImplClass, Categories);
02382           break;
02383         }
02384       }
02385     }
02386   }
02387   if (isInterfaceDeclKind) {
02388     // Reject invalid vardecls.
02389     for (unsigned i = 0; i != tuvNum; i++) {
02390       DeclGroupRef DG = allTUVars[i].getAsVal<DeclGroupRef>();
02391       for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
02392         if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
02393           if (!VDecl->hasExternalStorage())
02394             Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
02395         }
02396     }
02397   }
02398   ActOnObjCContainerFinishDefinition();
02399 
02400   for (unsigned i = 0; i != tuvNum; i++) {
02401     DeclGroupRef DG = allTUVars[i].getAsVal<DeclGroupRef>();
02402     for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
02403       (*I)->setTopLevelDeclInObjCContainer();
02404     Consumer.HandleTopLevelDeclInObjCContainer(DG);
02405   }
02406 
02407   return ClassDecl;
02408 }
02409 
02410 
02411 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
02412 /// objective-c's type qualifier from the parser version of the same info.
02413 static Decl::ObjCDeclQualifier
02414 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
02415   return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
02416 }
02417 
02418 static inline
02419 bool containsInvalidMethodImplAttribute(ObjCMethodDecl *IMD,
02420                                         const AttrVec &A) {
02421   // If method is only declared in implementation (private method),
02422   // No need to issue any diagnostics on method definition with attributes.
02423   if (!IMD)
02424     return false;
02425 
02426   // method declared in interface has no attribute. 
02427   // But implementation has attributes. This is invalid
02428   if (!IMD->hasAttrs())
02429     return true;
02430 
02431   const AttrVec &D = IMD->getAttrs();
02432   if (D.size() != A.size())
02433     return true;
02434 
02435   // attributes on method declaration and definition must match exactly.
02436   // Note that we have at most a couple of attributes on methods, so this
02437   // n*n search is good enough.
02438   for (AttrVec::const_iterator i = A.begin(), e = A.end(); i != e; ++i) {
02439     bool match = false;
02440     for (AttrVec::const_iterator i1 = D.begin(), e1 = D.end(); i1 != e1; ++i1) {
02441       if ((*i)->getKind() == (*i1)->getKind()) {
02442         match = true;
02443         break;
02444       }
02445     }
02446     if (!match)
02447       return true;
02448   }
02449   return false;
02450 }
02451 
02452 /// \brief Check whether the declared result type of the given Objective-C
02453 /// method declaration is compatible with the method's class.
02454 ///
02455 static Sema::ResultTypeCompatibilityKind 
02456 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
02457                                     ObjCInterfaceDecl *CurrentClass) {
02458   QualType ResultType = Method->getResultType();
02459   
02460   // If an Objective-C method inherits its related result type, then its 
02461   // declared result type must be compatible with its own class type. The
02462   // declared result type is compatible if:
02463   if (const ObjCObjectPointerType *ResultObjectType
02464                                 = ResultType->getAs<ObjCObjectPointerType>()) {
02465     //   - it is id or qualified id, or
02466     if (ResultObjectType->isObjCIdType() ||
02467         ResultObjectType->isObjCQualifiedIdType())
02468       return Sema::RTC_Compatible;
02469   
02470     if (CurrentClass) {
02471       if (ObjCInterfaceDecl *ResultClass 
02472                                       = ResultObjectType->getInterfaceDecl()) {
02473         //   - it is the same as the method's class type, or
02474         if (declaresSameEntity(CurrentClass, ResultClass))
02475           return Sema::RTC_Compatible;
02476         
02477         //   - it is a superclass of the method's class type
02478         if (ResultClass->isSuperClassOf(CurrentClass))
02479           return Sema::RTC_Compatible;
02480       }      
02481     } else {
02482       // Any Objective-C pointer type might be acceptable for a protocol
02483       // method; we just don't know.
02484       return Sema::RTC_Unknown;
02485     }
02486   }
02487   
02488   return Sema::RTC_Incompatible;
02489 }
02490 
02491 namespace {
02492 /// A helper class for searching for methods which a particular method
02493 /// overrides.
02494 class OverrideSearch {
02495 public:
02496   Sema &S;
02497   ObjCMethodDecl *Method;
02498   llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden;
02499   bool Recursive;
02500 
02501 public:
02502   OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
02503     Selector selector = method->getSelector();
02504 
02505     // Bypass this search if we've never seen an instance/class method
02506     // with this selector before.
02507     Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
02508     if (it == S.MethodPool.end()) {
02509       if (!S.ExternalSource) return;
02510       S.ReadMethodPool(selector);
02511       
02512       it = S.MethodPool.find(selector);
02513       if (it == S.MethodPool.end())
02514         return;
02515     }
02516     ObjCMethodList &list =
02517       method->isInstanceMethod() ? it->second.first : it->second.second;
02518     if (!list.Method) return;
02519 
02520     ObjCContainerDecl *container
02521       = cast<ObjCContainerDecl>(method->getDeclContext());
02522 
02523     // Prevent the search from reaching this container again.  This is
02524     // important with categories, which override methods from the
02525     // interface and each other.
02526     if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) {
02527       searchFromContainer(container);
02528       if (ObjCInterfaceDecl *Interface = Category->getClassInterface())
02529         searchFromContainer(Interface);
02530     } else {
02531       searchFromContainer(container);
02532     }
02533   }
02534 
02535   typedef llvm::SmallPtrSet<ObjCMethodDecl*, 128>::iterator iterator;
02536   iterator begin() const { return Overridden.begin(); }
02537   iterator end() const { return Overridden.end(); }
02538 
02539 private:
02540   void searchFromContainer(ObjCContainerDecl *container) {
02541     if (container->isInvalidDecl()) return;
02542 
02543     switch (container->getDeclKind()) {
02544 #define OBJCCONTAINER(type, base) \
02545     case Decl::type: \
02546       searchFrom(cast<type##Decl>(container)); \
02547       break;
02548 #define ABSTRACT_DECL(expansion)
02549 #define DECL(type, base) \
02550     case Decl::type:
02551 #include "clang/AST/DeclNodes.inc"
02552       llvm_unreachable("not an ObjC container!");
02553     }
02554   }
02555 
02556   void searchFrom(ObjCProtocolDecl *protocol) {
02557     if (!protocol->hasDefinition())
02558       return;
02559     
02560     // A method in a protocol declaration overrides declarations from
02561     // referenced ("parent") protocols.
02562     search(protocol->getReferencedProtocols());
02563   }
02564 
02565   void searchFrom(ObjCCategoryDecl *category) {
02566     // A method in a category declaration overrides declarations from
02567     // the main class and from protocols the category references.
02568     // The main class is handled in the constructor.
02569     search(category->getReferencedProtocols());
02570   }
02571 
02572   void searchFrom(ObjCCategoryImplDecl *impl) {
02573     // A method in a category definition that has a category
02574     // declaration overrides declarations from the category
02575     // declaration.
02576     if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
02577       search(category);
02578       if (ObjCInterfaceDecl *Interface = category->getClassInterface())
02579         search(Interface);
02580 
02581     // Otherwise it overrides declarations from the class.
02582     } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) {
02583       search(Interface);
02584     }
02585   }
02586 
02587   void searchFrom(ObjCInterfaceDecl *iface) {
02588     // A method in a class declaration overrides declarations from
02589     if (!iface->hasDefinition())
02590       return;
02591     
02592     //   - categories,
02593     for (ObjCCategoryDecl *category = iface->getCategoryList();
02594            category; category = category->getNextClassCategory())
02595       search(category);
02596 
02597     //   - the super class, and
02598     if (ObjCInterfaceDecl *super = iface->getSuperClass())
02599       search(super);
02600 
02601     //   - any referenced protocols.
02602     search(iface->getReferencedProtocols());
02603   }
02604 
02605   void searchFrom(ObjCImplementationDecl *impl) {
02606     // A method in a class implementation overrides declarations from
02607     // the class interface.
02608     if (ObjCInterfaceDecl *Interface = impl->getClassInterface())
02609       search(Interface);
02610   }
02611 
02612 
02613   void search(const ObjCProtocolList &protocols) {
02614     for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
02615          i != e; ++i)
02616       search(*i);
02617   }
02618 
02619   void search(ObjCContainerDecl *container) {
02620     // Check for a method in this container which matches this selector.
02621     ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
02622                                                 Method->isInstanceMethod());
02623 
02624     // If we find one, record it and bail out.
02625     if (meth) {
02626       Overridden.insert(meth);
02627       return;
02628     }
02629 
02630     // Otherwise, search for methods that a hypothetical method here
02631     // would have overridden.
02632 
02633     // Note that we're now in a recursive case.
02634     Recursive = true;
02635 
02636     searchFromContainer(container);
02637   }
02638 };
02639 }
02640 
02641 void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
02642                                     ObjCInterfaceDecl *CurrentClass,
02643                                     ResultTypeCompatibilityKind RTC) {
02644   // Search for overridden methods and merge information down from them.
02645   OverrideSearch overrides(*this, ObjCMethod);
02646   // Keep track if the method overrides any method in the class's base classes,
02647   // its protocols, or its categories' protocols; we will keep that info
02648   // in the ObjCMethodDecl.
02649   // For this info, a method in an implementation is not considered as
02650   // overriding the same method in the interface or its categories.
02651   bool hasOverriddenMethodsInBaseOrProtocol = false;
02652   for (OverrideSearch::iterator
02653          i = overrides.begin(), e = overrides.end(); i != e; ++i) {
02654     ObjCMethodDecl *overridden = *i;
02655 
02656     if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
02657         CurrentClass != overridden->getClassInterface() ||
02658         overridden->isOverriding())
02659       hasOverriddenMethodsInBaseOrProtocol = true;
02660 
02661     // Propagate down the 'related result type' bit from overridden methods.
02662     if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
02663       ObjCMethod->SetRelatedResultType();
02664 
02665     // Then merge the declarations.
02666     mergeObjCMethodDecls(ObjCMethod, overridden);
02667 
02668     if (ObjCMethod->isImplicit() && overridden->isImplicit())
02669       continue; // Conflicting properties are detected elsewhere.
02670 
02671     // Check for overriding methods
02672     if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) || 
02673         isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
02674       CheckConflictingOverridingMethod(ObjCMethod, overridden,
02675               isa<ObjCProtocolDecl>(overridden->getDeclContext()));
02676     
02677     if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
02678         isa<ObjCInterfaceDecl>(overridden->getDeclContext())) {
02679       ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
02680                                           E = ObjCMethod->param_end();
02681       ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
02682                                      PrevE = overridden->param_end();
02683       for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
02684         assert(PrevI != overridden->param_end() && "Param mismatch");
02685         QualType T1 = Context.getCanonicalType((*ParamI)->getType());
02686         QualType T2 = Context.getCanonicalType((*PrevI)->getType());
02687         // If type of argument of method in this class does not match its
02688         // respective argument type in the super class method, issue warning;
02689         if (!Context.typesAreCompatible(T1, T2)) {
02690           Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
02691             << T1 << T2;
02692           Diag(overridden->getLocation(), diag::note_previous_declaration);
02693           break;
02694         }
02695       }
02696     }
02697   }
02698 
02699   ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
02700 }
02701 
02702 Decl *Sema::ActOnMethodDeclaration(
02703     Scope *S,
02704     SourceLocation MethodLoc, SourceLocation EndLoc,
02705     tok::TokenKind MethodType, 
02706     ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
02707     ArrayRef<SourceLocation> SelectorLocs,
02708     Selector Sel,
02709     // optional arguments. The number of types/arguments is obtained
02710     // from the Sel.getNumArgs().
02711     ObjCArgInfo *ArgInfo,
02712     DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
02713     AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
02714     bool isVariadic, bool MethodDefinition) {
02715   // Make sure we can establish a context for the method.
02716   if (!CurContext->isObjCContainer()) {
02717     Diag(MethodLoc, diag::error_missing_method_context);
02718     return 0;
02719   }
02720   ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
02721   Decl *ClassDecl = cast<Decl>(OCD); 
02722   QualType resultDeclType;
02723 
02724   bool HasRelatedResultType = false;
02725   TypeSourceInfo *ResultTInfo = 0;
02726   if (ReturnType) {
02727     resultDeclType = GetTypeFromParser(ReturnType, &ResultTInfo);
02728 
02729     // Methods cannot return interface types. All ObjC objects are
02730     // passed by reference.
02731     if (resultDeclType->isObjCObjectType()) {
02732       Diag(MethodLoc, diag::err_object_cannot_be_passed_returned_by_value)
02733         << 0 << resultDeclType;
02734       return 0;
02735     }    
02736     
02737     HasRelatedResultType = (resultDeclType == Context.getObjCInstanceType());
02738   } else { // get the type for "id".
02739     resultDeclType = Context.getObjCIdType();
02740     Diag(MethodLoc, diag::warn_missing_method_return_type)
02741       << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
02742   }
02743 
02744   ObjCMethodDecl* ObjCMethod =
02745     ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel,
02746                            resultDeclType,
02747                            ResultTInfo,
02748                            CurContext,
02749                            MethodType == tok::minus, isVariadic,
02750                            /*isSynthesized=*/false,
02751                            /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
02752                            MethodDeclKind == tok::objc_optional 
02753                              ? ObjCMethodDecl::Optional
02754                              : ObjCMethodDecl::Required,
02755                            HasRelatedResultType);
02756 
02757   SmallVector<ParmVarDecl*, 16> Params;
02758 
02759   for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
02760     QualType ArgType;
02761     TypeSourceInfo *DI;
02762 
02763     if (ArgInfo[i].Type == 0) {
02764       ArgType = Context.getObjCIdType();
02765       DI = 0;
02766     } else {
02767       ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
02768       // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
02769       ArgType = Context.getAdjustedParameterType(ArgType);
02770     }
02771 
02772     LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc, 
02773                    LookupOrdinaryName, ForRedeclaration);
02774     LookupName(R, S);
02775     if (R.isSingleResult()) {
02776       NamedDecl *PrevDecl = R.getFoundDecl();
02777       if (S->isDeclScope(PrevDecl)) {
02778         Diag(ArgInfo[i].NameLoc, 
02779              (MethodDefinition ? diag::warn_method_param_redefinition 
02780                                : diag::warn_method_param_declaration)) 
02781           << ArgInfo[i].Name;
02782         Diag(PrevDecl->getLocation(), 
02783              diag::note_previous_declaration);
02784       }
02785     }
02786 
02787     SourceLocation StartLoc = DI
02788       ? DI->getTypeLoc().getBeginLoc()
02789       : ArgInfo[i].NameLoc;
02790 
02791     ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
02792                                         ArgInfo[i].NameLoc, ArgInfo[i].Name,
02793                                         ArgType, DI, SC_None, SC_None);
02794 
02795     Param->setObjCMethodScopeInfo(i);
02796 
02797     Param->setObjCDeclQualifier(
02798       CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
02799 
02800     // Apply the attributes to the parameter.
02801     ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
02802 
02803     if (Param->hasAttr<BlocksAttr>()) {
02804       Diag(Param->getLocation(), diag::err_block_on_nonlocal);
02805       Param->setInvalidDecl();
02806     }
02807     S->AddDecl(Param);
02808     IdResolver.AddDecl(Param);
02809 
02810     Params.push_back(Param);
02811   }
02812   
02813   for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
02814     ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
02815     QualType ArgType = Param->getType();
02816     if (ArgType.isNull())
02817       ArgType = Context.getObjCIdType();
02818     else
02819       // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
02820       ArgType = Context.getAdjustedParameterType(ArgType);
02821     if (ArgType->isObjCObjectType()) {
02822       Diag(Param->getLocation(),
02823            diag::err_object_cannot_be_passed_returned_by_value)
02824       << 1 << ArgType;
02825       Param->setInvalidDecl();
02826     }
02827     Param->setDeclContext(ObjCMethod);
02828     
02829     Params.push_back(Param);
02830   }
02831   
02832   ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
02833   ObjCMethod->setObjCDeclQualifier(
02834     CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
02835 
02836   if (AttrList)
02837     ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
02838 
02839   // Add the method now.
02840   const ObjCMethodDecl *PrevMethod = 0;
02841   if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
02842     if (MethodType == tok::minus) {
02843       PrevMethod = ImpDecl->getInstanceMethod(Sel);
02844       ImpDecl->addInstanceMethod(ObjCMethod);
02845     } else {
02846       PrevMethod = ImpDecl->getClassMethod(Sel);
02847       ImpDecl->addClassMethod(ObjCMethod);
02848     }
02849 
02850     ObjCMethodDecl *IMD = 0;
02851     if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface())
02852       IMD = IDecl->lookupMethod(ObjCMethod->getSelector(), 
02853                                 ObjCMethod->isInstanceMethod());
02854     if (ObjCMethod->hasAttrs() &&
02855         containsInvalidMethodImplAttribute(IMD, ObjCMethod->getAttrs())) {
02856       SourceLocation MethodLoc = IMD->getLocation();
02857       if (!getSourceManager().isInSystemHeader(MethodLoc)) {
02858         Diag(EndLoc, diag::warn_attribute_method_def);
02859         Diag(MethodLoc, diag::note_method_declared_at)
02860           << ObjCMethod->getDeclName();
02861       }
02862     }
02863   } else {
02864     cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
02865   }
02866 
02867   if (PrevMethod) {
02868     // You can never have two method definitions with the same name.
02869     Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
02870       << ObjCMethod->getDeclName();
02871     Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
02872   }
02873 
02874   // If this Objective-C method does not have a related result type, but we
02875   // are allowed to infer related result types, try to do so based on the
02876   // method family.
02877   ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
02878   if (!CurrentClass) {
02879     if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
02880       CurrentClass = Cat->getClassInterface();
02881     else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
02882       CurrentClass = Impl->getClassInterface();
02883     else if (ObjCCategoryImplDecl *CatImpl
02884                                    = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
02885       CurrentClass = CatImpl->getClassInterface();
02886   }
02887 
02888   ResultTypeCompatibilityKind RTC
02889     = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
02890 
02891   CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
02892 
02893   bool ARCError = false;
02894   if (getLangOpts().ObjCAutoRefCount)
02895     ARCError = CheckARCMethodDecl(*this, ObjCMethod);
02896 
02897   // Infer the related result type when possible.
02898   if (!ARCError && RTC == Sema::RTC_Compatible &&
02899       !ObjCMethod->hasRelatedResultType() &&
02900       LangOpts.ObjCInferRelatedResultType) {
02901     bool InferRelatedResultType = false;
02902     switch (ObjCMethod->getMethodFamily()) {
02903     case OMF_None:
02904     case OMF_copy:
02905     case OMF_dealloc:
02906     case OMF_finalize:
02907     case OMF_mutableCopy:
02908     case OMF_release:
02909     case OMF_retainCount:
02910     case OMF_performSelector:
02911       break;
02912       
02913     case OMF_alloc:
02914     case OMF_new:
02915       InferRelatedResultType = ObjCMethod->isClassMethod();
02916       break;
02917         
02918     case OMF_init:
02919     case OMF_autorelease:
02920     case OMF_retain:
02921     case OMF_self:
02922       InferRelatedResultType = ObjCMethod->isInstanceMethod();
02923       break;
02924     }
02925     
02926     if (InferRelatedResultType)
02927       ObjCMethod->SetRelatedResultType();
02928   }
02929     
02930   return ObjCMethod;
02931 }
02932 
02933 bool Sema::CheckObjCDeclScope(Decl *D) {
02934   // Following is also an error. But it is caused by a missing @end
02935   // and diagnostic is issued elsewhere.
02936   if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
02937     return false;
02938 
02939   // If we switched context to translation unit while we are still lexically in
02940   // an objc container, it means the parser missed emitting an error.
02941   if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
02942     return false;
02943   
02944   Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
02945   D->setInvalidDecl();
02946 
02947   return true;
02948 }
02949 
02950 /// Called whenever @defs(ClassName) is encountered in the source.  Inserts the
02951 /// instance variables of ClassName into Decls.
02952 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
02953                      IdentifierInfo *ClassName,
02954                      SmallVectorImpl<Decl*> &Decls) {
02955   // Check that ClassName is a valid class
02956   ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
02957   if (!Class) {
02958     Diag(DeclStart, diag::err_undef_interface) << ClassName;
02959     return;
02960   }
02961   if (LangOpts.ObjCNonFragileABI) {
02962     Diag(DeclStart, diag::err_atdef_nonfragile_interface);
02963     return;
02964   }
02965 
02966   // Collect the instance variables
02967   SmallVector<const ObjCIvarDecl*, 32> Ivars;
02968   Context.DeepCollectObjCIvars(Class, true, Ivars);
02969   // For each ivar, create a fresh ObjCAtDefsFieldDecl.
02970   for (unsigned i = 0; i < Ivars.size(); i++) {
02971     const FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
02972     RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
02973     Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
02974                                            /*FIXME: StartL=*/ID->getLocation(),
02975                                            ID->getLocation(),
02976                                            ID->getIdentifier(), ID->getType(),
02977                                            ID->getBitWidth());
02978     Decls.push_back(FD);
02979   }
02980 
02981   // Introduce all of these fields into the appropriate scope.
02982   for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
02983        D != Decls.end(); ++D) {
02984     FieldDecl *FD = cast<FieldDecl>(*D);
02985     if (getLangOpts().CPlusPlus)
02986       PushOnScopeChains(cast<FieldDecl>(FD), S);
02987     else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
02988       Record->addDecl(FD);
02989   }
02990 }
02991 
02992 /// \brief Build a type-check a new Objective-C exception variable declaration.
02993 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
02994                                       SourceLocation StartLoc,
02995                                       SourceLocation IdLoc,
02996                                       IdentifierInfo *Id,
02997                                       bool Invalid) {
02998   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 
02999   // duration shall not be qualified by an address-space qualifier."
03000   // Since all parameters have automatic store duration, they can not have
03001   // an address space.
03002   if (T.getAddressSpace() != 0) {
03003     Diag(IdLoc, diag::err_arg_with_address_space);
03004     Invalid = true;
03005   }
03006   
03007   // An @catch parameter must be an unqualified object pointer type;
03008   // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
03009   if (Invalid) {
03010     // Don't do any further checking.
03011   } else if (T->isDependentType()) {
03012     // Okay: we don't know what this type will instantiate to.
03013   } else if (!T->isObjCObjectPointerType()) {
03014     Invalid = true;
03015     Diag(IdLoc ,diag::err_catch_param_not_objc_type);
03016   } else if (T->isObjCQualifiedIdType()) {
03017     Invalid = true;
03018     Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
03019   }
03020   
03021   VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
03022                                  T, TInfo, SC_None, SC_None);
03023   New->setExceptionVariable(true);
03024   
03025   // In ARC, infer 'retaining' for variables of retainable type.
03026   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
03027     Invalid = true;
03028 
03029   if (Invalid)
03030     New->setInvalidDecl();
03031   return New;
03032 }
03033 
03034 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
03035   const DeclSpec &DS = D.getDeclSpec();
03036   
03037   // We allow the "register" storage class on exception variables because
03038   // GCC did, but we drop it completely. Any other storage class is an error.
03039   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
03040     Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
03041       << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
03042   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
03043     Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
03044       << DS.getStorageClassSpec();
03045   }  
03046   if (D.getDeclSpec().isThreadSpecified())
03047     Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
03048   D.getMutableDeclSpec().ClearStorageClassSpecs();
03049 
03050   DiagnoseFunctionSpecifiers(D);
03051   
03052   // Check that there are no default arguments inside the type of this
03053   // exception object (C++ only).
03054   if (getLangOpts().CPlusPlus)
03055     CheckExtraCXXDefaultArguments(D);
03056   
03057   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
03058   QualType ExceptionType = TInfo->getType();
03059 
03060   VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
03061                                         D.getSourceRange().getBegin(),
03062                                         D.getIdentifierLoc(),
03063                                         D.getIdentifier(),
03064                                         D.isInvalidType());
03065   
03066   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
03067   if (D.getCXXScopeSpec().isSet()) {
03068     Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
03069       << D.getCXXScopeSpec().getRange();
03070     New->setInvalidDecl();
03071   }
03072   
03073   // Add the parameter declaration into this scope.
03074   S->AddDecl(New);
03075   if (D.getIdentifier())
03076     IdResolver.AddDecl(New);
03077   
03078   ProcessDeclAttributes(S, New, D);
03079   
03080   if (New->hasAttr<BlocksAttr>())
03081     Diag(New->getLocation(), diag::err_block_on_nonlocal);
03082   return New;
03083 }
03084 
03085 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
03086 /// initialization.
03087 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
03088                                 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
03089   for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv; 
03090        Iv= Iv->getNextIvar()) {
03091     QualType QT = Context.getBaseElementType(Iv->getType());
03092     if (QT->isRecordType())
03093       Ivars.push_back(Iv);
03094   }
03095 }
03096 
03097 void Sema::DiagnoseUseOfUnimplementedSelectors() {
03098   // Load referenced selectors from the external source.
03099   if (ExternalSource) {
03100     SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
03101     ExternalSource->ReadReferencedSelectors(Sels);
03102     for (unsigned I = 0, N = Sels.size(); I != N; ++I)
03103       ReferencedSelectors[Sels[I].first] = Sels[I].second;
03104   }
03105   
03106   // Warning will be issued only when selector table is
03107   // generated (which means there is at lease one implementation
03108   // in the TU). This is to match gcc's behavior.
03109   if (ReferencedSelectors.empty() || 
03110       !Context.AnyObjCImplementation())
03111     return;
03112   for (llvm::DenseMap<Selector, SourceLocation>::iterator S = 
03113         ReferencedSelectors.begin(),
03114        E = ReferencedSelectors.end(); S != E; ++S) {
03115     Selector Sel = (*S).first;
03116     if (!LookupImplementedMethodInGlobalPool(Sel))
03117       Diag((*S).second, diag::warn_unimplemented_selector) << Sel;
03118   }
03119   return;
03120 }