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