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