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