]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaDeclObjC.cpp
Upgrade our copy of llvm/clang to r132879, from upstream's trunk.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Sema / SemaDeclObjC.cpp
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/Sema/Lookup.h"
16 #include "clang/Sema/ExternalSemaSource.h"
17 #include "clang/Sema/Scope.h"
18 #include "clang/Sema/ScopeInfo.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/Sema/DeclSpec.h"
23 #include "llvm/ADT/DenseSet.h"
24
25 using namespace clang;
26
27 bool Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, 
28                                    const ObjCMethodDecl *Overridden,
29                                    bool IsImplementation) {
30   if (Overridden->hasRelatedResultType() && 
31       !NewMethod->hasRelatedResultType()) {
32     // This can only happen when the method follows a naming convention that
33     // implies a related result type, and the original (overridden) method has
34     // a suitable return type, but the new (overriding) method does not have
35     // a suitable return type.
36     QualType ResultType = NewMethod->getResultType();
37     SourceRange ResultTypeRange;
38     if (const TypeSourceInfo *ResultTypeInfo 
39         = NewMethod->getResultTypeSourceInfo())
40       ResultTypeRange = ResultTypeInfo->getTypeLoc().getSourceRange();
41     
42     // Figure out which class this method is part of, if any.
43     ObjCInterfaceDecl *CurrentClass 
44       = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
45     if (!CurrentClass) {
46       DeclContext *DC = NewMethod->getDeclContext();
47       if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
48         CurrentClass = Cat->getClassInterface();
49       else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
50         CurrentClass = Impl->getClassInterface();
51       else if (ObjCCategoryImplDecl *CatImpl
52                = dyn_cast<ObjCCategoryImplDecl>(DC))
53         CurrentClass = CatImpl->getClassInterface();
54     }
55     
56     if (CurrentClass) {
57       Diag(NewMethod->getLocation(), 
58            diag::warn_related_result_type_compatibility_class)
59         << Context.getObjCInterfaceType(CurrentClass)
60         << ResultType
61         << ResultTypeRange;
62     } else {
63       Diag(NewMethod->getLocation(), 
64            diag::warn_related_result_type_compatibility_protocol)
65         << ResultType
66         << ResultTypeRange;
67     }
68     
69     Diag(Overridden->getLocation(), diag::note_related_result_type_overridden)
70       << Overridden->getMethodFamily();
71   }
72   
73   return false;
74 }
75
76
77 static bool CheckObjCMethodOverrides(Sema &S, ObjCMethodDecl *NewMethod,
78                                      DeclContext *DC, 
79                                      bool SkipCurrent = true) {
80   if (!DC)
81     return false;
82   
83   if (!SkipCurrent) {
84     // Look for this method. If we find it, we're done.
85     Selector Sel = NewMethod->getSelector();
86     bool IsInstance = NewMethod->isInstanceMethod();
87     DeclContext::lookup_const_iterator Meth, MethEnd;
88     for (llvm::tie(Meth, MethEnd) = DC->lookup(Sel); Meth != MethEnd; ++Meth) {
89       ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(*Meth);
90       if (MD && MD->isInstanceMethod() == IsInstance)
91         return S.CheckObjCMethodOverride(NewMethod, MD, false);
92     }
93   }
94   
95   if (ObjCInterfaceDecl *Class = llvm::dyn_cast<ObjCInterfaceDecl>(DC)) {
96     // Look through categories.
97     for (ObjCCategoryDecl *Category = Class->getCategoryList();
98          Category; Category = Category->getNextClassCategory()) {
99       if (CheckObjCMethodOverrides(S, NewMethod, Category, false))
100         return true;
101     }
102     
103     // Look through protocols.
104     for (ObjCList<ObjCProtocolDecl>::iterator I = Class->protocol_begin(),
105          IEnd = Class->protocol_end();
106          I != IEnd; ++I)
107       if (CheckObjCMethodOverrides(S, NewMethod, *I, false))
108         return true;
109     
110     // Look in our superclass.
111     return CheckObjCMethodOverrides(S, NewMethod, Class->getSuperClass(), 
112                                     false);
113   }
114   
115   if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(DC)) {
116     // Look through protocols.
117     for (ObjCList<ObjCProtocolDecl>::iterator I = Category->protocol_begin(),
118          IEnd = Category->protocol_end();
119          I != IEnd; ++I)
120       if (CheckObjCMethodOverrides(S, NewMethod, *I, false))
121         return true;
122     
123     return false;
124   }
125   
126   if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(DC)) {
127     // Look through protocols.
128     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocol->protocol_begin(),
129          IEnd = Protocol->protocol_end();
130          I != IEnd; ++I)
131       if (CheckObjCMethodOverrides(S, NewMethod, *I, false))
132         return true;
133     
134     return false;
135   }
136   
137   return false;
138 }
139
140 bool Sema::CheckObjCMethodOverrides(ObjCMethodDecl *NewMethod, 
141                                     DeclContext *DC) {
142   if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(DC))
143     return ::CheckObjCMethodOverrides(*this, NewMethod, Class);
144   
145   if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(DC))
146     return ::CheckObjCMethodOverrides(*this, NewMethod, Category);
147   
148   if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(DC))
149     return ::CheckObjCMethodOverrides(*this, NewMethod, Protocol);
150   
151   if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(DC))
152     return ::CheckObjCMethodOverrides(*this, NewMethod, 
153                                       Impl->getClassInterface());
154   
155   if (ObjCCategoryImplDecl *CatImpl = dyn_cast<ObjCCategoryImplDecl>(DC))
156     return ::CheckObjCMethodOverrides(*this, NewMethod, 
157                                       CatImpl->getClassInterface());
158   
159   return ::CheckObjCMethodOverrides(*this, NewMethod, CurContext);
160 }
161
162 static void DiagnoseObjCImplementedDeprecations(Sema &S,
163                                                 NamedDecl *ND,
164                                                 SourceLocation ImplLoc,
165                                                 int select) {
166   if (ND && ND->isDeprecated()) {
167     S.Diag(ImplLoc, diag::warn_deprecated_def) << select;
168     if (select == 0)
169       S.Diag(ND->getLocation(), diag::note_method_declared_at);
170     else
171       S.Diag(ND->getLocation(), diag::note_previous_decl) << "class";
172   }
173 }
174
175 /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
176 /// and user declared, in the method definition's AST.
177 void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
178   assert(getCurMethodDecl() == 0 && "Method parsing confused");
179   ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
180
181   // If we don't have a valid method decl, simply return.
182   if (!MDecl)
183     return;
184
185   // Allow the rest of sema to find private method decl implementations.
186   if (MDecl->isInstanceMethod())
187     AddInstanceMethodToGlobalPool(MDecl, true);
188   else
189     AddFactoryMethodToGlobalPool(MDecl, true);
190   
191   // Allow all of Sema to see that we are entering a method definition.
192   PushDeclContext(FnBodyScope, MDecl);
193   PushFunctionScope();
194   
195   // Create Decl objects for each parameter, entrring them in the scope for
196   // binding to their use.
197
198   // Insert the invisible arguments, self and _cmd!
199   MDecl->createImplicitParams(Context, MDecl->getClassInterface());
200
201   PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
202   PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
203
204   // Introduce all of the other parameters into this scope.
205   for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
206        E = MDecl->param_end(); PI != E; ++PI) {
207     ParmVarDecl *Param = (*PI);
208     if (!Param->isInvalidDecl() &&
209         RequireCompleteType(Param->getLocation(), Param->getType(),
210                             diag::err_typecheck_decl_incomplete_type))
211           Param->setInvalidDecl();
212     if ((*PI)->getIdentifier())
213       PushOnScopeChains(*PI, FnBodyScope);
214   }
215   // Warn on implementating deprecated methods under 
216   // -Wdeprecated-implementations flag.
217   if (ObjCInterfaceDecl *IC = MDecl->getClassInterface())
218     if (ObjCMethodDecl *IMD = 
219           IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod()))
220       DiagnoseObjCImplementedDeprecations(*this, 
221                                           dyn_cast<NamedDecl>(IMD), 
222                                           MDecl->getLocation(), 0);
223 }
224
225 Decl *Sema::
226 ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
227                          IdentifierInfo *ClassName, SourceLocation ClassLoc,
228                          IdentifierInfo *SuperName, SourceLocation SuperLoc,
229                          Decl * const *ProtoRefs, unsigned NumProtoRefs,
230                          const SourceLocation *ProtoLocs, 
231                          SourceLocation EndProtoLoc, AttributeList *AttrList) {
232   assert(ClassName && "Missing class identifier");
233
234   // Check for another declaration kind with the same name.
235   NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
236                                          LookupOrdinaryName, ForRedeclaration);
237
238   if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
239     Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
240     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
241   }
242
243   ObjCInterfaceDecl* IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
244   if (IDecl) {
245     // Class already seen. Is it a forward declaration?
246     if (!IDecl->isForwardDecl()) {
247       IDecl->setInvalidDecl();
248       Diag(AtInterfaceLoc, diag::err_duplicate_class_def)<<IDecl->getDeclName();
249       Diag(IDecl->getLocation(), diag::note_previous_definition);
250
251       // Return the previous class interface.
252       // FIXME: don't leak the objects passed in!
253       return IDecl;
254     } else {
255       IDecl->setLocation(AtInterfaceLoc);
256       IDecl->setForwardDecl(false);
257       IDecl->setClassLoc(ClassLoc);
258       // If the forward decl was in a PCH, we need to write it again in a
259       // dependent AST file.
260       IDecl->setChangedSinceDeserialization(true);
261       
262       // Since this ObjCInterfaceDecl was created by a forward declaration,
263       // we now add it to the DeclContext since it wasn't added before
264       // (see ActOnForwardClassDeclaration).
265       IDecl->setLexicalDeclContext(CurContext);
266       CurContext->addDecl(IDecl);
267       
268       if (AttrList)
269         ProcessDeclAttributeList(TUScope, IDecl, AttrList);
270     }
271   } else {
272     IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc,
273                                       ClassName, ClassLoc);
274     if (AttrList)
275       ProcessDeclAttributeList(TUScope, IDecl, AttrList);
276
277     PushOnScopeChains(IDecl, TUScope);
278   }
279
280   if (SuperName) {
281     // Check if a different kind of symbol declared in this scope.
282     PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
283                                 LookupOrdinaryName);
284
285     if (!PrevDecl) {
286       // Try to correct for a typo in the superclass name.
287       LookupResult R(*this, SuperName, SuperLoc, LookupOrdinaryName);
288       if (CorrectTypo(R, TUScope, 0, 0, false, CTC_NoKeywords) &&
289           (PrevDecl = R.getAsSingle<ObjCInterfaceDecl>())) {
290         Diag(SuperLoc, diag::err_undef_superclass_suggest)
291           << SuperName << ClassName << PrevDecl->getDeclName();
292         Diag(PrevDecl->getLocation(), diag::note_previous_decl)
293           << PrevDecl->getDeclName();
294       }
295     }
296
297     if (PrevDecl == IDecl) {
298       Diag(SuperLoc, diag::err_recursive_superclass)
299         << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
300       IDecl->setLocEnd(ClassLoc);
301     } else {
302       ObjCInterfaceDecl *SuperClassDecl =
303                                 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
304
305       // Diagnose classes that inherit from deprecated classes.
306       if (SuperClassDecl)
307         (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
308
309       if (PrevDecl && SuperClassDecl == 0) {
310         // The previous declaration was not a class decl. Check if we have a
311         // typedef. If we do, get the underlying class type.
312         if (const TypedefNameDecl *TDecl =
313               dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
314           QualType T = TDecl->getUnderlyingType();
315           if (T->isObjCObjectType()) {
316             if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface())
317               SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
318           }
319         }
320
321         // This handles the following case:
322         //
323         // typedef int SuperClass;
324         // @interface MyClass : SuperClass {} @end
325         //
326         if (!SuperClassDecl) {
327           Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
328           Diag(PrevDecl->getLocation(), diag::note_previous_definition);
329         }
330       }
331
332       if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
333         if (!SuperClassDecl)
334           Diag(SuperLoc, diag::err_undef_superclass)
335             << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
336         else if (SuperClassDecl->isForwardDecl())
337           Diag(SuperLoc, diag::err_undef_superclass)
338             << SuperClassDecl->getDeclName() << ClassName
339             << SourceRange(AtInterfaceLoc, ClassLoc);
340       }
341       IDecl->setSuperClass(SuperClassDecl);
342       IDecl->setSuperClassLoc(SuperLoc);
343       IDecl->setLocEnd(SuperLoc);
344     }
345   } else { // we have a root class.
346     IDecl->setLocEnd(ClassLoc);
347   }
348
349   // Check then save referenced protocols.
350   if (NumProtoRefs) {
351     IDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
352                            ProtoLocs, Context);
353     IDecl->setLocEnd(EndProtoLoc);
354   }
355
356   CheckObjCDeclScope(IDecl);
357   return IDecl;
358 }
359
360 /// ActOnCompatiblityAlias - this action is called after complete parsing of
361 /// @compatibility_alias declaration. It sets up the alias relationships.
362 Decl *Sema::ActOnCompatiblityAlias(SourceLocation AtLoc,
363                                         IdentifierInfo *AliasName,
364                                         SourceLocation AliasLocation,
365                                         IdentifierInfo *ClassName,
366                                         SourceLocation ClassLocation) {
367   // Look for previous declaration of alias name
368   NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
369                                       LookupOrdinaryName, ForRedeclaration);
370   if (ADecl) {
371     if (isa<ObjCCompatibleAliasDecl>(ADecl))
372       Diag(AliasLocation, diag::warn_previous_alias_decl);
373     else
374       Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
375     Diag(ADecl->getLocation(), diag::note_previous_declaration);
376     return 0;
377   }
378   // Check for class declaration
379   NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
380                                        LookupOrdinaryName, ForRedeclaration);
381   if (const TypedefNameDecl *TDecl =
382         dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
383     QualType T = TDecl->getUnderlyingType();
384     if (T->isObjCObjectType()) {
385       if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
386         ClassName = IDecl->getIdentifier();
387         CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
388                                   LookupOrdinaryName, ForRedeclaration);
389       }
390     }
391   }
392   ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
393   if (CDecl == 0) {
394     Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
395     if (CDeclU)
396       Diag(CDeclU->getLocation(), diag::note_previous_declaration);
397     return 0;
398   }
399
400   // Everything checked out, instantiate a new alias declaration AST.
401   ObjCCompatibleAliasDecl *AliasDecl =
402     ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
403
404   if (!CheckObjCDeclScope(AliasDecl))
405     PushOnScopeChains(AliasDecl, TUScope);
406
407   return AliasDecl;
408 }
409
410 bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
411   IdentifierInfo *PName,
412   SourceLocation &Ploc, SourceLocation PrevLoc,
413   const ObjCList<ObjCProtocolDecl> &PList) {
414   
415   bool res = false;
416   for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
417        E = PList.end(); I != E; ++I) {
418     if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
419                                                  Ploc)) {
420       if (PDecl->getIdentifier() == PName) {
421         Diag(Ploc, diag::err_protocol_has_circular_dependency);
422         Diag(PrevLoc, diag::note_previous_definition);
423         res = true;
424       }
425       if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
426             PDecl->getLocation(), PDecl->getReferencedProtocols()))
427         res = true;
428     }
429   }
430   return res;
431 }
432
433 Decl *
434 Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
435                                   IdentifierInfo *ProtocolName,
436                                   SourceLocation ProtocolLoc,
437                                   Decl * const *ProtoRefs,
438                                   unsigned NumProtoRefs,
439                                   const SourceLocation *ProtoLocs,
440                                   SourceLocation EndProtoLoc,
441                                   AttributeList *AttrList) {
442   bool err = false;
443   // FIXME: Deal with AttrList.
444   assert(ProtocolName && "Missing protocol identifier");
445   ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolName, ProtocolLoc);
446   if (PDecl) {
447     // Protocol already seen. Better be a forward protocol declaration
448     if (!PDecl->isForwardDecl()) {
449       Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
450       Diag(PDecl->getLocation(), diag::note_previous_definition);
451       // Just return the protocol we already had.
452       // FIXME: don't leak the objects passed in!
453       return PDecl;
454     }
455     ObjCList<ObjCProtocolDecl> PList;
456     PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
457     err = CheckForwardProtocolDeclarationForCircularDependency(
458             ProtocolName, ProtocolLoc, PDecl->getLocation(), PList);
459
460     // Make sure the cached decl gets a valid start location.
461     PDecl->setLocation(AtProtoInterfaceLoc);
462     PDecl->setForwardDecl(false);
463     CurContext->addDecl(PDecl);
464     // Repeat in dependent AST files.
465     PDecl->setChangedSinceDeserialization(true);
466   } else {
467     PDecl = ObjCProtocolDecl::Create(Context, CurContext,
468                                      AtProtoInterfaceLoc,ProtocolName);
469     PushOnScopeChains(PDecl, TUScope);
470     PDecl->setForwardDecl(false);
471   }
472   if (AttrList)
473     ProcessDeclAttributeList(TUScope, PDecl, AttrList);
474   if (!err && NumProtoRefs ) {
475     /// Check then save referenced protocols.
476     PDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
477                            ProtoLocs, Context);
478     PDecl->setLocEnd(EndProtoLoc);
479   }
480
481   CheckObjCDeclScope(PDecl);
482   return PDecl;
483 }
484
485 /// FindProtocolDeclaration - This routine looks up protocols and
486 /// issues an error if they are not declared. It returns list of
487 /// protocol declarations in its 'Protocols' argument.
488 void
489 Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
490                               const IdentifierLocPair *ProtocolId,
491                               unsigned NumProtocols,
492                               llvm::SmallVectorImpl<Decl *> &Protocols) {
493   for (unsigned i = 0; i != NumProtocols; ++i) {
494     ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first,
495                                              ProtocolId[i].second);
496     if (!PDecl) {
497       LookupResult R(*this, ProtocolId[i].first, ProtocolId[i].second,
498                      LookupObjCProtocolName);
499       if (CorrectTypo(R, TUScope, 0, 0, false, CTC_NoKeywords) &&
500           (PDecl = R.getAsSingle<ObjCProtocolDecl>())) {
501         Diag(ProtocolId[i].second, diag::err_undeclared_protocol_suggest)
502           << ProtocolId[i].first << R.getLookupName();
503         Diag(PDecl->getLocation(), diag::note_previous_decl)
504           << PDecl->getDeclName();
505       }
506     }
507
508     if (!PDecl) {
509       Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
510         << ProtocolId[i].first;
511       continue;
512     }
513
514     (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
515
516     // If this is a forward declaration and we are supposed to warn in this
517     // case, do it.
518     if (WarnOnDeclarations && PDecl->isForwardDecl())
519       Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
520         << ProtocolId[i].first;
521     Protocols.push_back(PDecl);
522   }
523 }
524
525 /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
526 /// a class method in its extension.
527 ///
528 void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
529                                             ObjCInterfaceDecl *ID) {
530   if (!ID)
531     return;  // Possibly due to previous error
532
533   llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
534   for (ObjCInterfaceDecl::method_iterator i = ID->meth_begin(),
535        e =  ID->meth_end(); i != e; ++i) {
536     ObjCMethodDecl *MD = *i;
537     MethodMap[MD->getSelector()] = MD;
538   }
539
540   if (MethodMap.empty())
541     return;
542   for (ObjCCategoryDecl::method_iterator i = CAT->meth_begin(),
543        e =  CAT->meth_end(); i != e; ++i) {
544     ObjCMethodDecl *Method = *i;
545     const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
546     if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
547       Diag(Method->getLocation(), diag::err_duplicate_method_decl)
548             << Method->getDeclName();
549       Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
550     }
551   }
552 }
553
554 /// ActOnForwardProtocolDeclaration - Handle @protocol foo;
555 Decl *
556 Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
557                                       const IdentifierLocPair *IdentList,
558                                       unsigned NumElts,
559                                       AttributeList *attrList) {
560   llvm::SmallVector<ObjCProtocolDecl*, 32> Protocols;
561   llvm::SmallVector<SourceLocation, 8> ProtoLocs;
562
563   for (unsigned i = 0; i != NumElts; ++i) {
564     IdentifierInfo *Ident = IdentList[i].first;
565     ObjCProtocolDecl *PDecl = LookupProtocol(Ident, IdentList[i].second);
566     bool isNew = false;
567     if (PDecl == 0) { // Not already seen?
568       PDecl = ObjCProtocolDecl::Create(Context, CurContext,
569                                        IdentList[i].second, Ident);
570       PushOnScopeChains(PDecl, TUScope, false);
571       isNew = true;
572     }
573     if (attrList) {
574       ProcessDeclAttributeList(TUScope, PDecl, attrList);
575       if (!isNew)
576         PDecl->setChangedSinceDeserialization(true);
577     }
578     Protocols.push_back(PDecl);
579     ProtoLocs.push_back(IdentList[i].second);
580   }
581
582   ObjCForwardProtocolDecl *PDecl =
583     ObjCForwardProtocolDecl::Create(Context, CurContext, AtProtocolLoc,
584                                     Protocols.data(), Protocols.size(),
585                                     ProtoLocs.data());
586   CurContext->addDecl(PDecl);
587   CheckObjCDeclScope(PDecl);
588   return PDecl;
589 }
590
591 Decl *Sema::
592 ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
593                             IdentifierInfo *ClassName, SourceLocation ClassLoc,
594                             IdentifierInfo *CategoryName,
595                             SourceLocation CategoryLoc,
596                             Decl * const *ProtoRefs,
597                             unsigned NumProtoRefs,
598                             const SourceLocation *ProtoLocs,
599                             SourceLocation EndProtoLoc) {
600   ObjCCategoryDecl *CDecl;
601   ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
602
603   /// Check that class of this category is already completely declared.
604   if (!IDecl || IDecl->isForwardDecl()) {
605     // Create an invalid ObjCCategoryDecl to serve as context for
606     // the enclosing method declarations.  We mark the decl invalid
607     // to make it clear that this isn't a valid AST.
608     CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
609                                      ClassLoc, CategoryLoc, CategoryName);
610     CDecl->setInvalidDecl();
611     Diag(ClassLoc, diag::err_undef_interface) << ClassName;
612     return CDecl;
613   }
614
615   if (!CategoryName && IDecl->getImplementation()) {
616     Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
617     Diag(IDecl->getImplementation()->getLocation(), 
618           diag::note_implementation_declared);
619   }
620
621   CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
622                                    ClassLoc, CategoryLoc, CategoryName);
623   // FIXME: PushOnScopeChains?
624   CurContext->addDecl(CDecl);
625
626   CDecl->setClassInterface(IDecl);
627   // Insert class extension to the list of class's categories.
628   if (!CategoryName)
629     CDecl->insertNextClassCategory();
630
631   // If the interface is deprecated, warn about it.
632   (void)DiagnoseUseOfDecl(IDecl, ClassLoc);
633
634   if (CategoryName) {
635     /// Check for duplicate interface declaration for this category
636     ObjCCategoryDecl *CDeclChain;
637     for (CDeclChain = IDecl->getCategoryList(); CDeclChain;
638          CDeclChain = CDeclChain->getNextClassCategory()) {
639       if (CDeclChain->getIdentifier() == CategoryName) {
640         // Class extensions can be declared multiple times.
641         Diag(CategoryLoc, diag::warn_dup_category_def)
642           << ClassName << CategoryName;
643         Diag(CDeclChain->getLocation(), diag::note_previous_definition);
644         break;
645       }
646     }
647     if (!CDeclChain)
648       CDecl->insertNextClassCategory();
649   }
650
651   if (NumProtoRefs) {
652     CDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs, 
653                            ProtoLocs, Context);
654     // Protocols in the class extension belong to the class.
655     if (CDecl->IsClassExtension())
656      IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl**)ProtoRefs, 
657                                             NumProtoRefs, Context); 
658   }
659
660   CheckObjCDeclScope(CDecl);
661   return CDecl;
662 }
663
664 /// ActOnStartCategoryImplementation - Perform semantic checks on the
665 /// category implementation declaration and build an ObjCCategoryImplDecl
666 /// object.
667 Decl *Sema::ActOnStartCategoryImplementation(
668                       SourceLocation AtCatImplLoc,
669                       IdentifierInfo *ClassName, SourceLocation ClassLoc,
670                       IdentifierInfo *CatName, SourceLocation CatLoc) {
671   ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
672   ObjCCategoryDecl *CatIDecl = 0;
673   if (IDecl) {
674     CatIDecl = IDecl->FindCategoryDeclaration(CatName);
675     if (!CatIDecl) {
676       // Category @implementation with no corresponding @interface.
677       // Create and install one.
678       CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, SourceLocation(),
679                                           SourceLocation(), SourceLocation(),
680                                           CatName);
681       CatIDecl->setClassInterface(IDecl);
682       CatIDecl->insertNextClassCategory();
683     }
684   }
685
686   ObjCCategoryImplDecl *CDecl =
687     ObjCCategoryImplDecl::Create(Context, CurContext, AtCatImplLoc, CatName,
688                                  IDecl);
689   /// Check that class of this category is already completely declared.
690   if (!IDecl || IDecl->isForwardDecl())
691     Diag(ClassLoc, diag::err_undef_interface) << ClassName;
692
693   // FIXME: PushOnScopeChains?
694   CurContext->addDecl(CDecl);
695
696   /// Check that CatName, category name, is not used in another implementation.
697   if (CatIDecl) {
698     if (CatIDecl->getImplementation()) {
699       Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
700         << CatName;
701       Diag(CatIDecl->getImplementation()->getLocation(),
702            diag::note_previous_definition);
703     } else {
704       CatIDecl->setImplementation(CDecl);
705       // Warn on implementating category of deprecated class under 
706       // -Wdeprecated-implementations flag.
707       DiagnoseObjCImplementedDeprecations(*this, 
708                                           dyn_cast<NamedDecl>(IDecl), 
709                                           CDecl->getLocation(), 2);
710     }
711   }
712
713   CheckObjCDeclScope(CDecl);
714   return CDecl;
715 }
716
717 Decl *Sema::ActOnStartClassImplementation(
718                       SourceLocation AtClassImplLoc,
719                       IdentifierInfo *ClassName, SourceLocation ClassLoc,
720                       IdentifierInfo *SuperClassname,
721                       SourceLocation SuperClassLoc) {
722   ObjCInterfaceDecl* IDecl = 0;
723   // Check for another declaration kind with the same name.
724   NamedDecl *PrevDecl
725     = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
726                        ForRedeclaration);
727   if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
728     Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
729     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
730   } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
731     // If this is a forward declaration of an interface, warn.
732     if (IDecl->isForwardDecl()) {
733       Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
734       IDecl = 0;
735     }
736   } else {
737     // We did not find anything with the name ClassName; try to correct for 
738     // typos in the class name.
739     LookupResult R(*this, ClassName, ClassLoc, LookupOrdinaryName);
740     if (CorrectTypo(R, TUScope, 0, 0, false, CTC_NoKeywords) &&
741         (IDecl = R.getAsSingle<ObjCInterfaceDecl>())) {
742       // Suggest the (potentially) correct interface name. However, put the
743       // fix-it hint itself in a separate note, since changing the name in 
744       // the warning would make the fix-it change semantics.However, don't
745       // provide a code-modification hint or use the typo name for recovery,
746       // because this is just a warning. The program may actually be correct.
747       Diag(ClassLoc, diag::warn_undef_interface_suggest)
748         << ClassName << R.getLookupName();
749       Diag(IDecl->getLocation(), diag::note_previous_decl)
750         << R.getLookupName()
751         << FixItHint::CreateReplacement(ClassLoc,
752                                         R.getLookupName().getAsString());
753       IDecl = 0;
754     } else {
755       Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
756     }
757   }
758
759   // Check that super class name is valid class name
760   ObjCInterfaceDecl* SDecl = 0;
761   if (SuperClassname) {
762     // Check if a different kind of symbol declared in this scope.
763     PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
764                                 LookupOrdinaryName);
765     if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
766       Diag(SuperClassLoc, diag::err_redefinition_different_kind)
767         << SuperClassname;
768       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
769     } else {
770       SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
771       if (!SDecl)
772         Diag(SuperClassLoc, diag::err_undef_superclass)
773           << SuperClassname << ClassName;
774       else if (IDecl && IDecl->getSuperClass() != SDecl) {
775         // This implementation and its interface do not have the same
776         // super class.
777         Diag(SuperClassLoc, diag::err_conflicting_super_class)
778           << SDecl->getDeclName();
779         Diag(SDecl->getLocation(), diag::note_previous_definition);
780       }
781     }
782   }
783
784   if (!IDecl) {
785     // Legacy case of @implementation with no corresponding @interface.
786     // Build, chain & install the interface decl into the identifier.
787
788     // FIXME: Do we support attributes on the @implementation? If so we should
789     // copy them over.
790     IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
791                                       ClassName, ClassLoc, false, true);
792     IDecl->setSuperClass(SDecl);
793     IDecl->setLocEnd(ClassLoc);
794
795     PushOnScopeChains(IDecl, TUScope);
796   } else {
797     // Mark the interface as being completed, even if it was just as
798     //   @class ....;
799     // declaration; the user cannot reopen it.
800     IDecl->setForwardDecl(false);
801   }
802
803   ObjCImplementationDecl* IMPDecl =
804     ObjCImplementationDecl::Create(Context, CurContext, AtClassImplLoc,
805                                    IDecl, SDecl);
806
807   if (CheckObjCDeclScope(IMPDecl))
808     return IMPDecl;
809
810   // Check that there is no duplicate implementation of this class.
811   if (IDecl->getImplementation()) {
812     // FIXME: Don't leak everything!
813     Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
814     Diag(IDecl->getImplementation()->getLocation(),
815          diag::note_previous_definition);
816   } else { // add it to the list.
817     IDecl->setImplementation(IMPDecl);
818     PushOnScopeChains(IMPDecl, TUScope);
819     // Warn on implementating deprecated class under 
820     // -Wdeprecated-implementations flag.
821     DiagnoseObjCImplementedDeprecations(*this, 
822                                         dyn_cast<NamedDecl>(IDecl), 
823                                         IMPDecl->getLocation(), 1);
824   }
825   return IMPDecl;
826 }
827
828 void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
829                                     ObjCIvarDecl **ivars, unsigned numIvars,
830                                     SourceLocation RBrace) {
831   assert(ImpDecl && "missing implementation decl");
832   ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
833   if (!IDecl)
834     return;
835   /// Check case of non-existing @interface decl.
836   /// (legacy objective-c @implementation decl without an @interface decl).
837   /// Add implementations's ivar to the synthesize class's ivar list.
838   if (IDecl->isImplicitInterfaceDecl()) {
839     IDecl->setLocEnd(RBrace);
840     // Add ivar's to class's DeclContext.
841     for (unsigned i = 0, e = numIvars; i != e; ++i) {
842       ivars[i]->setLexicalDeclContext(ImpDecl);
843       IDecl->makeDeclVisibleInContext(ivars[i], false);
844       ImpDecl->addDecl(ivars[i]);
845     }
846     
847     return;
848   }
849   // If implementation has empty ivar list, just return.
850   if (numIvars == 0)
851     return;
852
853   assert(ivars && "missing @implementation ivars");
854   if (LangOpts.ObjCNonFragileABI2) {
855     if (ImpDecl->getSuperClass())
856       Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
857     for (unsigned i = 0; i < numIvars; i++) {
858       ObjCIvarDecl* ImplIvar = ivars[i];
859       if (const ObjCIvarDecl *ClsIvar = 
860             IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
861         Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration); 
862         Diag(ClsIvar->getLocation(), diag::note_previous_definition);
863         continue;
864       }
865       // Instance ivar to Implementation's DeclContext.
866       ImplIvar->setLexicalDeclContext(ImpDecl);
867       IDecl->makeDeclVisibleInContext(ImplIvar, false);
868       ImpDecl->addDecl(ImplIvar);
869     }
870     return;
871   }
872   // Check interface's Ivar list against those in the implementation.
873   // names and types must match.
874   //
875   unsigned j = 0;
876   ObjCInterfaceDecl::ivar_iterator
877     IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
878   for (; numIvars > 0 && IVI != IVE; ++IVI) {
879     ObjCIvarDecl* ImplIvar = ivars[j++];
880     ObjCIvarDecl* ClsIvar = *IVI;
881     assert (ImplIvar && "missing implementation ivar");
882     assert (ClsIvar && "missing class ivar");
883
884     // First, make sure the types match.
885     if (Context.getCanonicalType(ImplIvar->getType()) !=
886         Context.getCanonicalType(ClsIvar->getType())) {
887       Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
888         << ImplIvar->getIdentifier()
889         << ImplIvar->getType() << ClsIvar->getType();
890       Diag(ClsIvar->getLocation(), diag::note_previous_definition);
891     } else if (ImplIvar->isBitField() && ClsIvar->isBitField()) {
892       Expr *ImplBitWidth = ImplIvar->getBitWidth();
893       Expr *ClsBitWidth = ClsIvar->getBitWidth();
894       if (ImplBitWidth->EvaluateAsInt(Context).getZExtValue() !=
895           ClsBitWidth->EvaluateAsInt(Context).getZExtValue()) {
896         Diag(ImplBitWidth->getLocStart(), diag::err_conflicting_ivar_bitwidth)
897           << ImplIvar->getIdentifier();
898         Diag(ClsBitWidth->getLocStart(), diag::note_previous_definition);
899       }
900     }
901     // Make sure the names are identical.
902     if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
903       Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
904         << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
905       Diag(ClsIvar->getLocation(), diag::note_previous_definition);
906     }
907     --numIvars;
908   }
909
910   if (numIvars > 0)
911     Diag(ivars[j]->getLocation(), diag::err_inconsistant_ivar_count);
912   else if (IVI != IVE)
913     Diag((*IVI)->getLocation(), diag::err_inconsistant_ivar_count);
914 }
915
916 void Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
917                                bool &IncompleteImpl, unsigned DiagID) {
918   if (!IncompleteImpl) {
919     Diag(ImpLoc, diag::warn_incomplete_impl);
920     IncompleteImpl = true;
921   }
922   if (DiagID == diag::warn_unimplemented_protocol_method)
923     Diag(ImpLoc, DiagID) << method->getDeclName();
924   else
925     Diag(method->getLocation(), DiagID) << method->getDeclName();
926 }
927
928 /// Determines if type B can be substituted for type A.  Returns true if we can
929 /// guarantee that anything that the user will do to an object of type A can 
930 /// also be done to an object of type B.  This is trivially true if the two 
931 /// types are the same, or if B is a subclass of A.  It becomes more complex
932 /// in cases where protocols are involved.
933 ///
934 /// Object types in Objective-C describe the minimum requirements for an
935 /// object, rather than providing a complete description of a type.  For
936 /// example, if A is a subclass of B, then B* may refer to an instance of A.
937 /// The principle of substitutability means that we may use an instance of A
938 /// anywhere that we may use an instance of B - it will implement all of the
939 /// ivars of B and all of the methods of B.  
940 ///
941 /// This substitutability is important when type checking methods, because 
942 /// the implementation may have stricter type definitions than the interface.
943 /// The interface specifies minimum requirements, but the implementation may
944 /// have more accurate ones.  For example, a method may privately accept 
945 /// instances of B, but only publish that it accepts instances of A.  Any
946 /// object passed to it will be type checked against B, and so will implicitly
947 /// by a valid A*.  Similarly, a method may return a subclass of the class that
948 /// it is declared as returning.
949 ///
950 /// This is most important when considering subclassing.  A method in a
951 /// subclass must accept any object as an argument that its superclass's
952 /// implementation accepts.  It may, however, accept a more general type
953 /// without breaking substitutability (i.e. you can still use the subclass
954 /// anywhere that you can use the superclass, but not vice versa).  The
955 /// converse requirement applies to return types: the return type for a
956 /// subclass method must be a valid object of the kind that the superclass
957 /// advertises, but it may be specified more accurately.  This avoids the need
958 /// for explicit down-casting by callers.
959 ///
960 /// Note: This is a stricter requirement than for assignment.  
961 static bool isObjCTypeSubstitutable(ASTContext &Context,
962                                     const ObjCObjectPointerType *A,
963                                     const ObjCObjectPointerType *B,
964                                     bool rejectId) {
965   // Reject a protocol-unqualified id.
966   if (rejectId && B->isObjCIdType()) return false;
967
968   // If B is a qualified id, then A must also be a qualified id and it must
969   // implement all of the protocols in B.  It may not be a qualified class.
970   // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
971   // stricter definition so it is not substitutable for id<A>.
972   if (B->isObjCQualifiedIdType()) {
973     return A->isObjCQualifiedIdType() &&
974            Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
975                                                      QualType(B,0),
976                                                      false);
977   }
978
979   /*
980   // id is a special type that bypasses type checking completely.  We want a
981   // warning when it is used in one place but not another.
982   if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
983
984
985   // If B is a qualified id, then A must also be a qualified id (which it isn't
986   // if we've got this far)
987   if (B->isObjCQualifiedIdType()) return false;
988   */
989
990   // Now we know that A and B are (potentially-qualified) class types.  The
991   // normal rules for assignment apply.
992   return Context.canAssignObjCInterfaces(A, B);
993 }
994
995 static SourceRange getTypeRange(TypeSourceInfo *TSI) {
996   return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
997 }
998
999 static void CheckMethodOverrideReturn(Sema &S,
1000                                       ObjCMethodDecl *MethodImpl,
1001                                       ObjCMethodDecl *MethodDecl,
1002                                       bool IsProtocolMethodDecl) {
1003   if (IsProtocolMethodDecl &&
1004       (MethodDecl->getObjCDeclQualifier() !=
1005        MethodImpl->getObjCDeclQualifier())) {
1006     S.Diag(MethodImpl->getLocation(), 
1007            diag::warn_conflicting_ret_type_modifiers)
1008         << MethodImpl->getDeclName()
1009         << getTypeRange(MethodImpl->getResultTypeSourceInfo());
1010     S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
1011         << getTypeRange(MethodDecl->getResultTypeSourceInfo());
1012   }
1013   
1014   if (S.Context.hasSameUnqualifiedType(MethodImpl->getResultType(),
1015                                        MethodDecl->getResultType()))
1016     return;
1017
1018   unsigned DiagID = diag::warn_conflicting_ret_types;
1019
1020   // Mismatches between ObjC pointers go into a different warning
1021   // category, and sometimes they're even completely whitelisted.
1022   if (const ObjCObjectPointerType *ImplPtrTy =
1023         MethodImpl->getResultType()->getAs<ObjCObjectPointerType>()) {
1024     if (const ObjCObjectPointerType *IfacePtrTy =
1025           MethodDecl->getResultType()->getAs<ObjCObjectPointerType>()) {
1026       // Allow non-matching return types as long as they don't violate
1027       // the principle of substitutability.  Specifically, we permit
1028       // return types that are subclasses of the declared return type,
1029       // or that are more-qualified versions of the declared type.
1030       if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
1031         return;
1032
1033       DiagID = diag::warn_non_covariant_ret_types;
1034     }
1035   }
1036
1037   S.Diag(MethodImpl->getLocation(), DiagID)
1038     << MethodImpl->getDeclName()
1039     << MethodDecl->getResultType()
1040     << MethodImpl->getResultType()
1041     << getTypeRange(MethodImpl->getResultTypeSourceInfo());
1042   S.Diag(MethodDecl->getLocation(), diag::note_previous_definition)
1043     << getTypeRange(MethodDecl->getResultTypeSourceInfo());
1044 }
1045
1046 static void CheckMethodOverrideParam(Sema &S,
1047                                      ObjCMethodDecl *MethodImpl,
1048                                      ObjCMethodDecl *MethodDecl,
1049                                      ParmVarDecl *ImplVar,
1050                                      ParmVarDecl *IfaceVar,
1051                                      bool IsProtocolMethodDecl) {
1052   if (IsProtocolMethodDecl &&
1053       (ImplVar->getObjCDeclQualifier() !=
1054        IfaceVar->getObjCDeclQualifier())) {
1055     S.Diag(ImplVar->getLocation(), 
1056            diag::warn_conflicting_param_modifiers)
1057         << getTypeRange(ImplVar->getTypeSourceInfo())
1058         << MethodImpl->getDeclName();
1059     S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
1060         << getTypeRange(IfaceVar->getTypeSourceInfo());   
1061   }
1062       
1063   QualType ImplTy = ImplVar->getType();
1064   QualType IfaceTy = IfaceVar->getType();
1065   
1066   if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
1067     return;
1068
1069   unsigned DiagID = diag::warn_conflicting_param_types;
1070
1071   // Mismatches between ObjC pointers go into a different warning
1072   // category, and sometimes they're even completely whitelisted.
1073   if (const ObjCObjectPointerType *ImplPtrTy =
1074         ImplTy->getAs<ObjCObjectPointerType>()) {
1075     if (const ObjCObjectPointerType *IfacePtrTy =
1076           IfaceTy->getAs<ObjCObjectPointerType>()) {
1077       // Allow non-matching argument types as long as they don't
1078       // violate the principle of substitutability.  Specifically, the
1079       // implementation must accept any objects that the superclass
1080       // accepts, however it may also accept others.
1081       if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
1082         return;
1083
1084       DiagID = diag::warn_non_contravariant_param_types;
1085     }
1086   }
1087
1088   S.Diag(ImplVar->getLocation(), DiagID)
1089     << getTypeRange(ImplVar->getTypeSourceInfo())
1090     << MethodImpl->getDeclName() << IfaceTy << ImplTy;
1091   S.Diag(IfaceVar->getLocation(), diag::note_previous_definition)
1092     << getTypeRange(IfaceVar->getTypeSourceInfo());
1093 }
1094                                      
1095
1096 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
1097                                        ObjCMethodDecl *MethodDecl,
1098                                        bool IsProtocolMethodDecl) {
1099   CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, 
1100                             IsProtocolMethodDecl);
1101
1102   for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
1103        IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end();
1104        IM != EM; ++IM, ++IF)
1105     CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
1106                              IsProtocolMethodDecl);
1107
1108   if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
1109     Diag(ImpMethodDecl->getLocation(), diag::warn_conflicting_variadic);
1110     Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
1111   }
1112 }
1113
1114 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
1115 /// improve the efficiency of selector lookups and type checking by associating
1116 /// with each protocol / interface / category the flattened instance tables. If
1117 /// we used an immutable set to keep the table then it wouldn't add significant
1118 /// memory cost and it would be handy for lookups.
1119
1120 /// CheckProtocolMethodDefs - This routine checks unimplemented methods
1121 /// Declared in protocol, and those referenced by it.
1122 void Sema::CheckProtocolMethodDefs(SourceLocation ImpLoc,
1123                                    ObjCProtocolDecl *PDecl,
1124                                    bool& IncompleteImpl,
1125                                    const llvm::DenseSet<Selector> &InsMap,
1126                                    const llvm::DenseSet<Selector> &ClsMap,
1127                                    ObjCContainerDecl *CDecl) {
1128   ObjCInterfaceDecl *IDecl;
1129   if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl))
1130     IDecl = C->getClassInterface();
1131   else
1132     IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
1133   assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
1134   
1135   ObjCInterfaceDecl *Super = IDecl->getSuperClass();
1136   ObjCInterfaceDecl *NSIDecl = 0;
1137   if (getLangOptions().NeXTRuntime) {
1138     // check to see if class implements forwardInvocation method and objects
1139     // of this class are derived from 'NSProxy' so that to forward requests
1140     // from one object to another.
1141     // Under such conditions, which means that every method possible is
1142     // implemented in the class, we should not issue "Method definition not
1143     // found" warnings.
1144     // FIXME: Use a general GetUnarySelector method for this.
1145     IdentifierInfo* II = &Context.Idents.get("forwardInvocation");
1146     Selector fISelector = Context.Selectors.getSelector(1, &II);
1147     if (InsMap.count(fISelector))
1148       // Is IDecl derived from 'NSProxy'? If so, no instance methods
1149       // need be implemented in the implementation.
1150       NSIDecl = IDecl->lookupInheritedClass(&Context.Idents.get("NSProxy"));
1151   }
1152
1153   // If a method lookup fails locally we still need to look and see if
1154   // the method was implemented by a base class or an inherited
1155   // protocol. This lookup is slow, but occurs rarely in correct code
1156   // and otherwise would terminate in a warning.
1157
1158   // check unimplemented instance methods.
1159   if (!NSIDecl)
1160     for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
1161          E = PDecl->instmeth_end(); I != E; ++I) {
1162       ObjCMethodDecl *method = *I;
1163       if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1164           !method->isSynthesized() && !InsMap.count(method->getSelector()) &&
1165           (!Super ||
1166            !Super->lookupInstanceMethod(method->getSelector()))) {
1167             // Ugly, but necessary. Method declared in protcol might have
1168             // have been synthesized due to a property declared in the class which
1169             // uses the protocol.
1170             ObjCMethodDecl *MethodInClass =
1171             IDecl->lookupInstanceMethod(method->getSelector());
1172             if (!MethodInClass || !MethodInClass->isSynthesized()) {
1173               unsigned DIAG = diag::warn_unimplemented_protocol_method;
1174               if (Diags.getDiagnosticLevel(DIAG, ImpLoc)
1175                       != Diagnostic::Ignored) {
1176                 WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
1177                 Diag(method->getLocation(), diag::note_method_declared_at);
1178                 Diag(CDecl->getLocation(), diag::note_required_for_protocol_at)
1179                   << PDecl->getDeclName();
1180               }
1181             }
1182           }
1183     }
1184   // check unimplemented class methods
1185   for (ObjCProtocolDecl::classmeth_iterator
1186          I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1187        I != E; ++I) {
1188     ObjCMethodDecl *method = *I;
1189     if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1190         !ClsMap.count(method->getSelector()) &&
1191         (!Super || !Super->lookupClassMethod(method->getSelector()))) {
1192       unsigned DIAG = diag::warn_unimplemented_protocol_method;
1193       if (Diags.getDiagnosticLevel(DIAG, ImpLoc) != Diagnostic::Ignored) {
1194         WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
1195         Diag(method->getLocation(), diag::note_method_declared_at);
1196         Diag(IDecl->getLocation(), diag::note_required_for_protocol_at) <<
1197           PDecl->getDeclName();
1198       }
1199     }
1200   }
1201   // Check on this protocols's referenced protocols, recursively.
1202   for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
1203        E = PDecl->protocol_end(); PI != E; ++PI)
1204     CheckProtocolMethodDefs(ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap, IDecl);
1205 }
1206
1207 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
1208 /// or protocol against those declared in their implementations.
1209 ///
1210 void Sema::MatchAllMethodDeclarations(const llvm::DenseSet<Selector> &InsMap,
1211                                       const llvm::DenseSet<Selector> &ClsMap,
1212                                       llvm::DenseSet<Selector> &InsMapSeen,
1213                                       llvm::DenseSet<Selector> &ClsMapSeen,
1214                                       ObjCImplDecl* IMPDecl,
1215                                       ObjCContainerDecl* CDecl,
1216                                       bool &IncompleteImpl,
1217                                       bool ImmediateClass) {
1218   // Check and see if instance methods in class interface have been
1219   // implemented in the implementation class. If so, their types match.
1220   for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(),
1221        E = CDecl->instmeth_end(); I != E; ++I) {
1222     if (InsMapSeen.count((*I)->getSelector()))
1223         continue;
1224     InsMapSeen.insert((*I)->getSelector());
1225     if (!(*I)->isSynthesized() &&
1226         !InsMap.count((*I)->getSelector())) {
1227       if (ImmediateClass)
1228         WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl,
1229                             diag::note_undef_method_impl);
1230       continue;
1231     } else {
1232       ObjCMethodDecl *ImpMethodDecl =
1233       IMPDecl->getInstanceMethod((*I)->getSelector());
1234       ObjCMethodDecl *MethodDecl =
1235       CDecl->getInstanceMethod((*I)->getSelector());
1236       assert(MethodDecl &&
1237              "MethodDecl is null in ImplMethodsVsClassMethods");
1238       // ImpMethodDecl may be null as in a @dynamic property.
1239       if (ImpMethodDecl)
1240         WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl,
1241                                     isa<ObjCProtocolDecl>(CDecl));
1242     }
1243   }
1244
1245   // Check and see if class methods in class interface have been
1246   // implemented in the implementation class. If so, their types match.
1247    for (ObjCInterfaceDecl::classmeth_iterator
1248        I = CDecl->classmeth_begin(), E = CDecl->classmeth_end(); I != E; ++I) {
1249      if (ClsMapSeen.count((*I)->getSelector()))
1250        continue;
1251      ClsMapSeen.insert((*I)->getSelector());
1252     if (!ClsMap.count((*I)->getSelector())) {
1253       if (ImmediateClass)
1254         WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl,
1255                             diag::note_undef_method_impl);
1256     } else {
1257       ObjCMethodDecl *ImpMethodDecl =
1258         IMPDecl->getClassMethod((*I)->getSelector());
1259       ObjCMethodDecl *MethodDecl =
1260         CDecl->getClassMethod((*I)->getSelector());
1261       WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl, 
1262                                   isa<ObjCProtocolDecl>(CDecl));
1263     }
1264   }
1265   
1266   if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
1267     // Also methods in class extensions need be looked at next.
1268     for (const ObjCCategoryDecl *ClsExtDecl = I->getFirstClassExtension(); 
1269          ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension())
1270       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1271                                  IMPDecl,
1272                                  const_cast<ObjCCategoryDecl *>(ClsExtDecl), 
1273                                  IncompleteImpl, false);
1274     
1275     // Check for any implementation of a methods declared in protocol.
1276     for (ObjCInterfaceDecl::all_protocol_iterator
1277           PI = I->all_referenced_protocol_begin(),
1278           E = I->all_referenced_protocol_end(); PI != E; ++PI)
1279       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1280                                  IMPDecl,
1281                                  (*PI), IncompleteImpl, false);
1282     if (I->getSuperClass())
1283       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1284                                  IMPDecl,
1285                                  I->getSuperClass(), IncompleteImpl, false);
1286   }
1287 }
1288
1289 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
1290                                      ObjCContainerDecl* CDecl,
1291                                      bool IncompleteImpl) {
1292   llvm::DenseSet<Selector> InsMap;
1293   // Check and see if instance methods in class interface have been
1294   // implemented in the implementation class.
1295   for (ObjCImplementationDecl::instmeth_iterator
1296          I = IMPDecl->instmeth_begin(), E = IMPDecl->instmeth_end(); I!=E; ++I)
1297     InsMap.insert((*I)->getSelector());
1298
1299   // Check and see if properties declared in the interface have either 1)
1300   // an implementation or 2) there is a @synthesize/@dynamic implementation
1301   // of the property in the @implementation.
1302   if (isa<ObjCInterfaceDecl>(CDecl) &&
1303         !(LangOpts.ObjCDefaultSynthProperties && LangOpts.ObjCNonFragileABI2))
1304     DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap);
1305       
1306   llvm::DenseSet<Selector> ClsMap;
1307   for (ObjCImplementationDecl::classmeth_iterator
1308        I = IMPDecl->classmeth_begin(),
1309        E = IMPDecl->classmeth_end(); I != E; ++I)
1310     ClsMap.insert((*I)->getSelector());
1311
1312   // Check for type conflict of methods declared in a class/protocol and
1313   // its implementation; if any.
1314   llvm::DenseSet<Selector> InsMapSeen, ClsMapSeen;
1315   MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1316                              IMPDecl, CDecl,
1317                              IncompleteImpl, true);
1318
1319   // Check the protocol list for unimplemented methods in the @implementation
1320   // class.
1321   // Check and see if class methods in class interface have been
1322   // implemented in the implementation class.
1323
1324   if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
1325     for (ObjCInterfaceDecl::all_protocol_iterator
1326           PI = I->all_referenced_protocol_begin(),
1327           E = I->all_referenced_protocol_end(); PI != E; ++PI)
1328       CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
1329                               InsMap, ClsMap, I);
1330     // Check class extensions (unnamed categories)
1331     for (const ObjCCategoryDecl *Categories = I->getFirstClassExtension();
1332          Categories; Categories = Categories->getNextClassExtension())
1333       ImplMethodsVsClassMethods(S, IMPDecl, 
1334                                 const_cast<ObjCCategoryDecl*>(Categories), 
1335                                 IncompleteImpl);
1336   } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1337     // For extended class, unimplemented methods in its protocols will
1338     // be reported in the primary class.
1339     if (!C->IsClassExtension()) {
1340       for (ObjCCategoryDecl::protocol_iterator PI = C->protocol_begin(),
1341            E = C->protocol_end(); PI != E; ++PI)
1342         CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
1343                                 InsMap, ClsMap, CDecl);
1344       // Report unimplemented properties in the category as well.
1345       // When reporting on missing setter/getters, do not report when
1346       // setter/getter is implemented in category's primary class 
1347       // implementation.
1348       if (ObjCInterfaceDecl *ID = C->getClassInterface())
1349         if (ObjCImplDecl *IMP = ID->getImplementation()) {
1350           for (ObjCImplementationDecl::instmeth_iterator
1351                I = IMP->instmeth_begin(), E = IMP->instmeth_end(); I!=E; ++I)
1352             InsMap.insert((*I)->getSelector());
1353         }
1354       DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap);      
1355     } 
1356   } else
1357     assert(false && "invalid ObjCContainerDecl type.");
1358 }
1359
1360 /// ActOnForwardClassDeclaration -
1361 Decl *
1362 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
1363                                    IdentifierInfo **IdentList,
1364                                    SourceLocation *IdentLocs,
1365                                    unsigned NumElts) {
1366   llvm::SmallVector<ObjCInterfaceDecl*, 32> Interfaces;
1367
1368   for (unsigned i = 0; i != NumElts; ++i) {
1369     // Check for another declaration kind with the same name.
1370     NamedDecl *PrevDecl
1371       = LookupSingleName(TUScope, IdentList[i], IdentLocs[i], 
1372                          LookupOrdinaryName, ForRedeclaration);
1373     if (PrevDecl && PrevDecl->isTemplateParameter()) {
1374       // Maybe we will complain about the shadowed template parameter.
1375       DiagnoseTemplateParameterShadow(AtClassLoc, PrevDecl);
1376       // Just pretend that we didn't see the previous declaration.
1377       PrevDecl = 0;
1378     }
1379
1380     if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1381       // GCC apparently allows the following idiom:
1382       //
1383       // typedef NSObject < XCElementTogglerP > XCElementToggler;
1384       // @class XCElementToggler;
1385       //
1386       // FIXME: Make an extension?
1387       TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
1388       if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
1389         Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
1390         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1391       } else {
1392         // a forward class declaration matching a typedef name of a class refers
1393         // to the underlying class.
1394         if (const ObjCObjectType *OI =
1395               TDD->getUnderlyingType()->getAs<ObjCObjectType>())
1396           PrevDecl = OI->getInterface();
1397       }
1398     }
1399     ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
1400     if (!IDecl) {  // Not already seen?  Make a forward decl.
1401       IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
1402                                         IdentList[i], IdentLocs[i], true);
1403       
1404       // Push the ObjCInterfaceDecl on the scope chain but do *not* add it to
1405       // the current DeclContext.  This prevents clients that walk DeclContext
1406       // from seeing the imaginary ObjCInterfaceDecl until it is actually
1407       // declared later (if at all).  We also take care to explicitly make
1408       // sure this declaration is visible for name lookup.
1409       PushOnScopeChains(IDecl, TUScope, false);
1410       CurContext->makeDeclVisibleInContext(IDecl, true);
1411     }
1412
1413     Interfaces.push_back(IDecl);
1414   }
1415
1416   assert(Interfaces.size() == NumElts);
1417   ObjCClassDecl *CDecl = ObjCClassDecl::Create(Context, CurContext, AtClassLoc,
1418                                                Interfaces.data(), IdentLocs,
1419                                                Interfaces.size());
1420   CurContext->addDecl(CDecl);
1421   CheckObjCDeclScope(CDecl);
1422   return CDecl;
1423 }
1424
1425
1426 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and
1427 /// returns true, or false, accordingly.
1428 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
1429 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
1430                                       const ObjCMethodDecl *PrevMethod,
1431                                       bool matchBasedOnSizeAndAlignment,
1432                                       bool matchBasedOnStrictEqulity) {
1433   QualType T1 = Context.getCanonicalType(Method->getResultType());
1434   QualType T2 = Context.getCanonicalType(PrevMethod->getResultType());
1435
1436   if (T1 != T2) {
1437     // The result types are different.
1438     if (!matchBasedOnSizeAndAlignment || matchBasedOnStrictEqulity)
1439       return false;
1440     // Incomplete types don't have a size and alignment.
1441     if (T1->isIncompleteType() || T2->isIncompleteType())
1442       return false;
1443     // Check is based on size and alignment.
1444     if (Context.getTypeInfo(T1) != Context.getTypeInfo(T2))
1445       return false;
1446   }
1447
1448   ObjCMethodDecl::param_iterator ParamI = Method->param_begin(),
1449        E = Method->param_end();
1450   ObjCMethodDecl::param_iterator PrevI = PrevMethod->param_begin();
1451
1452   for (; ParamI != E; ++ParamI, ++PrevI) {
1453     assert(PrevI != PrevMethod->param_end() && "Param mismatch");
1454     T1 = Context.getCanonicalType((*ParamI)->getType());
1455     T2 = Context.getCanonicalType((*PrevI)->getType());
1456     if (T1 != T2) {
1457       // The result types are different.
1458       if (!matchBasedOnSizeAndAlignment || matchBasedOnStrictEqulity)
1459         return false;
1460       // Incomplete types don't have a size and alignment.
1461       if (T1->isIncompleteType() || T2->isIncompleteType())
1462         return false;
1463       // Check is based on size and alignment.
1464       if (Context.getTypeInfo(T1) != Context.getTypeInfo(T2))
1465         return false;
1466     }
1467   }
1468   return true;
1469 }
1470
1471 /// \brief Read the contents of the method pool for a given selector from
1472 /// external storage.
1473 ///
1474 /// This routine should only be called once, when the method pool has no entry
1475 /// for this selector.
1476 Sema::GlobalMethodPool::iterator Sema::ReadMethodPool(Selector Sel) {
1477   assert(ExternalSource && "We need an external AST source");
1478   assert(MethodPool.find(Sel) == MethodPool.end() &&
1479          "Selector data already loaded into the method pool");
1480
1481   // Read the method list from the external source.
1482   GlobalMethods Methods = ExternalSource->ReadMethodPool(Sel);
1483
1484   return MethodPool.insert(std::make_pair(Sel, Methods)).first;
1485 }
1486
1487 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
1488                                  bool instance) {
1489   GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
1490   if (Pos == MethodPool.end()) {
1491     if (ExternalSource)
1492       Pos = ReadMethodPool(Method->getSelector());
1493     else
1494       Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
1495                                              GlobalMethods())).first;
1496   }
1497   Method->setDefined(impl);
1498   ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
1499   if (Entry.Method == 0) {
1500     // Haven't seen a method with this selector name yet - add it.
1501     Entry.Method = Method;
1502     Entry.Next = 0;
1503     return;
1504   }
1505
1506   // We've seen a method with this name, see if we have already seen this type
1507   // signature.
1508   for (ObjCMethodList *List = &Entry; List; List = List->Next)
1509     if (MatchTwoMethodDeclarations(Method, List->Method)) {
1510       ObjCMethodDecl *PrevObjCMethod = List->Method;
1511       PrevObjCMethod->setDefined(impl);
1512       // If a method is deprecated, push it in the global pool.
1513       // This is used for better diagnostics.
1514       if (Method->isDeprecated()) {
1515         if (!PrevObjCMethod->isDeprecated())
1516           List->Method = Method;
1517       }
1518       // If new method is unavailable, push it into global pool
1519       // unless previous one is deprecated.
1520       if (Method->isUnavailable()) {
1521         if (PrevObjCMethod->getAvailability() < AR_Deprecated)
1522           List->Method = Method;
1523       }
1524       return;
1525     }
1526
1527   // We have a new signature for an existing method - add it.
1528   // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
1529   ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
1530   Entry.Next = new (Mem) ObjCMethodList(Method, Entry.Next);
1531 }
1532
1533 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
1534                                                bool receiverIdOrClass,
1535                                                bool warn, bool instance) {
1536   GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
1537   if (Pos == MethodPool.end()) {
1538     if (ExternalSource)
1539       Pos = ReadMethodPool(Sel);
1540     else
1541       return 0;
1542   }
1543
1544   ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
1545
1546   bool strictSelectorMatch = receiverIdOrClass && warn &&
1547     (Diags.getDiagnosticLevel(diag::warn_strict_multiple_method_decl,
1548                               R.getBegin()) != 
1549       Diagnostic::Ignored);
1550   if (warn && MethList.Method && MethList.Next) {
1551     bool issueWarning = false;
1552     if (strictSelectorMatch)
1553       for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next) {
1554         // This checks if the methods differ in type mismatch.
1555         if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method, false, true))
1556           issueWarning = true;
1557       }
1558
1559     if (!issueWarning)
1560       for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next) {
1561         // This checks if the methods differ by size & alignment.
1562         if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method, true))
1563           issueWarning = true;
1564       }
1565
1566     if (issueWarning) {
1567       if (strictSelectorMatch)
1568         Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
1569       else
1570         Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
1571       Diag(MethList.Method->getLocStart(), diag::note_using)
1572         << MethList.Method->getSourceRange();
1573       for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1574         Diag(Next->Method->getLocStart(), diag::note_also_found)
1575           << Next->Method->getSourceRange();
1576     }
1577   }
1578   return MethList.Method;
1579 }
1580
1581 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
1582   GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
1583   if (Pos == MethodPool.end())
1584     return 0;
1585
1586   GlobalMethods &Methods = Pos->second;
1587
1588   if (Methods.first.Method && Methods.first.Method->isDefined())
1589     return Methods.first.Method;
1590   if (Methods.second.Method && Methods.second.Method->isDefined())
1591     return Methods.second.Method;
1592   return 0;
1593 }
1594
1595 /// CompareMethodParamsInBaseAndSuper - This routine compares methods with
1596 /// identical selector names in current and its super classes and issues
1597 /// a warning if any of their argument types are incompatible.
1598 void Sema::CompareMethodParamsInBaseAndSuper(Decl *ClassDecl,
1599                                              ObjCMethodDecl *Method,
1600                                              bool IsInstance)  {
1601   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
1602   if (ID == 0) return;
1603
1604   while (ObjCInterfaceDecl *SD = ID->getSuperClass()) {
1605     ObjCMethodDecl *SuperMethodDecl =
1606         SD->lookupMethod(Method->getSelector(), IsInstance);
1607     if (SuperMethodDecl == 0) {
1608       ID = SD;
1609       continue;
1610     }
1611     ObjCMethodDecl::param_iterator ParamI = Method->param_begin(),
1612       E = Method->param_end();
1613     ObjCMethodDecl::param_iterator PrevI = SuperMethodDecl->param_begin();
1614     for (; ParamI != E; ++ParamI, ++PrevI) {
1615       // Number of parameters are the same and is guaranteed by selector match.
1616       assert(PrevI != SuperMethodDecl->param_end() && "Param mismatch");
1617       QualType T1 = Context.getCanonicalType((*ParamI)->getType());
1618       QualType T2 = Context.getCanonicalType((*PrevI)->getType());
1619       // If type of argument of method in this class does not match its
1620       // respective argument type in the super class method, issue warning;
1621       if (!Context.typesAreCompatible(T1, T2)) {
1622         Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
1623           << T1 << T2;
1624         Diag(SuperMethodDecl->getLocation(), diag::note_previous_declaration);
1625         return;
1626       }
1627     }
1628     ID = SD;
1629   }
1630 }
1631
1632 /// DiagnoseDuplicateIvars - 
1633 /// Check for duplicate ivars in the entire class at the start of 
1634 /// @implementation. This becomes necesssary because class extension can
1635 /// add ivars to a class in random order which will not be known until
1636 /// class's @implementation is seen.
1637 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, 
1638                                   ObjCInterfaceDecl *SID) {
1639   for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
1640        IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
1641     ObjCIvarDecl* Ivar = (*IVI);
1642     if (Ivar->isInvalidDecl())
1643       continue;
1644     if (IdentifierInfo *II = Ivar->getIdentifier()) {
1645       ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
1646       if (prevIvar) {
1647         Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
1648         Diag(prevIvar->getLocation(), diag::note_previous_declaration);
1649         Ivar->setInvalidDecl();
1650       }
1651     }
1652   }
1653 }
1654
1655 // Note: For class/category implemenations, allMethods/allProperties is
1656 // always null.
1657 void Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd,
1658                       Decl *ClassDecl,
1659                       Decl **allMethods, unsigned allNum,
1660                       Decl **allProperties, unsigned pNum,
1661                       DeclGroupPtrTy *allTUVars, unsigned tuvNum) {
1662   // FIXME: If we don't have a ClassDecl, we have an error. We should consider
1663   // always passing in a decl. If the decl has an error, isInvalidDecl()
1664   // should be true.
1665   if (!ClassDecl)
1666     return;
1667   
1668   bool isInterfaceDeclKind =
1669         isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
1670          || isa<ObjCProtocolDecl>(ClassDecl);
1671   bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
1672
1673   if (!isInterfaceDeclKind && AtEnd.isInvalid()) {
1674     // FIXME: This is wrong.  We shouldn't be pretending that there is
1675     //  an '@end' in the declaration.
1676     SourceLocation L = ClassDecl->getLocation();
1677     AtEnd.setBegin(L);
1678     AtEnd.setEnd(L);
1679     Diag(L, diag::err_missing_atend);
1680   }
1681   
1682   // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
1683   llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
1684   llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
1685
1686   for (unsigned i = 0; i < allNum; i++ ) {
1687     ObjCMethodDecl *Method =
1688       cast_or_null<ObjCMethodDecl>(allMethods[i]);
1689
1690     if (!Method) continue;  // Already issued a diagnostic.
1691     if (Method->isInstanceMethod()) {
1692       /// Check for instance method of the same name with incompatible types
1693       const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
1694       bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
1695                               : false;
1696       if ((isInterfaceDeclKind && PrevMethod && !match)
1697           || (checkIdenticalMethods && match)) {
1698           Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1699             << Method->getDeclName();
1700           Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1701         Method->setInvalidDecl();
1702       } else {
1703         InsMap[Method->getSelector()] = Method;
1704         /// The following allows us to typecheck messages to "id".
1705         AddInstanceMethodToGlobalPool(Method);
1706         // verify that the instance method conforms to the same definition of
1707         // parent methods if it shadows one.
1708         CompareMethodParamsInBaseAndSuper(ClassDecl, Method, true);
1709       }
1710     } else {
1711       /// Check for class method of the same name with incompatible types
1712       const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
1713       bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
1714                               : false;
1715       if ((isInterfaceDeclKind && PrevMethod && !match)
1716           || (checkIdenticalMethods && match)) {
1717         Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1718           << Method->getDeclName();
1719         Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1720         Method->setInvalidDecl();
1721       } else {
1722         ClsMap[Method->getSelector()] = Method;
1723         /// The following allows us to typecheck messages to "Class".
1724         AddFactoryMethodToGlobalPool(Method);
1725         // verify that the class method conforms to the same definition of
1726         // parent methods if it shadows one.
1727         CompareMethodParamsInBaseAndSuper(ClassDecl, Method, false);
1728       }
1729     }
1730   }
1731   if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
1732     // Compares properties declared in this class to those of its
1733     // super class.
1734     ComparePropertiesInBaseAndSuper(I);
1735     CompareProperties(I, I);
1736   } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
1737     // Categories are used to extend the class by declaring new methods.
1738     // By the same token, they are also used to add new properties. No
1739     // need to compare the added property to those in the class.
1740
1741     // Compare protocol properties with those in category
1742     CompareProperties(C, C);
1743     if (C->IsClassExtension()) {
1744       ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
1745       DiagnoseClassExtensionDupMethods(C, CCPrimary);
1746     }
1747   }
1748   if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
1749     if (CDecl->getIdentifier())
1750       // ProcessPropertyDecl is responsible for diagnosing conflicts with any
1751       // user-defined setter/getter. It also synthesizes setter/getter methods
1752       // and adds them to the DeclContext and global method pools.
1753       for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
1754                                             E = CDecl->prop_end();
1755            I != E; ++I)
1756         ProcessPropertyDecl(*I, CDecl);
1757     CDecl->setAtEndRange(AtEnd);
1758   }
1759   if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
1760     IC->setAtEndRange(AtEnd);
1761     if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
1762       // Any property declared in a class extension might have user
1763       // declared setter or getter in current class extension or one
1764       // of the other class extensions. Mark them as synthesized as
1765       // property will be synthesized when property with same name is
1766       // seen in the @implementation.
1767       for (const ObjCCategoryDecl *ClsExtDecl =
1768            IDecl->getFirstClassExtension();
1769            ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
1770         for (ObjCContainerDecl::prop_iterator I = ClsExtDecl->prop_begin(),
1771              E = ClsExtDecl->prop_end(); I != E; ++I) {
1772           ObjCPropertyDecl *Property = (*I);
1773           // Skip over properties declared @dynamic
1774           if (const ObjCPropertyImplDecl *PIDecl
1775               = IC->FindPropertyImplDecl(Property->getIdentifier()))
1776             if (PIDecl->getPropertyImplementation() 
1777                   == ObjCPropertyImplDecl::Dynamic)
1778               continue;
1779           
1780           for (const ObjCCategoryDecl *CExtDecl =
1781                IDecl->getFirstClassExtension();
1782                CExtDecl; CExtDecl = CExtDecl->getNextClassExtension()) {
1783             if (ObjCMethodDecl *GetterMethod =
1784                 CExtDecl->getInstanceMethod(Property->getGetterName()))
1785               GetterMethod->setSynthesized(true);
1786             if (!Property->isReadOnly())
1787               if (ObjCMethodDecl *SetterMethod =
1788                   CExtDecl->getInstanceMethod(Property->getSetterName()))
1789                 SetterMethod->setSynthesized(true);
1790           }        
1791         }
1792       }
1793       
1794       if (LangOpts.ObjCDefaultSynthProperties &&
1795           LangOpts.ObjCNonFragileABI2)
1796         DefaultSynthesizeProperties(S, IC, IDecl);
1797       ImplMethodsVsClassMethods(S, IC, IDecl);
1798       AtomicPropertySetterGetterRules(IC, IDecl);
1799   
1800       if (LangOpts.ObjCNonFragileABI2)
1801         while (IDecl->getSuperClass()) {
1802           DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
1803           IDecl = IDecl->getSuperClass();
1804         }
1805     }
1806     SetIvarInitializers(IC);
1807   } else if (ObjCCategoryImplDecl* CatImplClass =
1808                                    dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
1809     CatImplClass->setAtEndRange(AtEnd);
1810
1811     // Find category interface decl and then check that all methods declared
1812     // in this interface are implemented in the category @implementation.
1813     if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
1814       for (ObjCCategoryDecl *Categories = IDecl->getCategoryList();
1815            Categories; Categories = Categories->getNextClassCategory()) {
1816         if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
1817           ImplMethodsVsClassMethods(S, CatImplClass, Categories);
1818           break;
1819         }
1820       }
1821     }
1822   }
1823   if (isInterfaceDeclKind) {
1824     // Reject invalid vardecls.
1825     for (unsigned i = 0; i != tuvNum; i++) {
1826       DeclGroupRef DG = allTUVars[i].getAsVal<DeclGroupRef>();
1827       for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
1828         if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
1829           if (!VDecl->hasExternalStorage())
1830             Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
1831         }
1832     }
1833   }
1834 }
1835
1836
1837 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
1838 /// objective-c's type qualifier from the parser version of the same info.
1839 static Decl::ObjCDeclQualifier
1840 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
1841   return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
1842 }
1843
1844 static inline
1845 bool containsInvalidMethodImplAttribute(const AttrVec &A) {
1846   // The 'ibaction' attribute is allowed on method definitions because of
1847   // how the IBAction macro is used on both method declarations and definitions.
1848   // If the method definitions contains any other attributes, return true.
1849   for (AttrVec::const_iterator i = A.begin(), e = A.end(); i != e; ++i)
1850     if ((*i)->getKind() != attr::IBAction)
1851       return true;
1852   return false;
1853 }
1854
1855 /// \brief Check whether the declared result type of the given Objective-C
1856 /// method declaration is compatible with the method's class.
1857 ///
1858 static bool 
1859 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
1860                                     ObjCInterfaceDecl *CurrentClass) {
1861   QualType ResultType = Method->getResultType();
1862   SourceRange ResultTypeRange;
1863   if (const TypeSourceInfo *ResultTypeInfo = Method->getResultTypeSourceInfo())
1864     ResultTypeRange = ResultTypeInfo->getTypeLoc().getSourceRange();
1865   
1866   // If an Objective-C method inherits its related result type, then its 
1867   // declared result type must be compatible with its own class type. The
1868   // declared result type is compatible if:
1869   if (const ObjCObjectPointerType *ResultObjectType
1870                                 = ResultType->getAs<ObjCObjectPointerType>()) {
1871     //   - it is id or qualified id, or
1872     if (ResultObjectType->isObjCIdType() ||
1873         ResultObjectType->isObjCQualifiedIdType())
1874       return false;
1875   
1876     if (CurrentClass) {
1877       if (ObjCInterfaceDecl *ResultClass 
1878                                       = ResultObjectType->getInterfaceDecl()) {
1879         //   - it is the same as the method's class type, or
1880         if (CurrentClass == ResultClass)
1881           return false;
1882         
1883         //   - it is a superclass of the method's class type
1884         if (ResultClass->isSuperClassOf(CurrentClass))
1885           return false;
1886       }      
1887     }
1888   }
1889   
1890   return true;
1891 }
1892
1893 /// \brief Determine if any method in the global method pool has an inferred 
1894 /// result type.
1895 static bool 
1896 anyMethodInfersRelatedResultType(Sema &S, Selector Sel, bool IsInstance) {
1897   Sema::GlobalMethodPool::iterator Pos = S.MethodPool.find(Sel);
1898   if (Pos == S.MethodPool.end()) {
1899     if (S.ExternalSource)
1900       Pos = S.ReadMethodPool(Sel);
1901     else
1902       return 0;
1903   }
1904   
1905   ObjCMethodList &List = IsInstance ? Pos->second.first : Pos->second.second;
1906   for (ObjCMethodList *M = &List; M; M = M->Next) {
1907     if (M->Method && M->Method->hasRelatedResultType())
1908       return true;
1909   }  
1910   
1911   return false;
1912 }
1913
1914 Decl *Sema::ActOnMethodDeclaration(
1915     Scope *S,
1916     SourceLocation MethodLoc, SourceLocation EndLoc,
1917     tok::TokenKind MethodType, Decl *ClassDecl,
1918     ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
1919     SourceLocation SelectorStartLoc,
1920     Selector Sel,
1921     // optional arguments. The number of types/arguments is obtained
1922     // from the Sel.getNumArgs().
1923     ObjCArgInfo *ArgInfo,
1924     DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
1925     AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
1926     bool isVariadic, bool MethodDefinition) {
1927   // Make sure we can establish a context for the method.
1928   if (!ClassDecl) {
1929     Diag(MethodLoc, diag::error_missing_method_context);
1930     return 0;
1931   }
1932   QualType resultDeclType;
1933
1934   TypeSourceInfo *ResultTInfo = 0;
1935   if (ReturnType) {
1936     resultDeclType = GetTypeFromParser(ReturnType, &ResultTInfo);
1937
1938     // Methods cannot return interface types. All ObjC objects are
1939     // passed by reference.
1940     if (resultDeclType->isObjCObjectType()) {
1941       Diag(MethodLoc, diag::err_object_cannot_be_passed_returned_by_value)
1942         << 0 << resultDeclType;
1943       return 0;
1944     }    
1945   } else // get the type for "id".
1946     resultDeclType = Context.getObjCIdType();
1947
1948   ObjCMethodDecl* ObjCMethod =
1949     ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel, resultDeclType,
1950                            ResultTInfo,
1951                            cast<DeclContext>(ClassDecl),
1952                            MethodType == tok::minus, isVariadic,
1953                            false, false,
1954                            MethodDeclKind == tok::objc_optional 
1955                              ? ObjCMethodDecl::Optional
1956                              : ObjCMethodDecl::Required,
1957                            false);
1958
1959   llvm::SmallVector<ParmVarDecl*, 16> Params;
1960
1961   for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
1962     QualType ArgType;
1963     TypeSourceInfo *DI;
1964
1965     if (ArgInfo[i].Type == 0) {
1966       ArgType = Context.getObjCIdType();
1967       DI = 0;
1968     } else {
1969       ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
1970       // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
1971       ArgType = adjustParameterType(ArgType);
1972     }
1973
1974     LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc, 
1975                    LookupOrdinaryName, ForRedeclaration);
1976     LookupName(R, S);
1977     if (R.isSingleResult()) {
1978       NamedDecl *PrevDecl = R.getFoundDecl();
1979       if (S->isDeclScope(PrevDecl)) {
1980         Diag(ArgInfo[i].NameLoc, 
1981              (MethodDefinition ? diag::warn_method_param_redefinition 
1982                                : diag::warn_method_param_declaration)) 
1983           << ArgInfo[i].Name;
1984         Diag(PrevDecl->getLocation(), 
1985              diag::note_previous_declaration);
1986       }
1987     }
1988
1989     SourceLocation StartLoc = DI
1990       ? DI->getTypeLoc().getBeginLoc()
1991       : ArgInfo[i].NameLoc;
1992
1993     ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
1994                                         ArgInfo[i].NameLoc, ArgInfo[i].Name,
1995                                         ArgType, DI, SC_None, SC_None);
1996
1997     Param->setObjCMethodScopeInfo(i);
1998
1999     Param->setObjCDeclQualifier(
2000       CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
2001
2002     // Apply the attributes to the parameter.
2003     ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
2004
2005     S->AddDecl(Param);
2006     IdResolver.AddDecl(Param);
2007
2008     Params.push_back(Param);
2009   }
2010   
2011   for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
2012     ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
2013     QualType ArgType = Param->getType();
2014     if (ArgType.isNull())
2015       ArgType = Context.getObjCIdType();
2016     else
2017       // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
2018       ArgType = adjustParameterType(ArgType);
2019     if (ArgType->isObjCObjectType()) {
2020       Diag(Param->getLocation(),
2021            diag::err_object_cannot_be_passed_returned_by_value)
2022       << 1 << ArgType;
2023       Param->setInvalidDecl();
2024     }
2025     Param->setDeclContext(ObjCMethod);
2026     
2027     Params.push_back(Param);
2028   }
2029   
2030   ObjCMethod->setMethodParams(Context, Params.data(), Params.size(),
2031                               Sel.getNumArgs());
2032   ObjCMethod->setObjCDeclQualifier(
2033     CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
2034   const ObjCMethodDecl *PrevMethod = 0;
2035
2036   if (AttrList)
2037     ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
2038
2039   const ObjCMethodDecl *InterfaceMD = 0;
2040
2041   // Add the method now.
2042   if (ObjCImplementationDecl *ImpDecl =
2043         dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
2044     if (MethodType == tok::minus) {
2045       PrevMethod = ImpDecl->getInstanceMethod(Sel);
2046       ImpDecl->addInstanceMethod(ObjCMethod);
2047     } else {
2048       PrevMethod = ImpDecl->getClassMethod(Sel);
2049       ImpDecl->addClassMethod(ObjCMethod);
2050     }
2051     InterfaceMD = ImpDecl->getClassInterface()->getMethod(Sel,
2052                                                    MethodType == tok::minus);
2053     
2054     if (ObjCMethod->hasAttrs() &&
2055         containsInvalidMethodImplAttribute(ObjCMethod->getAttrs()))
2056       Diag(EndLoc, diag::warn_attribute_method_def);
2057   } else if (ObjCCategoryImplDecl *CatImpDecl =
2058              dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
2059     if (MethodType == tok::minus) {
2060       PrevMethod = CatImpDecl->getInstanceMethod(Sel);
2061       CatImpDecl->addInstanceMethod(ObjCMethod);
2062     } else {
2063       PrevMethod = CatImpDecl->getClassMethod(Sel);
2064       CatImpDecl->addClassMethod(ObjCMethod);
2065     }
2066
2067     if (ObjCCategoryDecl *Cat = CatImpDecl->getCategoryDecl())
2068       InterfaceMD = Cat->getMethod(Sel, MethodType == tok::minus);
2069
2070     if (ObjCMethod->hasAttrs() &&
2071         containsInvalidMethodImplAttribute(ObjCMethod->getAttrs()))
2072       Diag(EndLoc, diag::warn_attribute_method_def);
2073   } else {
2074     cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
2075   }
2076   if (PrevMethod) {
2077     // You can never have two method definitions with the same name.
2078     Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
2079       << ObjCMethod->getDeclName();
2080     Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2081   }
2082
2083   // If this Objective-C method does not have a related result type, but we
2084   // are allowed to infer related result types, try to do so based on the
2085   // method family.
2086   ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
2087   if (!CurrentClass) {
2088     if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
2089       CurrentClass = Cat->getClassInterface();
2090     else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
2091       CurrentClass = Impl->getClassInterface();
2092     else if (ObjCCategoryImplDecl *CatImpl
2093                                    = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
2094       CurrentClass = CatImpl->getClassInterface();
2095   }
2096   
2097   // Merge information down from the interface declaration if we have one.
2098   if (InterfaceMD) {
2099     // Inherit the related result type, if we can.
2100     if (InterfaceMD->hasRelatedResultType() &&
2101         !CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass))
2102       ObjCMethod->SetRelatedResultType();
2103       
2104     mergeObjCMethodDecls(ObjCMethod, InterfaceMD);
2105   }
2106   
2107   if (!ObjCMethod->hasRelatedResultType() && 
2108       getLangOptions().ObjCInferRelatedResultType) {
2109     bool InferRelatedResultType = false;
2110     switch (ObjCMethod->getMethodFamily()) {
2111     case OMF_None:
2112     case OMF_copy:
2113     case OMF_dealloc:
2114     case OMF_mutableCopy:
2115     case OMF_release:
2116     case OMF_retainCount:
2117       break;
2118       
2119     case OMF_alloc:
2120     case OMF_new:
2121       InferRelatedResultType = ObjCMethod->isClassMethod();
2122       break;
2123         
2124     case OMF_init:
2125     case OMF_autorelease:
2126     case OMF_retain:
2127     case OMF_self:
2128       InferRelatedResultType = ObjCMethod->isInstanceMethod();
2129       break;
2130     }
2131     
2132     if (InferRelatedResultType &&
2133         !CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass))
2134       ObjCMethod->SetRelatedResultType();
2135     
2136     if (!InterfaceMD && 
2137         anyMethodInfersRelatedResultType(*this, ObjCMethod->getSelector(),
2138                                          ObjCMethod->isInstanceMethod()))
2139       CheckObjCMethodOverrides(ObjCMethod, cast<DeclContext>(ClassDecl));
2140   }
2141     
2142   return ObjCMethod;
2143 }
2144
2145 bool Sema::CheckObjCDeclScope(Decl *D) {
2146   if (isa<TranslationUnitDecl>(CurContext->getRedeclContext()))
2147     return false;
2148
2149   Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
2150   D->setInvalidDecl();
2151
2152   return true;
2153 }
2154
2155 /// Called whenever @defs(ClassName) is encountered in the source.  Inserts the
2156 /// instance variables of ClassName into Decls.
2157 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2158                      IdentifierInfo *ClassName,
2159                      llvm::SmallVectorImpl<Decl*> &Decls) {
2160   // Check that ClassName is a valid class
2161   ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
2162   if (!Class) {
2163     Diag(DeclStart, diag::err_undef_interface) << ClassName;
2164     return;
2165   }
2166   if (LangOpts.ObjCNonFragileABI) {
2167     Diag(DeclStart, diag::err_atdef_nonfragile_interface);
2168     return;
2169   }
2170
2171   // Collect the instance variables
2172   llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
2173   Context.DeepCollectObjCIvars(Class, true, Ivars);
2174   // For each ivar, create a fresh ObjCAtDefsFieldDecl.
2175   for (unsigned i = 0; i < Ivars.size(); i++) {
2176     FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
2177     RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
2178     Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
2179                                            /*FIXME: StartL=*/ID->getLocation(),
2180                                            ID->getLocation(),
2181                                            ID->getIdentifier(), ID->getType(),
2182                                            ID->getBitWidth());
2183     Decls.push_back(FD);
2184   }
2185
2186   // Introduce all of these fields into the appropriate scope.
2187   for (llvm::SmallVectorImpl<Decl*>::iterator D = Decls.begin();
2188        D != Decls.end(); ++D) {
2189     FieldDecl *FD = cast<FieldDecl>(*D);
2190     if (getLangOptions().CPlusPlus)
2191       PushOnScopeChains(cast<FieldDecl>(FD), S);
2192     else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
2193       Record->addDecl(FD);
2194   }
2195 }
2196
2197 /// \brief Build a type-check a new Objective-C exception variable declaration.
2198 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
2199                                       SourceLocation StartLoc,
2200                                       SourceLocation IdLoc,
2201                                       IdentifierInfo *Id,
2202                                       bool Invalid) {
2203   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 
2204   // duration shall not be qualified by an address-space qualifier."
2205   // Since all parameters have automatic store duration, they can not have
2206   // an address space.
2207   if (T.getAddressSpace() != 0) {
2208     Diag(IdLoc, diag::err_arg_with_address_space);
2209     Invalid = true;
2210   }
2211   
2212   // An @catch parameter must be an unqualified object pointer type;
2213   // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
2214   if (Invalid) {
2215     // Don't do any further checking.
2216   } else if (T->isDependentType()) {
2217     // Okay: we don't know what this type will instantiate to.
2218   } else if (!T->isObjCObjectPointerType()) {
2219     Invalid = true;
2220     Diag(IdLoc ,diag::err_catch_param_not_objc_type);
2221   } else if (T->isObjCQualifiedIdType()) {
2222     Invalid = true;
2223     Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
2224   }
2225   
2226   VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
2227                                  T, TInfo, SC_None, SC_None);
2228   New->setExceptionVariable(true);
2229   
2230   if (Invalid)
2231     New->setInvalidDecl();
2232   return New;
2233 }
2234
2235 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
2236   const DeclSpec &DS = D.getDeclSpec();
2237   
2238   // We allow the "register" storage class on exception variables because
2239   // GCC did, but we drop it completely. Any other storage class is an error.
2240   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2241     Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
2242       << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
2243   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
2244     Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
2245       << DS.getStorageClassSpec();
2246   }  
2247   if (D.getDeclSpec().isThreadSpecified())
2248     Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2249   D.getMutableDeclSpec().ClearStorageClassSpecs();
2250
2251   DiagnoseFunctionSpecifiers(D);
2252   
2253   // Check that there are no default arguments inside the type of this
2254   // exception object (C++ only).
2255   if (getLangOptions().CPlusPlus)
2256     CheckExtraCXXDefaultArguments(D);
2257   
2258   TagDecl *OwnedDecl = 0;
2259   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedDecl);
2260   QualType ExceptionType = TInfo->getType();
2261   
2262   if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) {
2263     // Objective-C++: Types shall not be defined in exception types.
2264     Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
2265       << Context.getTypeDeclType(OwnedDecl);
2266   }
2267
2268   VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
2269                                         D.getSourceRange().getBegin(),
2270                                         D.getIdentifierLoc(),
2271                                         D.getIdentifier(),
2272                                         D.isInvalidType());
2273   
2274   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2275   if (D.getCXXScopeSpec().isSet()) {
2276     Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
2277       << D.getCXXScopeSpec().getRange();
2278     New->setInvalidDecl();
2279   }
2280   
2281   // Add the parameter declaration into this scope.
2282   S->AddDecl(New);
2283   if (D.getIdentifier())
2284     IdResolver.AddDecl(New);
2285   
2286   ProcessDeclAttributes(S, New, D);
2287   
2288   if (New->hasAttr<BlocksAttr>())
2289     Diag(New->getLocation(), diag::err_block_on_nonlocal);
2290   return New;
2291 }
2292
2293 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
2294 /// initialization.
2295 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
2296                                 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
2297   for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv; 
2298        Iv= Iv->getNextIvar()) {
2299     QualType QT = Context.getBaseElementType(Iv->getType());
2300     if (QT->isRecordType())
2301       Ivars.push_back(Iv);
2302   }
2303 }
2304
2305 void ObjCImplementationDecl::setIvarInitializers(ASTContext &C,
2306                                              CXXCtorInitializer ** initializers,
2307                                                  unsigned numInitializers) {
2308   if (numInitializers > 0) {
2309     NumIvarInitializers = numInitializers;
2310     CXXCtorInitializer **ivarInitializers =
2311     new (C) CXXCtorInitializer*[NumIvarInitializers];
2312     memcpy(ivarInitializers, initializers,
2313            numInitializers * sizeof(CXXCtorInitializer*));
2314     IvarInitializers = ivarInitializers;
2315   }
2316 }
2317
2318 void Sema::DiagnoseUseOfUnimplementedSelectors() {
2319   // Warning will be issued only when selector table is
2320   // generated (which means there is at lease one implementation
2321   // in the TU). This is to match gcc's behavior.
2322   if (ReferencedSelectors.empty() || 
2323       !Context.AnyObjCImplementation())
2324     return;
2325   for (llvm::DenseMap<Selector, SourceLocation>::iterator S = 
2326         ReferencedSelectors.begin(),
2327        E = ReferencedSelectors.end(); S != E; ++S) {
2328     Selector Sel = (*S).first;
2329     if (!LookupImplementedMethodInGlobalPool(Sel))
2330       Diag((*S).second, diag::warn_unimplemented_selector) << Sel;
2331   }
2332   return;
2333 }