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