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