SemaDeclObjC.cpp revision 206125
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 "Sema.h"
15#include "Lookup.h"
16#include "clang/Sema/ExternalSemaSource.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/Parse/DeclSpec.h"
21using namespace clang;
22
23/// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
24/// and user declared, in the method definition's AST.
25void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, DeclPtrTy D) {
26  assert(getCurMethodDecl() == 0 && "Method parsing confused");
27  ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D.getAs<Decl>());
28
29  // If we don't have a valid method decl, simply return.
30  if (!MDecl)
31    return;
32
33  // Allow the rest of sema to find private method decl implementations.
34  if (MDecl->isInstanceMethod())
35    AddInstanceMethodToGlobalPool(MDecl);
36  else
37    AddFactoryMethodToGlobalPool(MDecl);
38
39  // Allow all of Sema to see that we are entering a method definition.
40  PushDeclContext(FnBodyScope, MDecl);
41  PushFunctionScope();
42
43  // Create Decl objects for each parameter, entrring them in the scope for
44  // binding to their use.
45
46  // Insert the invisible arguments, self and _cmd!
47  MDecl->createImplicitParams(Context, MDecl->getClassInterface());
48
49  PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
50  PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
51
52  // Introduce all of the other parameters into this scope.
53  for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
54       E = MDecl->param_end(); PI != E; ++PI)
55    if ((*PI)->getIdentifier())
56      PushOnScopeChains(*PI, FnBodyScope);
57}
58
59Sema::DeclPtrTy Sema::
60ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
61                         IdentifierInfo *ClassName, SourceLocation ClassLoc,
62                         IdentifierInfo *SuperName, SourceLocation SuperLoc,
63                         const DeclPtrTy *ProtoRefs, unsigned NumProtoRefs,
64                         const SourceLocation *ProtoLocs,
65                         SourceLocation EndProtoLoc, AttributeList *AttrList) {
66  assert(ClassName && "Missing class identifier");
67
68  // Check for another declaration kind with the same name.
69  NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
70  if (PrevDecl && PrevDecl->isTemplateParameter()) {
71    // Maybe we will complain about the shadowed template parameter.
72    DiagnoseTemplateParameterShadow(ClassLoc, PrevDecl);
73    // Just pretend that we didn't see the previous declaration.
74    PrevDecl = 0;
75  }
76
77  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
78    Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
79    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
80  }
81
82  ObjCInterfaceDecl* IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
83  if (IDecl) {
84    // Class already seen. Is it a forward declaration?
85    if (!IDecl->isForwardDecl()) {
86      IDecl->setInvalidDecl();
87      Diag(AtInterfaceLoc, diag::err_duplicate_class_def)<<IDecl->getDeclName();
88      Diag(IDecl->getLocation(), diag::note_previous_definition);
89
90      // Return the previous class interface.
91      // FIXME: don't leak the objects passed in!
92      return DeclPtrTy::make(IDecl);
93    } else {
94      IDecl->setLocation(AtInterfaceLoc);
95      IDecl->setForwardDecl(false);
96      IDecl->setClassLoc(ClassLoc);
97
98      // Since this ObjCInterfaceDecl was created by a forward declaration,
99      // we now add it to the DeclContext since it wasn't added before
100      // (see ActOnForwardClassDeclaration).
101      CurContext->addDecl(IDecl);
102
103      if (AttrList)
104        ProcessDeclAttributeList(TUScope, IDecl, AttrList);
105    }
106  } else {
107    IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc,
108                                      ClassName, ClassLoc);
109    if (AttrList)
110      ProcessDeclAttributeList(TUScope, IDecl, AttrList);
111
112    PushOnScopeChains(IDecl, TUScope);
113  }
114
115  if (SuperName) {
116    // Check if a different kind of symbol declared in this scope.
117    PrevDecl = LookupSingleName(TUScope, SuperName, LookupOrdinaryName);
118
119    if (!PrevDecl) {
120      // Try to correct for a typo in the superclass name.
121      LookupResult R(*this, SuperName, SuperLoc, LookupOrdinaryName);
122      if (CorrectTypo(R, TUScope, 0) &&
123          (PrevDecl = R.getAsSingle<ObjCInterfaceDecl>())) {
124        Diag(SuperLoc, diag::err_undef_superclass_suggest)
125          << SuperName << ClassName << PrevDecl->getDeclName();
126        Diag(PrevDecl->getLocation(), diag::note_previous_decl)
127          << PrevDecl->getDeclName();
128      }
129    }
130
131    if (PrevDecl == IDecl) {
132      Diag(SuperLoc, diag::err_recursive_superclass)
133        << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
134      IDecl->setLocEnd(ClassLoc);
135    } else {
136      ObjCInterfaceDecl *SuperClassDecl =
137                                dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
138
139      // Diagnose classes that inherit from deprecated classes.
140      if (SuperClassDecl)
141        (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
142
143      if (PrevDecl && SuperClassDecl == 0) {
144        // The previous declaration was not a class decl. Check if we have a
145        // typedef. If we do, get the underlying class type.
146        if (const TypedefDecl *TDecl = dyn_cast_or_null<TypedefDecl>(PrevDecl)) {
147          QualType T = TDecl->getUnderlyingType();
148          if (T->isObjCInterfaceType()) {
149            if (NamedDecl *IDecl = T->getAs<ObjCInterfaceType>()->getDecl())
150              SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
151          }
152        }
153
154        // This handles the following case:
155        //
156        // typedef int SuperClass;
157        // @interface MyClass : SuperClass {} @end
158        //
159        if (!SuperClassDecl) {
160          Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
161          Diag(PrevDecl->getLocation(), diag::note_previous_definition);
162        }
163      }
164
165      if (!dyn_cast_or_null<TypedefDecl>(PrevDecl)) {
166        if (!SuperClassDecl)
167          Diag(SuperLoc, diag::err_undef_superclass)
168            << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
169        else if (SuperClassDecl->isForwardDecl())
170          Diag(SuperLoc, diag::err_undef_superclass)
171            << SuperClassDecl->getDeclName() << ClassName
172            << SourceRange(AtInterfaceLoc, ClassLoc);
173      }
174      IDecl->setSuperClass(SuperClassDecl);
175      IDecl->setSuperClassLoc(SuperLoc);
176      IDecl->setLocEnd(SuperLoc);
177    }
178  } else { // we have a root class.
179    IDecl->setLocEnd(ClassLoc);
180  }
181
182  /// Check then save referenced protocols.
183  if (NumProtoRefs) {
184    IDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
185                           ProtoLocs, Context);
186    IDecl->setLocEnd(EndProtoLoc);
187  }
188
189  CheckObjCDeclScope(IDecl);
190  return DeclPtrTy::make(IDecl);
191}
192
193/// ActOnCompatiblityAlias - this action is called after complete parsing of
194/// @compatibility_alias declaration. It sets up the alias relationships.
195Sema::DeclPtrTy Sema::ActOnCompatiblityAlias(SourceLocation AtLoc,
196                                             IdentifierInfo *AliasName,
197                                             SourceLocation AliasLocation,
198                                             IdentifierInfo *ClassName,
199                                             SourceLocation ClassLocation) {
200  // Look for previous declaration of alias name
201  NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, LookupOrdinaryName);
202  if (ADecl) {
203    if (isa<ObjCCompatibleAliasDecl>(ADecl))
204      Diag(AliasLocation, diag::warn_previous_alias_decl);
205    else
206      Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
207    Diag(ADecl->getLocation(), diag::note_previous_declaration);
208    return DeclPtrTy();
209  }
210  // Check for class declaration
211  NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
212  if (const TypedefDecl *TDecl = dyn_cast_or_null<TypedefDecl>(CDeclU)) {
213    QualType T = TDecl->getUnderlyingType();
214    if (T->isObjCInterfaceType()) {
215      if (NamedDecl *IDecl = T->getAs<ObjCInterfaceType>()->getDecl()) {
216        ClassName = IDecl->getIdentifier();
217        CDeclU = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
218      }
219    }
220  }
221  ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
222  if (CDecl == 0) {
223    Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
224    if (CDeclU)
225      Diag(CDeclU->getLocation(), diag::note_previous_declaration);
226    return DeclPtrTy();
227  }
228
229  // Everything checked out, instantiate a new alias declaration AST.
230  ObjCCompatibleAliasDecl *AliasDecl =
231    ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
232
233  if (!CheckObjCDeclScope(AliasDecl))
234    PushOnScopeChains(AliasDecl, TUScope);
235
236  return DeclPtrTy::make(AliasDecl);
237}
238
239void Sema::CheckForwardProtocolDeclarationForCircularDependency(
240  IdentifierInfo *PName,
241  SourceLocation &Ploc, SourceLocation PrevLoc,
242  const ObjCList<ObjCProtocolDecl> &PList) {
243  for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
244       E = PList.end(); I != E; ++I) {
245
246    if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier())) {
247      if (PDecl->getIdentifier() == PName) {
248        Diag(Ploc, diag::err_protocol_has_circular_dependency);
249        Diag(PrevLoc, diag::note_previous_definition);
250      }
251      CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
252        PDecl->getLocation(), PDecl->getReferencedProtocols());
253    }
254  }
255}
256
257Sema::DeclPtrTy
258Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
259                                  IdentifierInfo *ProtocolName,
260                                  SourceLocation ProtocolLoc,
261                                  const DeclPtrTy *ProtoRefs,
262                                  unsigned NumProtoRefs,
263                                  const SourceLocation *ProtoLocs,
264                                  SourceLocation EndProtoLoc,
265                                  AttributeList *AttrList) {
266  // FIXME: Deal with AttrList.
267  assert(ProtocolName && "Missing protocol identifier");
268  ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolName);
269  if (PDecl) {
270    // Protocol already seen. Better be a forward protocol declaration
271    if (!PDecl->isForwardDecl()) {
272      Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
273      Diag(PDecl->getLocation(), diag::note_previous_definition);
274      // Just return the protocol we already had.
275      // FIXME: don't leak the objects passed in!
276      return DeclPtrTy::make(PDecl);
277    }
278    ObjCList<ObjCProtocolDecl> PList;
279    PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
280    CheckForwardProtocolDeclarationForCircularDependency(
281      ProtocolName, ProtocolLoc, PDecl->getLocation(), PList);
282    PList.Destroy(Context);
283
284    // Make sure the cached decl gets a valid start location.
285    PDecl->setLocation(AtProtoInterfaceLoc);
286    PDecl->setForwardDecl(false);
287  } else {
288    PDecl = ObjCProtocolDecl::Create(Context, CurContext,
289                                     AtProtoInterfaceLoc,ProtocolName);
290    PushOnScopeChains(PDecl, TUScope);
291    PDecl->setForwardDecl(false);
292  }
293  if (AttrList)
294    ProcessDeclAttributeList(TUScope, PDecl, AttrList);
295  if (NumProtoRefs) {
296    /// Check then save referenced protocols.
297    PDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
298                           ProtoLocs, Context);
299    PDecl->setLocEnd(EndProtoLoc);
300  }
301
302  CheckObjCDeclScope(PDecl);
303  return DeclPtrTy::make(PDecl);
304}
305
306/// FindProtocolDeclaration - This routine looks up protocols and
307/// issues an error if they are not declared. It returns list of
308/// protocol declarations in its 'Protocols' argument.
309void
310Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
311                              const IdentifierLocPair *ProtocolId,
312                              unsigned NumProtocols,
313                              llvm::SmallVectorImpl<DeclPtrTy> &Protocols) {
314  for (unsigned i = 0; i != NumProtocols; ++i) {
315    ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first);
316    if (!PDecl) {
317      LookupResult R(*this, ProtocolId[i].first, ProtocolId[i].second,
318                     LookupObjCProtocolName);
319      if (CorrectTypo(R, TUScope, 0) &&
320          (PDecl = R.getAsSingle<ObjCProtocolDecl>())) {
321        Diag(ProtocolId[i].second, diag::err_undeclared_protocol_suggest)
322          << ProtocolId[i].first << R.getLookupName();
323        Diag(PDecl->getLocation(), diag::note_previous_decl)
324          << PDecl->getDeclName();
325      }
326    }
327
328    if (!PDecl) {
329      Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
330        << ProtocolId[i].first;
331      continue;
332    }
333
334    (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
335
336    // If this is a forward declaration and we are supposed to warn in this
337    // case, do it.
338    if (WarnOnDeclarations && PDecl->isForwardDecl())
339      Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
340        << ProtocolId[i].first;
341    Protocols.push_back(DeclPtrTy::make(PDecl));
342  }
343}
344
345/// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
346/// a class method in its extension.
347///
348void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
349                                            ObjCInterfaceDecl *ID) {
350  if (!ID)
351    return;  // Possibly due to previous error
352
353  llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
354  for (ObjCInterfaceDecl::method_iterator i = ID->meth_begin(),
355       e =  ID->meth_end(); i != e; ++i) {
356    ObjCMethodDecl *MD = *i;
357    MethodMap[MD->getSelector()] = MD;
358  }
359
360  if (MethodMap.empty())
361    return;
362  for (ObjCCategoryDecl::method_iterator i = CAT->meth_begin(),
363       e =  CAT->meth_end(); i != e; ++i) {
364    ObjCMethodDecl *Method = *i;
365    const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
366    if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
367      Diag(Method->getLocation(), diag::err_duplicate_method_decl)
368            << Method->getDeclName();
369      Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
370    }
371  }
372}
373
374/// ActOnForwardProtocolDeclaration - Handle @protocol foo;
375Action::DeclPtrTy
376Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
377                                      const IdentifierLocPair *IdentList,
378                                      unsigned NumElts,
379                                      AttributeList *attrList) {
380  llvm::SmallVector<ObjCProtocolDecl*, 32> Protocols;
381  llvm::SmallVector<SourceLocation, 8> ProtoLocs;
382
383  for (unsigned i = 0; i != NumElts; ++i) {
384    IdentifierInfo *Ident = IdentList[i].first;
385    ObjCProtocolDecl *PDecl = LookupProtocol(Ident);
386    if (PDecl == 0) { // Not already seen?
387      PDecl = ObjCProtocolDecl::Create(Context, CurContext,
388                                       IdentList[i].second, Ident);
389      PushOnScopeChains(PDecl, TUScope);
390    }
391    if (attrList)
392      ProcessDeclAttributeList(TUScope, PDecl, attrList);
393    Protocols.push_back(PDecl);
394    ProtoLocs.push_back(IdentList[i].second);
395  }
396
397  ObjCForwardProtocolDecl *PDecl =
398    ObjCForwardProtocolDecl::Create(Context, CurContext, AtProtocolLoc,
399                                    Protocols.data(), Protocols.size(),
400                                    ProtoLocs.data());
401  CurContext->addDecl(PDecl);
402  CheckObjCDeclScope(PDecl);
403  return DeclPtrTy::make(PDecl);
404}
405
406Sema::DeclPtrTy Sema::
407ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
408                            IdentifierInfo *ClassName, SourceLocation ClassLoc,
409                            IdentifierInfo *CategoryName,
410                            SourceLocation CategoryLoc,
411                            const DeclPtrTy *ProtoRefs,
412                            unsigned NumProtoRefs,
413                            const SourceLocation *ProtoLocs,
414                            SourceLocation EndProtoLoc) {
415  ObjCCategoryDecl *CDecl = 0;
416  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc);
417
418  /// Check that class of this category is already completely declared.
419  if (!IDecl || IDecl->isForwardDecl()) {
420    // Create an invalid ObjCCategoryDecl to serve as context for
421    // the enclosing method declarations.  We mark the decl invalid
422    // to make it clear that this isn't a valid AST.
423    CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
424                                     ClassLoc, CategoryLoc, CategoryName);
425    CDecl->setInvalidDecl();
426    Diag(ClassLoc, diag::err_undef_interface) << ClassName;
427    return DeclPtrTy::make(CDecl);
428  }
429
430  if (!CategoryName) {
431    // Class extensions require a special treatment. Use an existing one.
432    // Note that 'getClassExtension()' can return NULL.
433    CDecl = IDecl->getClassExtension();
434    if (IDecl->getImplementation()) {
435      Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
436      Diag(IDecl->getImplementation()->getLocation(),
437           diag::note_implementation_declared);
438    }
439  }
440
441  if (!CDecl) {
442    CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
443                                     ClassLoc, CategoryLoc, CategoryName);
444    // FIXME: PushOnScopeChains?
445    CurContext->addDecl(CDecl);
446
447    CDecl->setClassInterface(IDecl);
448    // Insert first use of class extension to the list of class's categories.
449    if (!CategoryName)
450      CDecl->insertNextClassCategory();
451  }
452
453  // If the interface is deprecated, warn about it.
454  (void)DiagnoseUseOfDecl(IDecl, ClassLoc);
455
456  if (CategoryName) {
457    /// Check for duplicate interface declaration for this category
458    ObjCCategoryDecl *CDeclChain;
459    for (CDeclChain = IDecl->getCategoryList(); CDeclChain;
460         CDeclChain = CDeclChain->getNextClassCategory()) {
461      if (CDeclChain->getIdentifier() == CategoryName) {
462        // Class extensions can be declared multiple times.
463        Diag(CategoryLoc, diag::warn_dup_category_def)
464          << ClassName << CategoryName;
465        Diag(CDeclChain->getLocation(), diag::note_previous_definition);
466        break;
467      }
468    }
469    if (!CDeclChain)
470      CDecl->insertNextClassCategory();
471  }
472
473  if (NumProtoRefs) {
474    CDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
475                           ProtoLocs, Context);
476    // Protocols in the class extension belong to the class.
477    if (CDecl->IsClassExtension())
478     IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl**)ProtoRefs,
479                                            NumProtoRefs, ProtoLocs,
480                                            Context);
481  }
482
483  CheckObjCDeclScope(CDecl);
484  return DeclPtrTy::make(CDecl);
485}
486
487/// ActOnStartCategoryImplementation - Perform semantic checks on the
488/// category implementation declaration and build an ObjCCategoryImplDecl
489/// object.
490Sema::DeclPtrTy Sema::ActOnStartCategoryImplementation(
491                      SourceLocation AtCatImplLoc,
492                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
493                      IdentifierInfo *CatName, SourceLocation CatLoc) {
494  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc);
495  ObjCCategoryDecl *CatIDecl = 0;
496  if (IDecl) {
497    CatIDecl = IDecl->FindCategoryDeclaration(CatName);
498    if (!CatIDecl) {
499      // Category @implementation with no corresponding @interface.
500      // Create and install one.
501      CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, SourceLocation(),
502                                          SourceLocation(), SourceLocation(),
503                                          CatName);
504      CatIDecl->setClassInterface(IDecl);
505      CatIDecl->insertNextClassCategory();
506    }
507  }
508
509  ObjCCategoryImplDecl *CDecl =
510    ObjCCategoryImplDecl::Create(Context, CurContext, AtCatImplLoc, CatName,
511                                 IDecl);
512  /// Check that class of this category is already completely declared.
513  if (!IDecl || IDecl->isForwardDecl())
514    Diag(ClassLoc, diag::err_undef_interface) << ClassName;
515
516  // FIXME: PushOnScopeChains?
517  CurContext->addDecl(CDecl);
518
519  /// Check that CatName, category name, is not used in another implementation.
520  if (CatIDecl) {
521    if (CatIDecl->getImplementation()) {
522      Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
523        << CatName;
524      Diag(CatIDecl->getImplementation()->getLocation(),
525           diag::note_previous_definition);
526    } else
527      CatIDecl->setImplementation(CDecl);
528  }
529
530  CheckObjCDeclScope(CDecl);
531  return DeclPtrTy::make(CDecl);
532}
533
534Sema::DeclPtrTy Sema::ActOnStartClassImplementation(
535                      SourceLocation AtClassImplLoc,
536                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
537                      IdentifierInfo *SuperClassname,
538                      SourceLocation SuperClassLoc) {
539  ObjCInterfaceDecl* IDecl = 0;
540  // Check for another declaration kind with the same name.
541  NamedDecl *PrevDecl
542    = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
543  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
544    Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
545    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
546  } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
547    // If this is a forward declaration of an interface, warn.
548    if (IDecl->isForwardDecl()) {
549      Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
550      IDecl = 0;
551    }
552  } else {
553    // We did not find anything with the name ClassName; try to correct for
554    // typos in the class name.
555    LookupResult R(*this, ClassName, ClassLoc, LookupOrdinaryName);
556    if (CorrectTypo(R, TUScope, 0) &&
557        (IDecl = R.getAsSingle<ObjCInterfaceDecl>())) {
558      // Suggest the (potentially) correct interface name. However, put the
559      // fix-it hint itself in a separate note, since changing the name in
560      // the warning would make the fix-it change semantics.However, don't
561      // provide a code-modification hint or use the typo name for recovery,
562      // because this is just a warning. The program may actually be correct.
563      Diag(ClassLoc, diag::warn_undef_interface_suggest)
564        << ClassName << R.getLookupName();
565      Diag(IDecl->getLocation(), diag::note_previous_decl)
566        << R.getLookupName()
567        << FixItHint::CreateReplacement(ClassLoc,
568                                        R.getLookupName().getAsString());
569      IDecl = 0;
570    } else {
571      Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
572    }
573  }
574
575  // Check that super class name is valid class name
576  ObjCInterfaceDecl* SDecl = 0;
577  if (SuperClassname) {
578    // Check if a different kind of symbol declared in this scope.
579    PrevDecl = LookupSingleName(TUScope, SuperClassname, LookupOrdinaryName);
580    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
581      Diag(SuperClassLoc, diag::err_redefinition_different_kind)
582        << SuperClassname;
583      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
584    } else {
585      SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
586      if (!SDecl)
587        Diag(SuperClassLoc, diag::err_undef_superclass)
588          << SuperClassname << ClassName;
589      else if (IDecl && IDecl->getSuperClass() != SDecl) {
590        // This implementation and its interface do not have the same
591        // super class.
592        Diag(SuperClassLoc, diag::err_conflicting_super_class)
593          << SDecl->getDeclName();
594        Diag(SDecl->getLocation(), diag::note_previous_definition);
595      }
596    }
597  }
598
599  if (!IDecl) {
600    // Legacy case of @implementation with no corresponding @interface.
601    // Build, chain & install the interface decl into the identifier.
602
603    // FIXME: Do we support attributes on the @implementation? If so we should
604    // copy them over.
605    IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
606                                      ClassName, ClassLoc, false, true);
607    IDecl->setSuperClass(SDecl);
608    IDecl->setLocEnd(ClassLoc);
609
610    PushOnScopeChains(IDecl, TUScope);
611  } else {
612    // Mark the interface as being completed, even if it was just as
613    //   @class ....;
614    // declaration; the user cannot reopen it.
615    IDecl->setForwardDecl(false);
616  }
617
618  ObjCImplementationDecl* IMPDecl =
619    ObjCImplementationDecl::Create(Context, CurContext, AtClassImplLoc,
620                                   IDecl, SDecl);
621
622  if (CheckObjCDeclScope(IMPDecl))
623    return DeclPtrTy::make(IMPDecl);
624
625  // Check that there is no duplicate implementation of this class.
626  if (IDecl->getImplementation()) {
627    // FIXME: Don't leak everything!
628    Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
629    Diag(IDecl->getImplementation()->getLocation(),
630         diag::note_previous_definition);
631  } else { // add it to the list.
632    IDecl->setImplementation(IMPDecl);
633    PushOnScopeChains(IMPDecl, TUScope);
634  }
635  return DeclPtrTy::make(IMPDecl);
636}
637
638void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
639                                    ObjCIvarDecl **ivars, unsigned numIvars,
640                                    SourceLocation RBrace) {
641  assert(ImpDecl && "missing implementation decl");
642  ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
643  if (!IDecl)
644    return;
645  /// Check case of non-existing @interface decl.
646  /// (legacy objective-c @implementation decl without an @interface decl).
647  /// Add implementations's ivar to the synthesize class's ivar list.
648  if (IDecl->isImplicitInterfaceDecl()) {
649    IDecl->setLocEnd(RBrace);
650    // Add ivar's to class's DeclContext.
651    for (unsigned i = 0, e = numIvars; i != e; ++i) {
652      ivars[i]->setLexicalDeclContext(ImpDecl);
653      IDecl->makeDeclVisibleInContext(ivars[i], false);
654      ImpDecl->addDecl(ivars[i]);
655    }
656
657    return;
658  }
659  // If implementation has empty ivar list, just return.
660  if (numIvars == 0)
661    return;
662
663  assert(ivars && "missing @implementation ivars");
664  if (LangOpts.ObjCNonFragileABI2) {
665    if (ImpDecl->getSuperClass())
666      Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
667    for (unsigned i = 0; i < numIvars; i++) {
668      ObjCIvarDecl* ImplIvar = ivars[i];
669      if (const ObjCIvarDecl *ClsIvar =
670            IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
671        Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
672        Diag(ClsIvar->getLocation(), diag::note_previous_definition);
673        continue;
674      }
675      // Instance ivar to Implementation's DeclContext.
676      ImplIvar->setLexicalDeclContext(ImpDecl);
677      IDecl->makeDeclVisibleInContext(ImplIvar, false);
678      ImpDecl->addDecl(ImplIvar);
679    }
680    return;
681  }
682  // Check interface's Ivar list against those in the implementation.
683  // names and types must match.
684  //
685  unsigned j = 0;
686  ObjCInterfaceDecl::ivar_iterator
687    IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
688  for (; numIvars > 0 && IVI != IVE; ++IVI) {
689    ObjCIvarDecl* ImplIvar = ivars[j++];
690    ObjCIvarDecl* ClsIvar = *IVI;
691    assert (ImplIvar && "missing implementation ivar");
692    assert (ClsIvar && "missing class ivar");
693
694    // First, make sure the types match.
695    if (Context.getCanonicalType(ImplIvar->getType()) !=
696        Context.getCanonicalType(ClsIvar->getType())) {
697      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
698        << ImplIvar->getIdentifier()
699        << ImplIvar->getType() << ClsIvar->getType();
700      Diag(ClsIvar->getLocation(), diag::note_previous_definition);
701    } else if (ImplIvar->isBitField() && ClsIvar->isBitField()) {
702      Expr *ImplBitWidth = ImplIvar->getBitWidth();
703      Expr *ClsBitWidth = ClsIvar->getBitWidth();
704      if (ImplBitWidth->EvaluateAsInt(Context).getZExtValue() !=
705          ClsBitWidth->EvaluateAsInt(Context).getZExtValue()) {
706        Diag(ImplBitWidth->getLocStart(), diag::err_conflicting_ivar_bitwidth)
707          << ImplIvar->getIdentifier();
708        Diag(ClsBitWidth->getLocStart(), diag::note_previous_definition);
709      }
710    }
711    // Make sure the names are identical.
712    if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
713      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
714        << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
715      Diag(ClsIvar->getLocation(), diag::note_previous_definition);
716    }
717    --numIvars;
718  }
719
720  if (numIvars > 0)
721    Diag(ivars[j]->getLocation(), diag::err_inconsistant_ivar_count);
722  else if (IVI != IVE)
723    Diag((*IVI)->getLocation(), diag::err_inconsistant_ivar_count);
724}
725
726void Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
727                               bool &IncompleteImpl, unsigned DiagID) {
728  if (!IncompleteImpl) {
729    Diag(ImpLoc, diag::warn_incomplete_impl);
730    IncompleteImpl = true;
731  }
732  Diag(method->getLocation(), DiagID)
733    << method->getDeclName();
734}
735
736void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
737                                       ObjCMethodDecl *IntfMethodDecl) {
738  if (!Context.typesAreCompatible(IntfMethodDecl->getResultType(),
739                                  ImpMethodDecl->getResultType()) &&
740      !Context.QualifiedIdConformsQualifiedId(IntfMethodDecl->getResultType(),
741                                              ImpMethodDecl->getResultType())) {
742    Diag(ImpMethodDecl->getLocation(), diag::warn_conflicting_ret_types)
743      << ImpMethodDecl->getDeclName() << IntfMethodDecl->getResultType()
744      << ImpMethodDecl->getResultType();
745    Diag(IntfMethodDecl->getLocation(), diag::note_previous_definition);
746  }
747
748  for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
749       IF = IntfMethodDecl->param_begin(), EM = ImpMethodDecl->param_end();
750       IM != EM; ++IM, ++IF) {
751    QualType ParmDeclTy = (*IF)->getType().getUnqualifiedType();
752    QualType ParmImpTy = (*IM)->getType().getUnqualifiedType();
753    if (Context.typesAreCompatible(ParmDeclTy, ParmImpTy) ||
754        Context.QualifiedIdConformsQualifiedId(ParmDeclTy, ParmImpTy))
755      continue;
756
757    Diag((*IM)->getLocation(), diag::warn_conflicting_param_types)
758      << ImpMethodDecl->getDeclName() << (*IF)->getType()
759      << (*IM)->getType();
760    Diag((*IF)->getLocation(), diag::note_previous_definition);
761  }
762}
763
764/// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
765/// improve the efficiency of selector lookups and type checking by associating
766/// with each protocol / interface / category the flattened instance tables. If
767/// we used an immutable set to keep the table then it wouldn't add significant
768/// memory cost and it would be handy for lookups.
769
770/// CheckProtocolMethodDefs - This routine checks unimplemented methods
771/// Declared in protocol, and those referenced by it.
772void Sema::CheckProtocolMethodDefs(SourceLocation ImpLoc,
773                                   ObjCProtocolDecl *PDecl,
774                                   bool& IncompleteImpl,
775                                   const llvm::DenseSet<Selector> &InsMap,
776                                   const llvm::DenseSet<Selector> &ClsMap,
777                                   ObjCContainerDecl *CDecl) {
778  ObjCInterfaceDecl *IDecl;
779  if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl))
780    IDecl = C->getClassInterface();
781  else
782    IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
783  assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
784
785  ObjCInterfaceDecl *Super = IDecl->getSuperClass();
786  ObjCInterfaceDecl *NSIDecl = 0;
787  if (getLangOptions().NeXTRuntime) {
788    // check to see if class implements forwardInvocation method and objects
789    // of this class are derived from 'NSProxy' so that to forward requests
790    // from one object to another.
791    // Under such conditions, which means that every method possible is
792    // implemented in the class, we should not issue "Method definition not
793    // found" warnings.
794    // FIXME: Use a general GetUnarySelector method for this.
795    IdentifierInfo* II = &Context.Idents.get("forwardInvocation");
796    Selector fISelector = Context.Selectors.getSelector(1, &II);
797    if (InsMap.count(fISelector))
798      // Is IDecl derived from 'NSProxy'? If so, no instance methods
799      // need be implemented in the implementation.
800      NSIDecl = IDecl->lookupInheritedClass(&Context.Idents.get("NSProxy"));
801  }
802
803  // If a method lookup fails locally we still need to look and see if
804  // the method was implemented by a base class or an inherited
805  // protocol. This lookup is slow, but occurs rarely in correct code
806  // and otherwise would terminate in a warning.
807
808  // check unimplemented instance methods.
809  if (!NSIDecl)
810    for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
811         E = PDecl->instmeth_end(); I != E; ++I) {
812      ObjCMethodDecl *method = *I;
813      if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
814          !method->isSynthesized() && !InsMap.count(method->getSelector()) &&
815          (!Super ||
816           !Super->lookupInstanceMethod(method->getSelector()))) {
817            // Ugly, but necessary. Method declared in protcol might have
818            // have been synthesized due to a property declared in the class which
819            // uses the protocol.
820            ObjCMethodDecl *MethodInClass =
821            IDecl->lookupInstanceMethod(method->getSelector());
822            if (!MethodInClass || !MethodInClass->isSynthesized()) {
823              unsigned DIAG = diag::warn_unimplemented_protocol_method;
824              if (Diags.getDiagnosticLevel(DIAG) != Diagnostic::Ignored) {
825                WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
826                Diag(CDecl->getLocation(), diag::note_required_for_protocol_at)
827                  << PDecl->getDeclName();
828              }
829            }
830          }
831    }
832  // check unimplemented class methods
833  for (ObjCProtocolDecl::classmeth_iterator
834         I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
835       I != E; ++I) {
836    ObjCMethodDecl *method = *I;
837    if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
838        !ClsMap.count(method->getSelector()) &&
839        (!Super || !Super->lookupClassMethod(method->getSelector()))) {
840      unsigned DIAG = diag::warn_unimplemented_protocol_method;
841      if (Diags.getDiagnosticLevel(DIAG) != Diagnostic::Ignored) {
842        WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
843        Diag(IDecl->getLocation(), diag::note_required_for_protocol_at) <<
844          PDecl->getDeclName();
845      }
846    }
847  }
848  // Check on this protocols's referenced protocols, recursively.
849  for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
850       E = PDecl->protocol_end(); PI != E; ++PI)
851    CheckProtocolMethodDefs(ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap, IDecl);
852}
853
854/// MatchAllMethodDeclarations - Check methods declaraed in interface or
855/// or protocol against those declared in their implementations.
856///
857void Sema::MatchAllMethodDeclarations(const llvm::DenseSet<Selector> &InsMap,
858                                      const llvm::DenseSet<Selector> &ClsMap,
859                                      llvm::DenseSet<Selector> &InsMapSeen,
860                                      llvm::DenseSet<Selector> &ClsMapSeen,
861                                      ObjCImplDecl* IMPDecl,
862                                      ObjCContainerDecl* CDecl,
863                                      bool &IncompleteImpl,
864                                      bool ImmediateClass) {
865  // Check and see if instance methods in class interface have been
866  // implemented in the implementation class. If so, their types match.
867  for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(),
868       E = CDecl->instmeth_end(); I != E; ++I) {
869    if (InsMapSeen.count((*I)->getSelector()))
870        continue;
871    InsMapSeen.insert((*I)->getSelector());
872    if (!(*I)->isSynthesized() &&
873        !InsMap.count((*I)->getSelector())) {
874      if (ImmediateClass)
875        WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl,
876                            diag::note_undef_method_impl);
877      continue;
878    } else {
879      ObjCMethodDecl *ImpMethodDecl =
880      IMPDecl->getInstanceMethod((*I)->getSelector());
881      ObjCMethodDecl *IntfMethodDecl =
882      CDecl->getInstanceMethod((*I)->getSelector());
883      assert(IntfMethodDecl &&
884             "IntfMethodDecl is null in ImplMethodsVsClassMethods");
885      // ImpMethodDecl may be null as in a @dynamic property.
886      if (ImpMethodDecl)
887        WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl);
888    }
889  }
890
891  // Check and see if class methods in class interface have been
892  // implemented in the implementation class. If so, their types match.
893   for (ObjCInterfaceDecl::classmeth_iterator
894       I = CDecl->classmeth_begin(), E = CDecl->classmeth_end(); I != E; ++I) {
895     if (ClsMapSeen.count((*I)->getSelector()))
896       continue;
897     ClsMapSeen.insert((*I)->getSelector());
898    if (!ClsMap.count((*I)->getSelector())) {
899      if (ImmediateClass)
900        WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl,
901                            diag::note_undef_method_impl);
902    } else {
903      ObjCMethodDecl *ImpMethodDecl =
904        IMPDecl->getClassMethod((*I)->getSelector());
905      ObjCMethodDecl *IntfMethodDecl =
906        CDecl->getClassMethod((*I)->getSelector());
907      WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl);
908    }
909  }
910  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
911    // Check for any implementation of a methods declared in protocol.
912    for (ObjCInterfaceDecl::protocol_iterator PI = I->protocol_begin(),
913         E = I->protocol_end(); PI != E; ++PI)
914      MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
915                                 IMPDecl,
916                                 (*PI), IncompleteImpl, false);
917    if (I->getSuperClass())
918      MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
919                                 IMPDecl,
920                                 I->getSuperClass(), IncompleteImpl, false);
921  }
922}
923
924void Sema::ImplMethodsVsClassMethods(ObjCImplDecl* IMPDecl,
925                                     ObjCContainerDecl* CDecl,
926                                     bool IncompleteImpl) {
927  llvm::DenseSet<Selector> InsMap;
928  // Check and see if instance methods in class interface have been
929  // implemented in the implementation class.
930  for (ObjCImplementationDecl::instmeth_iterator
931         I = IMPDecl->instmeth_begin(), E = IMPDecl->instmeth_end(); I!=E; ++I)
932    InsMap.insert((*I)->getSelector());
933
934  // Check and see if properties declared in the interface have either 1)
935  // an implementation or 2) there is a @synthesize/@dynamic implementation
936  // of the property in the @implementation.
937  if (isa<ObjCInterfaceDecl>(CDecl))
938    DiagnoseUnimplementedProperties(IMPDecl, CDecl, InsMap);
939
940  llvm::DenseSet<Selector> ClsMap;
941  for (ObjCImplementationDecl::classmeth_iterator
942       I = IMPDecl->classmeth_begin(),
943       E = IMPDecl->classmeth_end(); I != E; ++I)
944    ClsMap.insert((*I)->getSelector());
945
946  // Check for type conflict of methods declared in a class/protocol and
947  // its implementation; if any.
948  llvm::DenseSet<Selector> InsMapSeen, ClsMapSeen;
949  MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
950                             IMPDecl, CDecl,
951                             IncompleteImpl, true);
952
953  // Check the protocol list for unimplemented methods in the @implementation
954  // class.
955  // Check and see if class methods in class interface have been
956  // implemented in the implementation class.
957
958  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
959    for (ObjCInterfaceDecl::protocol_iterator PI = I->protocol_begin(),
960         E = I->protocol_end(); PI != E; ++PI)
961      CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
962                              InsMap, ClsMap, I);
963    // Check class extensions (unnamed categories)
964    for (ObjCCategoryDecl *Categories = I->getCategoryList();
965         Categories; Categories = Categories->getNextClassCategory()) {
966      if (Categories->IsClassExtension()) {
967        ImplMethodsVsClassMethods(IMPDecl, Categories, IncompleteImpl);
968        break;
969      }
970    }
971  } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
972    // For extended class, unimplemented methods in its protocols will
973    // be reported in the primary class.
974    if (!C->IsClassExtension()) {
975      for (ObjCCategoryDecl::protocol_iterator PI = C->protocol_begin(),
976           E = C->protocol_end(); PI != E; ++PI)
977        CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
978                                InsMap, ClsMap, CDecl);
979      // Report unimplemented properties in the category as well.
980      // When reporting on missing setter/getters, do not report when
981      // setter/getter is implemented in category's primary class
982      // implementation.
983      if (ObjCInterfaceDecl *ID = C->getClassInterface())
984        if (ObjCImplDecl *IMP = ID->getImplementation()) {
985          for (ObjCImplementationDecl::instmeth_iterator
986               I = IMP->instmeth_begin(), E = IMP->instmeth_end(); I!=E; ++I)
987            InsMap.insert((*I)->getSelector());
988        }
989      DiagnoseUnimplementedProperties(IMPDecl, CDecl, InsMap);
990    }
991  } else
992    assert(false && "invalid ObjCContainerDecl type.");
993}
994
995/// ActOnForwardClassDeclaration -
996Action::DeclPtrTy
997Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
998                                   IdentifierInfo **IdentList,
999                                   SourceLocation *IdentLocs,
1000                                   unsigned NumElts) {
1001  llvm::SmallVector<ObjCInterfaceDecl*, 32> Interfaces;
1002
1003  for (unsigned i = 0; i != NumElts; ++i) {
1004    // Check for another declaration kind with the same name.
1005    NamedDecl *PrevDecl
1006      = LookupSingleName(TUScope, IdentList[i], LookupOrdinaryName);
1007    if (PrevDecl && PrevDecl->isTemplateParameter()) {
1008      // Maybe we will complain about the shadowed template parameter.
1009      DiagnoseTemplateParameterShadow(AtClassLoc, PrevDecl);
1010      // Just pretend that we didn't see the previous declaration.
1011      PrevDecl = 0;
1012    }
1013
1014    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1015      // GCC apparently allows the following idiom:
1016      //
1017      // typedef NSObject < XCElementTogglerP > XCElementToggler;
1018      // @class XCElementToggler;
1019      //
1020      // FIXME: Make an extension?
1021      TypedefDecl *TDD = dyn_cast<TypedefDecl>(PrevDecl);
1022      if (!TDD || !isa<ObjCInterfaceType>(TDD->getUnderlyingType())) {
1023        Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
1024        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1025      } else if (TDD) {
1026        // a forward class declaration matching a typedef name of a class refers
1027        // to the underlying class.
1028        if (ObjCInterfaceType * OI =
1029              dyn_cast<ObjCInterfaceType>(TDD->getUnderlyingType()))
1030          PrevDecl = OI->getDecl();
1031      }
1032    }
1033    ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
1034    if (!IDecl) {  // Not already seen?  Make a forward decl.
1035      IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
1036                                        IdentList[i], IdentLocs[i], true);
1037
1038      // Push the ObjCInterfaceDecl on the scope chain but do *not* add it to
1039      // the current DeclContext.  This prevents clients that walk DeclContext
1040      // from seeing the imaginary ObjCInterfaceDecl until it is actually
1041      // declared later (if at all).  We also take care to explicitly make
1042      // sure this declaration is visible for name lookup.
1043      PushOnScopeChains(IDecl, TUScope, false);
1044      CurContext->makeDeclVisibleInContext(IDecl, true);
1045    }
1046
1047    Interfaces.push_back(IDecl);
1048  }
1049
1050  assert(Interfaces.size() == NumElts);
1051  ObjCClassDecl *CDecl = ObjCClassDecl::Create(Context, CurContext, AtClassLoc,
1052                                               Interfaces.data(), IdentLocs,
1053                                               Interfaces.size());
1054  CurContext->addDecl(CDecl);
1055  CheckObjCDeclScope(CDecl);
1056  return DeclPtrTy::make(CDecl);
1057}
1058
1059
1060/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
1061/// returns true, or false, accordingly.
1062/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
1063bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
1064                                      const ObjCMethodDecl *PrevMethod,
1065                                      bool matchBasedOnSizeAndAlignment) {
1066  QualType T1 = Context.getCanonicalType(Method->getResultType());
1067  QualType T2 = Context.getCanonicalType(PrevMethod->getResultType());
1068
1069  if (T1 != T2) {
1070    // The result types are different.
1071    if (!matchBasedOnSizeAndAlignment)
1072      return false;
1073    // Incomplete types don't have a size and alignment.
1074    if (T1->isIncompleteType() || T2->isIncompleteType())
1075      return false;
1076    // Check is based on size and alignment.
1077    if (Context.getTypeInfo(T1) != Context.getTypeInfo(T2))
1078      return false;
1079  }
1080
1081  ObjCMethodDecl::param_iterator ParamI = Method->param_begin(),
1082       E = Method->param_end();
1083  ObjCMethodDecl::param_iterator PrevI = PrevMethod->param_begin();
1084
1085  for (; ParamI != E; ++ParamI, ++PrevI) {
1086    assert(PrevI != PrevMethod->param_end() && "Param mismatch");
1087    T1 = Context.getCanonicalType((*ParamI)->getType());
1088    T2 = Context.getCanonicalType((*PrevI)->getType());
1089    if (T1 != T2) {
1090      // The result types are different.
1091      if (!matchBasedOnSizeAndAlignment)
1092        return false;
1093      // Incomplete types don't have a size and alignment.
1094      if (T1->isIncompleteType() || T2->isIncompleteType())
1095        return false;
1096      // Check is based on size and alignment.
1097      if (Context.getTypeInfo(T1) != Context.getTypeInfo(T2))
1098        return false;
1099    }
1100  }
1101  return true;
1102}
1103
1104/// \brief Read the contents of the instance and factory method pools
1105/// for a given selector from external storage.
1106///
1107/// This routine should only be called once, when neither the instance
1108/// nor the factory method pool has an entry for this selector.
1109Sema::MethodPool::iterator Sema::ReadMethodPool(Selector Sel,
1110                                                bool isInstance) {
1111  assert(ExternalSource && "We need an external AST source");
1112  assert(InstanceMethodPool.find(Sel) == InstanceMethodPool.end() &&
1113         "Selector data already loaded into the instance method pool");
1114  assert(FactoryMethodPool.find(Sel) == FactoryMethodPool.end() &&
1115         "Selector data already loaded into the factory method pool");
1116
1117  // Read the method list from the external source.
1118  std::pair<ObjCMethodList, ObjCMethodList> Methods
1119    = ExternalSource->ReadMethodPool(Sel);
1120
1121  if (isInstance) {
1122    if (Methods.second.Method)
1123      FactoryMethodPool[Sel] = Methods.second;
1124    return InstanceMethodPool.insert(std::make_pair(Sel, Methods.first)).first;
1125  }
1126
1127  if (Methods.first.Method)
1128    InstanceMethodPool[Sel] = Methods.first;
1129
1130  return FactoryMethodPool.insert(std::make_pair(Sel, Methods.second)).first;
1131}
1132
1133void Sema::AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method) {
1134  llvm::DenseMap<Selector, ObjCMethodList>::iterator Pos
1135    = InstanceMethodPool.find(Method->getSelector());
1136  if (Pos == InstanceMethodPool.end()) {
1137    if (ExternalSource && !FactoryMethodPool.count(Method->getSelector()))
1138      Pos = ReadMethodPool(Method->getSelector(), /*isInstance=*/true);
1139    else
1140      Pos = InstanceMethodPool.insert(std::make_pair(Method->getSelector(),
1141                                                     ObjCMethodList())).first;
1142  }
1143
1144  ObjCMethodList &Entry = Pos->second;
1145  if (Entry.Method == 0) {
1146    // Haven't seen a method with this selector name yet - add it.
1147    Entry.Method = Method;
1148    Entry.Next = 0;
1149    return;
1150  }
1151
1152  // We've seen a method with this name, see if we have already seen this type
1153  // signature.
1154  for (ObjCMethodList *List = &Entry; List; List = List->Next)
1155    if (MatchTwoMethodDeclarations(Method, List->Method))
1156      return;
1157
1158  // We have a new signature for an existing method - add it.
1159  // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
1160  ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
1161  Entry.Next = new (Mem) ObjCMethodList(Method, Entry.Next);
1162}
1163
1164// FIXME: Finish implementing -Wno-strict-selector-match.
1165ObjCMethodDecl *Sema::LookupInstanceMethodInGlobalPool(Selector Sel,
1166                                                       SourceRange R,
1167                                                       bool warn) {
1168  llvm::DenseMap<Selector, ObjCMethodList>::iterator Pos
1169    = InstanceMethodPool.find(Sel);
1170  if (Pos == InstanceMethodPool.end()) {
1171    if (ExternalSource && !FactoryMethodPool.count(Sel))
1172      Pos = ReadMethodPool(Sel, /*isInstance=*/true);
1173    else
1174      return 0;
1175  }
1176
1177  ObjCMethodList &MethList = Pos->second;
1178  bool issueWarning = false;
1179
1180  if (MethList.Method && MethList.Next) {
1181    for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1182      // This checks if the methods differ by size & alignment.
1183      if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method, true))
1184        issueWarning = warn;
1185  }
1186  if (issueWarning && (MethList.Method && MethList.Next)) {
1187    Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
1188    Diag(MethList.Method->getLocStart(), diag::note_using)
1189      << MethList.Method->getSourceRange();
1190    for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1191      Diag(Next->Method->getLocStart(), diag::note_also_found)
1192        << Next->Method->getSourceRange();
1193  }
1194  return MethList.Method;
1195}
1196
1197void Sema::AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method) {
1198  llvm::DenseMap<Selector, ObjCMethodList>::iterator Pos
1199    = FactoryMethodPool.find(Method->getSelector());
1200  if (Pos == FactoryMethodPool.end()) {
1201    if (ExternalSource && !InstanceMethodPool.count(Method->getSelector()))
1202      Pos = ReadMethodPool(Method->getSelector(), /*isInstance=*/false);
1203    else
1204      Pos = FactoryMethodPool.insert(std::make_pair(Method->getSelector(),
1205                                                    ObjCMethodList())).first;
1206  }
1207
1208  ObjCMethodList &FirstMethod = Pos->second;
1209  if (!FirstMethod.Method) {
1210    // Haven't seen a method with this selector name yet - add it.
1211    FirstMethod.Method = Method;
1212    FirstMethod.Next = 0;
1213  } else {
1214    // We've seen a method with this name, now check the type signature(s).
1215    bool match = MatchTwoMethodDeclarations(Method, FirstMethod.Method);
1216
1217    for (ObjCMethodList *Next = FirstMethod.Next; !match && Next;
1218         Next = Next->Next)
1219      match = MatchTwoMethodDeclarations(Method, Next->Method);
1220
1221    if (!match) {
1222      // We have a new signature for an existing method - add it.
1223      // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
1224      ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
1225      ObjCMethodList *OMI = new (Mem) ObjCMethodList(Method, FirstMethod.Next);
1226      FirstMethod.Next = OMI;
1227    }
1228  }
1229}
1230
1231ObjCMethodDecl *Sema::LookupFactoryMethodInGlobalPool(Selector Sel,
1232                                                      SourceRange R) {
1233  llvm::DenseMap<Selector, ObjCMethodList>::iterator Pos
1234    = FactoryMethodPool.find(Sel);
1235  if (Pos == FactoryMethodPool.end()) {
1236    if (ExternalSource && !InstanceMethodPool.count(Sel))
1237      Pos = ReadMethodPool(Sel, /*isInstance=*/false);
1238    else
1239      return 0;
1240  }
1241
1242  ObjCMethodList &MethList = Pos->second;
1243  bool issueWarning = false;
1244
1245  if (MethList.Method && MethList.Next) {
1246    for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1247      // This checks if the methods differ by size & alignment.
1248      if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method, true))
1249        issueWarning = true;
1250  }
1251  if (issueWarning && (MethList.Method && MethList.Next)) {
1252    Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
1253    Diag(MethList.Method->getLocStart(), diag::note_using)
1254      << MethList.Method->getSourceRange();
1255    for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1256      Diag(Next->Method->getLocStart(), diag::note_also_found)
1257        << Next->Method->getSourceRange();
1258  }
1259  return MethList.Method;
1260}
1261
1262/// CompareMethodParamsInBaseAndSuper - This routine compares methods with
1263/// identical selector names in current and its super classes and issues
1264/// a warning if any of their argument types are incompatible.
1265void Sema::CompareMethodParamsInBaseAndSuper(Decl *ClassDecl,
1266                                             ObjCMethodDecl *Method,
1267                                             bool IsInstance)  {
1268  ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
1269  if (ID == 0) return;
1270
1271  while (ObjCInterfaceDecl *SD = ID->getSuperClass()) {
1272    ObjCMethodDecl *SuperMethodDecl =
1273        SD->lookupMethod(Method->getSelector(), IsInstance);
1274    if (SuperMethodDecl == 0) {
1275      ID = SD;
1276      continue;
1277    }
1278    ObjCMethodDecl::param_iterator ParamI = Method->param_begin(),
1279      E = Method->param_end();
1280    ObjCMethodDecl::param_iterator PrevI = SuperMethodDecl->param_begin();
1281    for (; ParamI != E; ++ParamI, ++PrevI) {
1282      // Number of parameters are the same and is guaranteed by selector match.
1283      assert(PrevI != SuperMethodDecl->param_end() && "Param mismatch");
1284      QualType T1 = Context.getCanonicalType((*ParamI)->getType());
1285      QualType T2 = Context.getCanonicalType((*PrevI)->getType());
1286      // If type of arguement of method in this class does not match its
1287      // respective argument type in the super class method, issue warning;
1288      if (!Context.typesAreCompatible(T1, T2)) {
1289        Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
1290          << T1 << T2;
1291        Diag(SuperMethodDecl->getLocation(), diag::note_previous_declaration);
1292        return;
1293      }
1294    }
1295    ID = SD;
1296  }
1297}
1298
1299/// DiagnoseDuplicateIvars -
1300/// Check for duplicate ivars in the entire class at the start of
1301/// @implementation. This becomes necesssary because class extension can
1302/// add ivars to a class in random order which will not be known until
1303/// class's @implementation is seen.
1304void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
1305                                  ObjCInterfaceDecl *SID) {
1306  for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
1307       IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
1308    ObjCIvarDecl* Ivar = (*IVI);
1309    if (Ivar->isInvalidDecl())
1310      continue;
1311    if (IdentifierInfo *II = Ivar->getIdentifier()) {
1312      ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
1313      if (prevIvar) {
1314        Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
1315        Diag(prevIvar->getLocation(), diag::note_previous_declaration);
1316        Ivar->setInvalidDecl();
1317      }
1318    }
1319  }
1320}
1321
1322// Note: For class/category implemenations, allMethods/allProperties is
1323// always null.
1324void Sema::ActOnAtEnd(SourceRange AtEnd,
1325                      DeclPtrTy classDecl,
1326                      DeclPtrTy *allMethods, unsigned allNum,
1327                      DeclPtrTy *allProperties, unsigned pNum,
1328                      DeclGroupPtrTy *allTUVars, unsigned tuvNum) {
1329  Decl *ClassDecl = classDecl.getAs<Decl>();
1330
1331  // FIXME: If we don't have a ClassDecl, we have an error. We should consider
1332  // always passing in a decl. If the decl has an error, isInvalidDecl()
1333  // should be true.
1334  if (!ClassDecl)
1335    return;
1336
1337  bool isInterfaceDeclKind =
1338        isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
1339         || isa<ObjCProtocolDecl>(ClassDecl);
1340  bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
1341
1342  if (!isInterfaceDeclKind && AtEnd.isInvalid()) {
1343    // FIXME: This is wrong.  We shouldn't be pretending that there is
1344    //  an '@end' in the declaration.
1345    SourceLocation L = ClassDecl->getLocation();
1346    AtEnd.setBegin(L);
1347    AtEnd.setEnd(L);
1348    Diag(L, diag::warn_missing_atend);
1349  }
1350
1351  DeclContext *DC = dyn_cast<DeclContext>(ClassDecl);
1352
1353  // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
1354  llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
1355  llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
1356
1357  for (unsigned i = 0; i < allNum; i++ ) {
1358    ObjCMethodDecl *Method =
1359      cast_or_null<ObjCMethodDecl>(allMethods[i].getAs<Decl>());
1360
1361    if (!Method) continue;  // Already issued a diagnostic.
1362    if (Method->isInstanceMethod()) {
1363      /// Check for instance method of the same name with incompatible types
1364      const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
1365      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
1366                              : false;
1367      if ((isInterfaceDeclKind && PrevMethod && !match)
1368          || (checkIdenticalMethods && match)) {
1369          Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1370            << Method->getDeclName();
1371          Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1372      } else {
1373        DC->addDecl(Method);
1374        InsMap[Method->getSelector()] = Method;
1375        /// The following allows us to typecheck messages to "id".
1376        AddInstanceMethodToGlobalPool(Method);
1377        // verify that the instance method conforms to the same definition of
1378        // parent methods if it shadows one.
1379        CompareMethodParamsInBaseAndSuper(ClassDecl, Method, true);
1380      }
1381    } else {
1382      /// Check for class method of the same name with incompatible types
1383      const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
1384      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
1385                              : false;
1386      if ((isInterfaceDeclKind && PrevMethod && !match)
1387          || (checkIdenticalMethods && match)) {
1388        Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1389          << Method->getDeclName();
1390        Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1391      } else {
1392        DC->addDecl(Method);
1393        ClsMap[Method->getSelector()] = Method;
1394        /// The following allows us to typecheck messages to "Class".
1395        AddFactoryMethodToGlobalPool(Method);
1396        // verify that the class method conforms to the same definition of
1397        // parent methods if it shadows one.
1398        CompareMethodParamsInBaseAndSuper(ClassDecl, Method, false);
1399      }
1400    }
1401  }
1402  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
1403    // Compares properties declared in this class to those of its
1404    // super class.
1405    ComparePropertiesInBaseAndSuper(I);
1406    CompareProperties(I, DeclPtrTy::make(I));
1407  } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
1408    // Categories are used to extend the class by declaring new methods.
1409    // By the same token, they are also used to add new properties. No
1410    // need to compare the added property to those in the class.
1411
1412    // Compare protocol properties with those in category
1413    CompareProperties(C, DeclPtrTy::make(C));
1414    if (C->IsClassExtension())
1415      DiagnoseClassExtensionDupMethods(C, C->getClassInterface());
1416  }
1417  if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
1418    if (CDecl->getIdentifier())
1419      // ProcessPropertyDecl is responsible for diagnosing conflicts with any
1420      // user-defined setter/getter. It also synthesizes setter/getter methods
1421      // and adds them to the DeclContext and global method pools.
1422      for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
1423                                            E = CDecl->prop_end();
1424           I != E; ++I)
1425        ProcessPropertyDecl(*I, CDecl);
1426    CDecl->setAtEndRange(AtEnd);
1427  }
1428  if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
1429    IC->setAtEndRange(AtEnd);
1430    if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
1431      ImplMethodsVsClassMethods(IC, IDecl);
1432      AtomicPropertySetterGetterRules(IC, IDecl);
1433      if (LangOpts.ObjCNonFragileABI2)
1434        while (IDecl->getSuperClass()) {
1435          DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
1436          IDecl = IDecl->getSuperClass();
1437        }
1438    }
1439  } else if (ObjCCategoryImplDecl* CatImplClass =
1440                                   dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
1441    CatImplClass->setAtEndRange(AtEnd);
1442
1443    // Find category interface decl and then check that all methods declared
1444    // in this interface are implemented in the category @implementation.
1445    if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
1446      for (ObjCCategoryDecl *Categories = IDecl->getCategoryList();
1447           Categories; Categories = Categories->getNextClassCategory()) {
1448        if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
1449          ImplMethodsVsClassMethods(CatImplClass, Categories);
1450          break;
1451        }
1452      }
1453    }
1454  }
1455  if (isInterfaceDeclKind) {
1456    // Reject invalid vardecls.
1457    for (unsigned i = 0; i != tuvNum; i++) {
1458      DeclGroupRef DG = allTUVars[i].getAsVal<DeclGroupRef>();
1459      for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
1460        if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
1461          if (!VDecl->hasExternalStorage())
1462            Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
1463        }
1464    }
1465  }
1466}
1467
1468
1469/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
1470/// objective-c's type qualifier from the parser version of the same info.
1471static Decl::ObjCDeclQualifier
1472CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
1473  Decl::ObjCDeclQualifier ret = Decl::OBJC_TQ_None;
1474  if (PQTVal & ObjCDeclSpec::DQ_In)
1475    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_In);
1476  if (PQTVal & ObjCDeclSpec::DQ_Inout)
1477    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Inout);
1478  if (PQTVal & ObjCDeclSpec::DQ_Out)
1479    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Out);
1480  if (PQTVal & ObjCDeclSpec::DQ_Bycopy)
1481    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Bycopy);
1482  if (PQTVal & ObjCDeclSpec::DQ_Byref)
1483    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Byref);
1484  if (PQTVal & ObjCDeclSpec::DQ_Oneway)
1485    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Oneway);
1486
1487  return ret;
1488}
1489
1490Sema::DeclPtrTy Sema::ActOnMethodDeclaration(
1491    SourceLocation MethodLoc, SourceLocation EndLoc,
1492    tok::TokenKind MethodType, DeclPtrTy classDecl,
1493    ObjCDeclSpec &ReturnQT, TypeTy *ReturnType,
1494    Selector Sel,
1495    // optional arguments. The number of types/arguments is obtained
1496    // from the Sel.getNumArgs().
1497    ObjCArgInfo *ArgInfo,
1498    llvm::SmallVectorImpl<Declarator> &Cdecls,
1499    AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
1500    bool isVariadic) {
1501  Decl *ClassDecl = classDecl.getAs<Decl>();
1502
1503  // Make sure we can establish a context for the method.
1504  if (!ClassDecl) {
1505    Diag(MethodLoc, diag::error_missing_method_context);
1506    getLabelMap().clear();
1507    return DeclPtrTy();
1508  }
1509  QualType resultDeclType;
1510
1511  TypeSourceInfo *ResultTInfo = 0;
1512  if (ReturnType) {
1513    resultDeclType = GetTypeFromParser(ReturnType, &ResultTInfo);
1514
1515    // Methods cannot return interface types. All ObjC objects are
1516    // passed by reference.
1517    if (resultDeclType->isObjCInterfaceType()) {
1518      Diag(MethodLoc, diag::err_object_cannot_be_passed_returned_by_value)
1519        << 0 << resultDeclType;
1520      return DeclPtrTy();
1521    }
1522  } else // get the type for "id".
1523    resultDeclType = Context.getObjCIdType();
1524
1525  ObjCMethodDecl* ObjCMethod =
1526    ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel, resultDeclType,
1527                           ResultTInfo,
1528                           cast<DeclContext>(ClassDecl),
1529                           MethodType == tok::minus, isVariadic,
1530                           false,
1531                           MethodDeclKind == tok::objc_optional ?
1532                           ObjCMethodDecl::Optional :
1533                           ObjCMethodDecl::Required);
1534
1535  llvm::SmallVector<ParmVarDecl*, 16> Params;
1536
1537  for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
1538    QualType ArgType;
1539    TypeSourceInfo *DI;
1540
1541    if (ArgInfo[i].Type == 0) {
1542      ArgType = Context.getObjCIdType();
1543      DI = 0;
1544    } else {
1545      ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
1546      // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
1547      ArgType = adjustParameterType(ArgType);
1548    }
1549
1550    ParmVarDecl* Param
1551      = ParmVarDecl::Create(Context, ObjCMethod, ArgInfo[i].NameLoc,
1552                            ArgInfo[i].Name, ArgType, DI,
1553                            VarDecl::None, 0);
1554
1555    if (ArgType->isObjCInterfaceType()) {
1556      Diag(ArgInfo[i].NameLoc,
1557           diag::err_object_cannot_be_passed_returned_by_value)
1558        << 1 << ArgType;
1559      Param->setInvalidDecl();
1560    }
1561
1562    Param->setObjCDeclQualifier(
1563      CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
1564
1565    // Apply the attributes to the parameter.
1566    ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
1567
1568    Params.push_back(Param);
1569  }
1570
1571  ObjCMethod->setMethodParams(Context, Params.data(), Sel.getNumArgs());
1572  ObjCMethod->setObjCDeclQualifier(
1573    CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
1574  const ObjCMethodDecl *PrevMethod = 0;
1575
1576  if (AttrList)
1577    ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
1578
1579  const ObjCMethodDecl *InterfaceMD = 0;
1580
1581  // For implementations (which can be very "coarse grain"), we add the
1582  // method now. This allows the AST to implement lookup methods that work
1583  // incrementally (without waiting until we parse the @end). It also allows
1584  // us to flag multiple declaration errors as they occur.
1585  if (ObjCImplementationDecl *ImpDecl =
1586        dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
1587    if (MethodType == tok::minus) {
1588      PrevMethod = ImpDecl->getInstanceMethod(Sel);
1589      ImpDecl->addInstanceMethod(ObjCMethod);
1590    } else {
1591      PrevMethod = ImpDecl->getClassMethod(Sel);
1592      ImpDecl->addClassMethod(ObjCMethod);
1593    }
1594    InterfaceMD = ImpDecl->getClassInterface()->getMethod(Sel,
1595                                                   MethodType == tok::minus);
1596    if (AttrList)
1597      Diag(EndLoc, diag::warn_attribute_method_def);
1598  } else if (ObjCCategoryImplDecl *CatImpDecl =
1599             dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
1600    if (MethodType == tok::minus) {
1601      PrevMethod = CatImpDecl->getInstanceMethod(Sel);
1602      CatImpDecl->addInstanceMethod(ObjCMethod);
1603    } else {
1604      PrevMethod = CatImpDecl->getClassMethod(Sel);
1605      CatImpDecl->addClassMethod(ObjCMethod);
1606    }
1607    if (AttrList)
1608      Diag(EndLoc, diag::warn_attribute_method_def);
1609  }
1610  if (PrevMethod) {
1611    // You can never have two method definitions with the same name.
1612    Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
1613      << ObjCMethod->getDeclName();
1614    Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1615  }
1616
1617  // If the interface declared this method, and it was deprecated there,
1618  // mark it deprecated here.
1619  if (InterfaceMD && InterfaceMD->hasAttr<DeprecatedAttr>())
1620    ObjCMethod->addAttr(::new (Context) DeprecatedAttr());
1621
1622  return DeclPtrTy::make(ObjCMethod);
1623}
1624
1625bool Sema::CheckObjCDeclScope(Decl *D) {
1626  if (isa<TranslationUnitDecl>(CurContext->getLookupContext()))
1627    return false;
1628
1629  Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
1630  D->setInvalidDecl();
1631
1632  return true;
1633}
1634
1635/// Called whenever @defs(ClassName) is encountered in the source.  Inserts the
1636/// instance variables of ClassName into Decls.
1637void Sema::ActOnDefs(Scope *S, DeclPtrTy TagD, SourceLocation DeclStart,
1638                     IdentifierInfo *ClassName,
1639                     llvm::SmallVectorImpl<DeclPtrTy> &Decls) {
1640  // Check that ClassName is a valid class
1641  ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
1642  if (!Class) {
1643    Diag(DeclStart, diag::err_undef_interface) << ClassName;
1644    return;
1645  }
1646  if (LangOpts.ObjCNonFragileABI) {
1647    Diag(DeclStart, diag::err_atdef_nonfragile_interface);
1648    return;
1649  }
1650
1651  // Collect the instance variables
1652  llvm::SmallVector<FieldDecl*, 32> RecFields;
1653  Context.CollectObjCIvars(Class, RecFields);
1654  // For each ivar, create a fresh ObjCAtDefsFieldDecl.
1655  for (unsigned i = 0; i < RecFields.size(); i++) {
1656    FieldDecl* ID = RecFields[i];
1657    RecordDecl *Record = dyn_cast<RecordDecl>(TagD.getAs<Decl>());
1658    Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record, ID->getLocation(),
1659                                           ID->getIdentifier(), ID->getType(),
1660                                           ID->getBitWidth());
1661    Decls.push_back(Sema::DeclPtrTy::make(FD));
1662  }
1663
1664  // Introduce all of these fields into the appropriate scope.
1665  for (llvm::SmallVectorImpl<DeclPtrTy>::iterator D = Decls.begin();
1666       D != Decls.end(); ++D) {
1667    FieldDecl *FD = cast<FieldDecl>(D->getAs<Decl>());
1668    if (getLangOptions().CPlusPlus)
1669      PushOnScopeChains(cast<FieldDecl>(FD), S);
1670    else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD.getAs<Decl>()))
1671      Record->addDecl(FD);
1672  }
1673}
1674
1675