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