1 //===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for Objective C declarations.
12 //===----------------------------------------------------------------------===//
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/AST/ASTMutationListener.h"
25 #include "clang/Basic/SourceManager.h"
26 #include "clang/Sema/DeclSpec.h"
27 #include "clang/Lex/Preprocessor.h"
28 #include "llvm/ADT/DenseSet.h"
30 using namespace clang;
32 /// Check whether the given method, which must be in the 'init'
33 /// family, is a valid member of that family.
35 /// \param receiverTypeIfCall - if null, check this as if declaring it;
36 /// if non-null, check this as if making a call to it with the given
39 /// \return true to indicate that there was an error and appropriate
40 /// actions were taken
41 bool Sema::checkInitMethod(ObjCMethodDecl *method,
42 QualType receiverTypeIfCall) {
43 if (method->isInvalidDecl()) return true;
45 // This castAs is safe: methods that don't return an object
46 // pointer won't be inferred as inits and will reject an explicit
47 // objc_method_family(init).
49 // We ignore protocols here. Should we? What about Class?
51 const ObjCObjectType *result = method->getResultType()
52 ->castAs<ObjCObjectPointerType>()->getObjectType();
54 if (result->isObjCId()) {
56 } else if (result->isObjCClass()) {
57 // fall through: always an error
59 ObjCInterfaceDecl *resultClass = result->getInterface();
60 assert(resultClass && "unexpected object type!");
62 // It's okay for the result type to still be a forward declaration
63 // if we're checking an interface declaration.
64 if (!resultClass->hasDefinition()) {
65 if (receiverTypeIfCall.isNull() &&
66 !isa<ObjCImplementationDecl>(method->getDeclContext()))
69 // Otherwise, we try to compare class types.
71 // If this method was declared in a protocol, we can't check
72 // anything unless we have a receiver type that's an interface.
73 const ObjCInterfaceDecl *receiverClass = 0;
74 if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
75 if (receiverTypeIfCall.isNull())
78 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
81 // This can be null for calls to e.g. id<Foo>.
82 if (!receiverClass) return false;
84 receiverClass = method->getClassInterface();
85 assert(receiverClass && "method not associated with a class!");
88 // If either class is a subclass of the other, it's fine.
89 if (receiverClass->isSuperClassOf(resultClass) ||
90 resultClass->isSuperClassOf(receiverClass))
95 SourceLocation loc = method->getLocation();
97 // If we're in a system header, and this is not a call, just make
98 // the method unusable.
99 if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
100 method->addAttr(new (Context) UnavailableAttr(loc, Context,
101 "init method returns a type unrelated to its receiver type"));
105 // Otherwise, it's an error.
106 Diag(loc, diag::err_arc_init_method_unrelated_result_type);
107 method->setInvalidDecl();
111 void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
112 const ObjCMethodDecl *Overridden,
113 bool IsImplementation) {
114 if (Overridden->hasRelatedResultType() &&
115 !NewMethod->hasRelatedResultType()) {
116 // This can only happen when the method follows a naming convention that
117 // implies a related result type, and the original (overridden) method has
118 // a suitable return type, but the new (overriding) method does not have
119 // a suitable return type.
120 QualType ResultType = NewMethod->getResultType();
121 SourceRange ResultTypeRange;
122 if (const TypeSourceInfo *ResultTypeInfo
123 = NewMethod->getResultTypeSourceInfo())
124 ResultTypeRange = ResultTypeInfo->getTypeLoc().getSourceRange();
126 // Figure out which class this method is part of, if any.
127 ObjCInterfaceDecl *CurrentClass
128 = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
130 DeclContext *DC = NewMethod->getDeclContext();
131 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
132 CurrentClass = Cat->getClassInterface();
133 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
134 CurrentClass = Impl->getClassInterface();
135 else if (ObjCCategoryImplDecl *CatImpl
136 = dyn_cast<ObjCCategoryImplDecl>(DC))
137 CurrentClass = CatImpl->getClassInterface();
141 Diag(NewMethod->getLocation(),
142 diag::warn_related_result_type_compatibility_class)
143 << Context.getObjCInterfaceType(CurrentClass)
147 Diag(NewMethod->getLocation(),
148 diag::warn_related_result_type_compatibility_protocol)
153 if (ObjCMethodFamily Family = Overridden->getMethodFamily())
154 Diag(Overridden->getLocation(),
155 diag::note_related_result_type_overridden_family)
158 Diag(Overridden->getLocation(),
159 diag::note_related_result_type_overridden);
161 if (getLangOpts().ObjCAutoRefCount) {
162 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
163 Overridden->hasAttr<NSReturnsRetainedAttr>())) {
164 Diag(NewMethod->getLocation(),
165 diag::err_nsreturns_retained_attribute_mismatch) << 1;
166 Diag(Overridden->getLocation(), diag::note_previous_decl)
169 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
170 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
171 Diag(NewMethod->getLocation(),
172 diag::err_nsreturns_retained_attribute_mismatch) << 0;
173 Diag(Overridden->getLocation(), diag::note_previous_decl)
176 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin();
177 for (ObjCMethodDecl::param_iterator
178 ni = NewMethod->param_begin(), ne = NewMethod->param_end();
179 ni != ne; ++ni, ++oi) {
180 const ParmVarDecl *oldDecl = (*oi);
181 ParmVarDecl *newDecl = (*ni);
182 if (newDecl->hasAttr<NSConsumedAttr>() !=
183 oldDecl->hasAttr<NSConsumedAttr>()) {
184 Diag(newDecl->getLocation(),
185 diag::err_nsconsumed_attribute_mismatch);
186 Diag(oldDecl->getLocation(), diag::note_previous_decl)
193 /// \brief Check a method declaration for compatibility with the Objective-C
195 static bool CheckARCMethodDecl(Sema &S, ObjCMethodDecl *method) {
196 ObjCMethodFamily family = method->getMethodFamily();
203 case OMF_autorelease:
204 case OMF_retainCount:
206 case OMF_performSelector:
210 // If the method doesn't obey the init rules, don't bother annotating it.
211 if (S.checkInitMethod(method, QualType()))
214 method->addAttr(new (S.Context) NSConsumesSelfAttr(SourceLocation(),
217 // Don't add a second copy of this attribute, but otherwise don't
218 // let it be suppressed.
219 if (method->hasAttr<NSReturnsRetainedAttr>())
225 case OMF_mutableCopy:
227 if (method->hasAttr<NSReturnsRetainedAttr>() ||
228 method->hasAttr<NSReturnsNotRetainedAttr>() ||
229 method->hasAttr<NSReturnsAutoreleasedAttr>())
234 method->addAttr(new (S.Context) NSReturnsRetainedAttr(SourceLocation(),
239 static void DiagnoseObjCImplementedDeprecations(Sema &S,
241 SourceLocation ImplLoc,
243 if (ND && ND->isDeprecated()) {
244 S.Diag(ImplLoc, diag::warn_deprecated_def) << select;
246 S.Diag(ND->getLocation(), diag::note_method_declared_at)
247 << ND->getDeclName();
249 S.Diag(ND->getLocation(), diag::note_previous_decl) << "class";
253 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
255 void Sema::AddAnyMethodToGlobalPool(Decl *D) {
256 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
258 // If we don't have a valid method decl, simply return.
261 if (MDecl->isInstanceMethod())
262 AddInstanceMethodToGlobalPool(MDecl, true);
264 AddFactoryMethodToGlobalPool(MDecl, true);
267 /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
268 /// and user declared, in the method definition's AST.
269 void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
270 assert(getCurMethodDecl() == 0 && "Method parsing confused");
271 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
273 // If we don't have a valid method decl, simply return.
277 // Allow all of Sema to see that we are entering a method definition.
278 PushDeclContext(FnBodyScope, MDecl);
281 // Create Decl objects for each parameter, entrring them in the scope for
282 // binding to their use.
284 // Insert the invisible arguments, self and _cmd!
285 MDecl->createImplicitParams(Context, MDecl->getClassInterface());
287 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
288 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
290 // Introduce all of the other parameters into this scope.
291 for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
292 E = MDecl->param_end(); PI != E; ++PI) {
293 ParmVarDecl *Param = (*PI);
294 if (!Param->isInvalidDecl() &&
295 RequireCompleteType(Param->getLocation(), Param->getType(),
296 diag::err_typecheck_decl_incomplete_type))
297 Param->setInvalidDecl();
298 if ((*PI)->getIdentifier())
299 PushOnScopeChains(*PI, FnBodyScope);
302 // In ARC, disallow definition of retain/release/autorelease/retainCount
303 if (getLangOpts().ObjCAutoRefCount) {
304 switch (MDecl->getMethodFamily()) {
306 case OMF_retainCount:
308 case OMF_autorelease:
309 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
310 << MDecl->getSelector();
318 case OMF_mutableCopy:
322 case OMF_performSelector:
327 // Warn on deprecated methods under -Wdeprecated-implementations,
328 // and prepare for warning on missing super calls.
329 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
330 if (ObjCMethodDecl *IMD =
331 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod()))
332 DiagnoseObjCImplementedDeprecations(*this,
333 dyn_cast<NamedDecl>(IMD),
334 MDecl->getLocation(), 0);
336 // If this is "dealloc" or "finalize", set some bit here.
337 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
338 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
339 // Only do this if the current class actually has a superclass.
340 if (IC->getSuperClass()) {
341 ObjCShouldCallSuperDealloc =
342 !(Context.getLangOpts().ObjCAutoRefCount ||
343 Context.getLangOpts().getGC() == LangOptions::GCOnly) &&
344 MDecl->getMethodFamily() == OMF_dealloc;
345 ObjCShouldCallSuperFinalize =
346 Context.getLangOpts().getGC() != LangOptions::NonGC &&
347 MDecl->getMethodFamily() == OMF_finalize;
354 // Callback to only accept typo corrections that are Objective-C classes.
355 // If an ObjCInterfaceDecl* is given to the constructor, then the validation
356 // function will reject corrections to that class.
357 class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback {
359 ObjCInterfaceValidatorCCC() : CurrentIDecl(0) {}
360 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
361 : CurrentIDecl(IDecl) {}
363 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
364 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
365 return ID && !declaresSameEntity(ID, CurrentIDecl);
369 ObjCInterfaceDecl *CurrentIDecl;
375 ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
376 IdentifierInfo *ClassName, SourceLocation ClassLoc,
377 IdentifierInfo *SuperName, SourceLocation SuperLoc,
378 Decl * const *ProtoRefs, unsigned NumProtoRefs,
379 const SourceLocation *ProtoLocs,
380 SourceLocation EndProtoLoc, AttributeList *AttrList) {
381 assert(ClassName && "Missing class identifier");
383 // Check for another declaration kind with the same name.
384 NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
385 LookupOrdinaryName, ForRedeclaration);
387 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
388 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
389 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
392 // Create a declaration to describe this @interface.
393 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
394 ObjCInterfaceDecl *IDecl
395 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
396 PrevIDecl, ClassLoc);
399 // Class already seen. Was it a definition?
400 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
401 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
402 << PrevIDecl->getDeclName();
403 Diag(Def->getLocation(), diag::note_previous_definition);
404 IDecl->setInvalidDecl();
409 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
410 PushOnScopeChains(IDecl, TUScope);
412 // Start the definition of this class. If we're in a redefinition case, there
413 // may already be a definition, so we'll end up adding to it.
414 if (!IDecl->hasDefinition())
415 IDecl->startDefinition();
418 // Check if a different kind of symbol declared in this scope.
419 PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
423 // Try to correct for a typo in the superclass name without correcting
424 // to the class we're defining.
425 ObjCInterfaceValidatorCCC Validator(IDecl);
426 if (TypoCorrection Corrected = CorrectTypo(
427 DeclarationNameInfo(SuperName, SuperLoc), LookupOrdinaryName, TUScope,
429 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
430 Diag(SuperLoc, diag::err_undef_superclass_suggest)
431 << SuperName << ClassName << PrevDecl->getDeclName();
432 Diag(PrevDecl->getLocation(), diag::note_previous_decl)
433 << PrevDecl->getDeclName();
437 if (declaresSameEntity(PrevDecl, IDecl)) {
438 Diag(SuperLoc, diag::err_recursive_superclass)
439 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
440 IDecl->setEndOfDefinitionLoc(ClassLoc);
442 ObjCInterfaceDecl *SuperClassDecl =
443 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
445 // Diagnose classes that inherit from deprecated classes.
447 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
449 if (PrevDecl && SuperClassDecl == 0) {
450 // The previous declaration was not a class decl. Check if we have a
451 // typedef. If we do, get the underlying class type.
452 if (const TypedefNameDecl *TDecl =
453 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
454 QualType T = TDecl->getUnderlyingType();
455 if (T->isObjCObjectType()) {
456 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface())
457 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
461 // This handles the following case:
463 // typedef int SuperClass;
464 // @interface MyClass : SuperClass {} @end
466 if (!SuperClassDecl) {
467 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
468 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
472 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
474 Diag(SuperLoc, diag::err_undef_superclass)
475 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
476 else if (RequireCompleteType(SuperLoc,
477 Context.getObjCInterfaceType(SuperClassDecl),
478 PDiag(diag::err_forward_superclass)
479 << SuperClassDecl->getDeclName()
481 << SourceRange(AtInterfaceLoc, ClassLoc))) {
485 IDecl->setSuperClass(SuperClassDecl);
486 IDecl->setSuperClassLoc(SuperLoc);
487 IDecl->setEndOfDefinitionLoc(SuperLoc);
489 } else { // we have a root class.
490 IDecl->setEndOfDefinitionLoc(ClassLoc);
493 // Check then save referenced protocols.
495 IDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
497 IDecl->setEndOfDefinitionLoc(EndProtoLoc);
500 CheckObjCDeclScope(IDecl);
501 return ActOnObjCContainerStartDefinition(IDecl);
504 /// ActOnCompatiblityAlias - this action is called after complete parsing of
505 /// @compatibility_alias declaration. It sets up the alias relationships.
506 Decl *Sema::ActOnCompatiblityAlias(SourceLocation AtLoc,
507 IdentifierInfo *AliasName,
508 SourceLocation AliasLocation,
509 IdentifierInfo *ClassName,
510 SourceLocation ClassLocation) {
511 // Look for previous declaration of alias name
512 NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
513 LookupOrdinaryName, ForRedeclaration);
515 if (isa<ObjCCompatibleAliasDecl>(ADecl))
516 Diag(AliasLocation, diag::warn_previous_alias_decl);
518 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
519 Diag(ADecl->getLocation(), diag::note_previous_declaration);
522 // Check for class declaration
523 NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
524 LookupOrdinaryName, ForRedeclaration);
525 if (const TypedefNameDecl *TDecl =
526 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
527 QualType T = TDecl->getUnderlyingType();
528 if (T->isObjCObjectType()) {
529 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
530 ClassName = IDecl->getIdentifier();
531 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
532 LookupOrdinaryName, ForRedeclaration);
536 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
538 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
540 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
544 // Everything checked out, instantiate a new alias declaration AST.
545 ObjCCompatibleAliasDecl *AliasDecl =
546 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
548 if (!CheckObjCDeclScope(AliasDecl))
549 PushOnScopeChains(AliasDecl, TUScope);
554 bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
555 IdentifierInfo *PName,
556 SourceLocation &Ploc, SourceLocation PrevLoc,
557 const ObjCList<ObjCProtocolDecl> &PList) {
560 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
561 E = PList.end(); I != E; ++I) {
562 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
564 if (PDecl->getIdentifier() == PName) {
565 Diag(Ploc, diag::err_protocol_has_circular_dependency);
566 Diag(PrevLoc, diag::note_previous_definition);
570 if (!PDecl->hasDefinition())
573 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
574 PDecl->getLocation(), PDecl->getReferencedProtocols()))
582 Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
583 IdentifierInfo *ProtocolName,
584 SourceLocation ProtocolLoc,
585 Decl * const *ProtoRefs,
586 unsigned NumProtoRefs,
587 const SourceLocation *ProtoLocs,
588 SourceLocation EndProtoLoc,
589 AttributeList *AttrList) {
591 // FIXME: Deal with AttrList.
592 assert(ProtocolName && "Missing protocol identifier");
593 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
595 ObjCProtocolDecl *PDecl = 0;
596 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : 0) {
597 // If we already have a definition, complain.
598 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
599 Diag(Def->getLocation(), diag::note_previous_definition);
601 // Create a new protocol that is completely distinct from previous
602 // declarations, and do not make this protocol available for name lookup.
603 // That way, we'll end up completely ignoring the duplicate.
604 // FIXME: Can we turn this into an error?
605 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
606 ProtocolLoc, AtProtoInterfaceLoc,
608 PDecl->startDefinition();
611 // Check for circular dependencies among protocol declarations. This can
612 // only happen if this protocol was forward-declared.
613 ObjCList<ObjCProtocolDecl> PList;
614 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
615 err = CheckForwardProtocolDeclarationForCircularDependency(
616 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
619 // Create the new declaration.
620 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
621 ProtocolLoc, AtProtoInterfaceLoc,
622 /*PrevDecl=*/PrevDecl);
624 PushOnScopeChains(PDecl, TUScope);
625 PDecl->startDefinition();
629 ProcessDeclAttributeList(TUScope, PDecl, AttrList);
631 // Merge attributes from previous declarations.
633 mergeDeclAttributes(PDecl, PrevDecl);
635 if (!err && NumProtoRefs ) {
636 /// Check then save referenced protocols.
637 PDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
641 CheckObjCDeclScope(PDecl);
642 return ActOnObjCContainerStartDefinition(PDecl);
645 /// FindProtocolDeclaration - This routine looks up protocols and
646 /// issues an error if they are not declared. It returns list of
647 /// protocol declarations in its 'Protocols' argument.
649 Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
650 const IdentifierLocPair *ProtocolId,
651 unsigned NumProtocols,
652 SmallVectorImpl<Decl *> &Protocols) {
653 for (unsigned i = 0; i != NumProtocols; ++i) {
654 ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first,
655 ProtocolId[i].second);
657 DeclFilterCCC<ObjCProtocolDecl> Validator;
658 TypoCorrection Corrected = CorrectTypo(
659 DeclarationNameInfo(ProtocolId[i].first, ProtocolId[i].second),
660 LookupObjCProtocolName, TUScope, NULL, Validator);
661 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>())) {
662 Diag(ProtocolId[i].second, diag::err_undeclared_protocol_suggest)
663 << ProtocolId[i].first << Corrected.getCorrection();
664 Diag(PDecl->getLocation(), diag::note_previous_decl)
665 << PDecl->getDeclName();
670 Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
671 << ProtocolId[i].first;
675 (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
677 // If this is a forward declaration and we are supposed to warn in this
679 if (WarnOnDeclarations && !PDecl->hasDefinition())
680 Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
681 << ProtocolId[i].first;
682 Protocols.push_back(PDecl);
686 /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
687 /// a class method in its extension.
689 void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
690 ObjCInterfaceDecl *ID) {
692 return; // Possibly due to previous error
694 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
695 for (ObjCInterfaceDecl::method_iterator i = ID->meth_begin(),
696 e = ID->meth_end(); i != e; ++i) {
697 ObjCMethodDecl *MD = *i;
698 MethodMap[MD->getSelector()] = MD;
701 if (MethodMap.empty())
703 for (ObjCCategoryDecl::method_iterator i = CAT->meth_begin(),
704 e = CAT->meth_end(); i != e; ++i) {
705 ObjCMethodDecl *Method = *i;
706 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
707 if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
708 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
709 << Method->getDeclName();
710 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
715 /// ActOnForwardProtocolDeclaration - Handle @protocol foo;
717 Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
718 const IdentifierLocPair *IdentList,
720 AttributeList *attrList) {
721 SmallVector<Decl *, 8> DeclsInGroup;
722 for (unsigned i = 0; i != NumElts; ++i) {
723 IdentifierInfo *Ident = IdentList[i].first;
724 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentList[i].second,
726 ObjCProtocolDecl *PDecl
727 = ObjCProtocolDecl::Create(Context, CurContext, Ident,
728 IdentList[i].second, AtProtocolLoc,
731 PushOnScopeChains(PDecl, TUScope);
732 CheckObjCDeclScope(PDecl);
735 ProcessDeclAttributeList(TUScope, PDecl, attrList);
738 mergeDeclAttributes(PDecl, PrevDecl);
740 DeclsInGroup.push_back(PDecl);
743 return BuildDeclaratorGroup(DeclsInGroup.data(), DeclsInGroup.size(), false);
747 ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
748 IdentifierInfo *ClassName, SourceLocation ClassLoc,
749 IdentifierInfo *CategoryName,
750 SourceLocation CategoryLoc,
751 Decl * const *ProtoRefs,
752 unsigned NumProtoRefs,
753 const SourceLocation *ProtoLocs,
754 SourceLocation EndProtoLoc) {
755 ObjCCategoryDecl *CDecl;
756 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
758 /// Check that class of this category is already completely declared.
761 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
762 PDiag(diag::err_category_forward_interface)
763 << (CategoryName == 0))) {
764 // Create an invalid ObjCCategoryDecl to serve as context for
765 // the enclosing method declarations. We mark the decl invalid
766 // to make it clear that this isn't a valid AST.
767 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
768 ClassLoc, CategoryLoc, CategoryName,IDecl);
769 CDecl->setInvalidDecl();
770 CurContext->addDecl(CDecl);
773 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
774 return ActOnObjCContainerStartDefinition(CDecl);
777 if (!CategoryName && IDecl->getImplementation()) {
778 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
779 Diag(IDecl->getImplementation()->getLocation(),
780 diag::note_implementation_declared);
784 /// Check for duplicate interface declaration for this category
785 ObjCCategoryDecl *CDeclChain;
786 for (CDeclChain = IDecl->getCategoryList(); CDeclChain;
787 CDeclChain = CDeclChain->getNextClassCategory()) {
788 if (CDeclChain->getIdentifier() == CategoryName) {
789 // Class extensions can be declared multiple times.
790 Diag(CategoryLoc, diag::warn_dup_category_def)
791 << ClassName << CategoryName;
792 Diag(CDeclChain->getLocation(), diag::note_previous_definition);
798 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
799 ClassLoc, CategoryLoc, CategoryName, IDecl);
800 // FIXME: PushOnScopeChains?
801 CurContext->addDecl(CDecl);
804 CDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
806 // Protocols in the class extension belong to the class.
807 if (CDecl->IsClassExtension())
808 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl**)ProtoRefs,
809 NumProtoRefs, Context);
812 CheckObjCDeclScope(CDecl);
813 return ActOnObjCContainerStartDefinition(CDecl);
816 /// ActOnStartCategoryImplementation - Perform semantic checks on the
817 /// category implementation declaration and build an ObjCCategoryImplDecl
819 Decl *Sema::ActOnStartCategoryImplementation(
820 SourceLocation AtCatImplLoc,
821 IdentifierInfo *ClassName, SourceLocation ClassLoc,
822 IdentifierInfo *CatName, SourceLocation CatLoc) {
823 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
824 ObjCCategoryDecl *CatIDecl = 0;
825 if (IDecl && IDecl->hasDefinition()) {
826 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
828 // Category @implementation with no corresponding @interface.
829 // Create and install one.
830 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
833 CatIDecl->setImplicit();
837 ObjCCategoryImplDecl *CDecl =
838 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
839 ClassLoc, AtCatImplLoc, CatLoc);
840 /// Check that class of this category is already completely declared.
842 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
843 CDecl->setInvalidDecl();
844 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
845 diag::err_undef_interface)) {
846 CDecl->setInvalidDecl();
849 // FIXME: PushOnScopeChains?
850 CurContext->addDecl(CDecl);
852 // If the interface is deprecated/unavailable, warn/error about it.
854 DiagnoseUseOfDecl(IDecl, ClassLoc);
856 /// Check that CatName, category name, is not used in another implementation.
858 if (CatIDecl->getImplementation()) {
859 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
861 Diag(CatIDecl->getImplementation()->getLocation(),
862 diag::note_previous_definition);
864 CatIDecl->setImplementation(CDecl);
865 // Warn on implementating category of deprecated class under
866 // -Wdeprecated-implementations flag.
867 DiagnoseObjCImplementedDeprecations(*this,
868 dyn_cast<NamedDecl>(IDecl),
869 CDecl->getLocation(), 2);
873 CheckObjCDeclScope(CDecl);
874 return ActOnObjCContainerStartDefinition(CDecl);
877 Decl *Sema::ActOnStartClassImplementation(
878 SourceLocation AtClassImplLoc,
879 IdentifierInfo *ClassName, SourceLocation ClassLoc,
880 IdentifierInfo *SuperClassname,
881 SourceLocation SuperClassLoc) {
882 ObjCInterfaceDecl* IDecl = 0;
883 // Check for another declaration kind with the same name.
885 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
887 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
888 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
889 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
890 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
891 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
892 diag::warn_undef_interface);
894 // We did not find anything with the name ClassName; try to correct for
895 // typos in the class name.
896 ObjCInterfaceValidatorCCC Validator;
897 if (TypoCorrection Corrected = CorrectTypo(
898 DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope,
900 // Suggest the (potentially) correct interface name. However, put the
901 // fix-it hint itself in a separate note, since changing the name in
902 // the warning would make the fix-it change semantics.However, don't
903 // provide a code-modification hint or use the typo name for recovery,
904 // because this is just a warning. The program may actually be correct.
905 IDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
906 DeclarationName CorrectedName = Corrected.getCorrection();
907 Diag(ClassLoc, diag::warn_undef_interface_suggest)
908 << ClassName << CorrectedName;
909 Diag(IDecl->getLocation(), diag::note_previous_decl) << CorrectedName
910 << FixItHint::CreateReplacement(ClassLoc, CorrectedName.getAsString());
913 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
917 // Check that super class name is valid class name
918 ObjCInterfaceDecl* SDecl = 0;
919 if (SuperClassname) {
920 // Check if a different kind of symbol declared in this scope.
921 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
923 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
924 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
926 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
928 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
929 if (SDecl && !SDecl->hasDefinition())
932 Diag(SuperClassLoc, diag::err_undef_superclass)
933 << SuperClassname << ClassName;
934 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
935 // This implementation and its interface do not have the same
937 Diag(SuperClassLoc, diag::err_conflicting_super_class)
938 << SDecl->getDeclName();
939 Diag(SDecl->getLocation(), diag::note_previous_definition);
945 // Legacy case of @implementation with no corresponding @interface.
946 // Build, chain & install the interface decl into the identifier.
948 // FIXME: Do we support attributes on the @implementation? If so we should
950 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
951 ClassName, /*PrevDecl=*/0, ClassLoc,
953 IDecl->startDefinition();
955 IDecl->setSuperClass(SDecl);
956 IDecl->setSuperClassLoc(SuperClassLoc);
957 IDecl->setEndOfDefinitionLoc(SuperClassLoc);
959 IDecl->setEndOfDefinitionLoc(ClassLoc);
962 PushOnScopeChains(IDecl, TUScope);
964 // Mark the interface as being completed, even if it was just as
966 // declaration; the user cannot reopen it.
967 if (!IDecl->hasDefinition())
968 IDecl->startDefinition();
971 ObjCImplementationDecl* IMPDecl =
972 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
973 ClassLoc, AtClassImplLoc);
975 if (CheckObjCDeclScope(IMPDecl))
976 return ActOnObjCContainerStartDefinition(IMPDecl);
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);
993 return ActOnObjCContainerStartDefinition(IMPDecl);
997 Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
998 SmallVector<Decl *, 64> DeclsInGroup;
999 DeclsInGroup.reserve(Decls.size() + 1);
1001 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
1002 Decl *Dcl = Decls[i];
1005 if (Dcl->getDeclContext()->isFileContext())
1006 Dcl->setTopLevelDeclInObjCContainer();
1007 DeclsInGroup.push_back(Dcl);
1010 DeclsInGroup.push_back(ObjCImpDecl);
1012 return BuildDeclaratorGroup(DeclsInGroup.data(), DeclsInGroup.size(), false);
1015 void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
1016 ObjCIvarDecl **ivars, unsigned numIvars,
1017 SourceLocation RBrace) {
1018 assert(ImpDecl && "missing implementation decl");
1019 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
1022 /// Check case of non-existing @interface decl.
1023 /// (legacy objective-c @implementation decl without an @interface decl).
1024 /// Add implementations's ivar to the synthesize class's ivar list.
1025 if (IDecl->isImplicitInterfaceDecl()) {
1026 IDecl->setEndOfDefinitionLoc(RBrace);
1027 // Add ivar's to class's DeclContext.
1028 for (unsigned i = 0, e = numIvars; i != e; ++i) {
1029 ivars[i]->setLexicalDeclContext(ImpDecl);
1030 IDecl->makeDeclVisibleInContext(ivars[i]);
1031 ImpDecl->addDecl(ivars[i]);
1036 // If implementation has empty ivar list, just return.
1040 assert(ivars && "missing @implementation ivars");
1041 if (LangOpts.ObjCNonFragileABI2) {
1042 if (ImpDecl->getSuperClass())
1043 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
1044 for (unsigned i = 0; i < numIvars; i++) {
1045 ObjCIvarDecl* ImplIvar = ivars[i];
1046 if (const ObjCIvarDecl *ClsIvar =
1047 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
1048 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
1049 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1052 // Instance ivar to Implementation's DeclContext.
1053 ImplIvar->setLexicalDeclContext(ImpDecl);
1054 IDecl->makeDeclVisibleInContext(ImplIvar);
1055 ImpDecl->addDecl(ImplIvar);
1059 // Check interface's Ivar list against those in the implementation.
1060 // names and types must match.
1063 ObjCInterfaceDecl::ivar_iterator
1064 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
1065 for (; numIvars > 0 && IVI != IVE; ++IVI) {
1066 ObjCIvarDecl* ImplIvar = ivars[j++];
1067 ObjCIvarDecl* ClsIvar = *IVI;
1068 assert (ImplIvar && "missing implementation ivar");
1069 assert (ClsIvar && "missing class ivar");
1071 // First, make sure the types match.
1072 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
1073 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
1074 << ImplIvar->getIdentifier()
1075 << ImplIvar->getType() << ClsIvar->getType();
1076 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1077 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
1078 ImplIvar->getBitWidthValue(Context) !=
1079 ClsIvar->getBitWidthValue(Context)) {
1080 Diag(ImplIvar->getBitWidth()->getLocStart(),
1081 diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier();
1082 Diag(ClsIvar->getBitWidth()->getLocStart(),
1083 diag::note_previous_definition);
1085 // Make sure the names are identical.
1086 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
1087 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
1088 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
1089 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1095 Diag(ivars[j]->getLocation(), diag::err_inconsistant_ivar_count);
1096 else if (IVI != IVE)
1097 Diag((*IVI)->getLocation(), diag::err_inconsistant_ivar_count);
1100 void Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
1101 bool &IncompleteImpl, unsigned DiagID) {
1102 // No point warning no definition of method which is 'unavailable'.
1103 if (method->hasAttr<UnavailableAttr>())
1105 if (!IncompleteImpl) {
1106 Diag(ImpLoc, diag::warn_incomplete_impl);
1107 IncompleteImpl = true;
1109 if (DiagID == diag::warn_unimplemented_protocol_method)
1110 Diag(ImpLoc, DiagID) << method->getDeclName();
1112 Diag(method->getLocation(), DiagID) << method->getDeclName();
1115 /// Determines if type B can be substituted for type A. Returns true if we can
1116 /// guarantee that anything that the user will do to an object of type A can
1117 /// also be done to an object of type B. This is trivially true if the two
1118 /// types are the same, or if B is a subclass of A. It becomes more complex
1119 /// in cases where protocols are involved.
1121 /// Object types in Objective-C describe the minimum requirements for an
1122 /// object, rather than providing a complete description of a type. For
1123 /// example, if A is a subclass of B, then B* may refer to an instance of A.
1124 /// The principle of substitutability means that we may use an instance of A
1125 /// anywhere that we may use an instance of B - it will implement all of the
1126 /// ivars of B and all of the methods of B.
1128 /// This substitutability is important when type checking methods, because
1129 /// the implementation may have stricter type definitions than the interface.
1130 /// The interface specifies minimum requirements, but the implementation may
1131 /// have more accurate ones. For example, a method may privately accept
1132 /// instances of B, but only publish that it accepts instances of A. Any
1133 /// object passed to it will be type checked against B, and so will implicitly
1134 /// by a valid A*. Similarly, a method may return a subclass of the class that
1135 /// it is declared as returning.
1137 /// This is most important when considering subclassing. A method in a
1138 /// subclass must accept any object as an argument that its superclass's
1139 /// implementation accepts. It may, however, accept a more general type
1140 /// without breaking substitutability (i.e. you can still use the subclass
1141 /// anywhere that you can use the superclass, but not vice versa). The
1142 /// converse requirement applies to return types: the return type for a
1143 /// subclass method must be a valid object of the kind that the superclass
1144 /// advertises, but it may be specified more accurately. This avoids the need
1145 /// for explicit down-casting by callers.
1147 /// Note: This is a stricter requirement than for assignment.
1148 static bool isObjCTypeSubstitutable(ASTContext &Context,
1149 const ObjCObjectPointerType *A,
1150 const ObjCObjectPointerType *B,
1152 // Reject a protocol-unqualified id.
1153 if (rejectId && B->isObjCIdType()) return false;
1155 // If B is a qualified id, then A must also be a qualified id and it must
1156 // implement all of the protocols in B. It may not be a qualified class.
1157 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
1158 // stricter definition so it is not substitutable for id<A>.
1159 if (B->isObjCQualifiedIdType()) {
1160 return A->isObjCQualifiedIdType() &&
1161 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
1167 // id is a special type that bypasses type checking completely. We want a
1168 // warning when it is used in one place but not another.
1169 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
1172 // If B is a qualified id, then A must also be a qualified id (which it isn't
1173 // if we've got this far)
1174 if (B->isObjCQualifiedIdType()) return false;
1177 // Now we know that A and B are (potentially-qualified) class types. The
1178 // normal rules for assignment apply.
1179 return Context.canAssignObjCInterfaces(A, B);
1182 static SourceRange getTypeRange(TypeSourceInfo *TSI) {
1183 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
1186 static bool CheckMethodOverrideReturn(Sema &S,
1187 ObjCMethodDecl *MethodImpl,
1188 ObjCMethodDecl *MethodDecl,
1189 bool IsProtocolMethodDecl,
1190 bool IsOverridingMode,
1192 if (IsProtocolMethodDecl &&
1193 (MethodDecl->getObjCDeclQualifier() !=
1194 MethodImpl->getObjCDeclQualifier())) {
1196 S.Diag(MethodImpl->getLocation(),
1198 diag::warn_conflicting_overriding_ret_type_modifiers
1199 : diag::warn_conflicting_ret_type_modifiers))
1200 << MethodImpl->getDeclName()
1201 << getTypeRange(MethodImpl->getResultTypeSourceInfo());
1202 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
1203 << getTypeRange(MethodDecl->getResultTypeSourceInfo());
1209 if (S.Context.hasSameUnqualifiedType(MethodImpl->getResultType(),
1210 MethodDecl->getResultType()))
1216 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
1217 : diag::warn_conflicting_ret_types;
1219 // Mismatches between ObjC pointers go into a different warning
1220 // category, and sometimes they're even completely whitelisted.
1221 if (const ObjCObjectPointerType *ImplPtrTy =
1222 MethodImpl->getResultType()->getAs<ObjCObjectPointerType>()) {
1223 if (const ObjCObjectPointerType *IfacePtrTy =
1224 MethodDecl->getResultType()->getAs<ObjCObjectPointerType>()) {
1225 // Allow non-matching return types as long as they don't violate
1226 // the principle of substitutability. Specifically, we permit
1227 // return types that are subclasses of the declared return type,
1228 // or that are more-qualified versions of the declared type.
1229 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
1233 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
1234 : diag::warn_non_covariant_ret_types;
1238 S.Diag(MethodImpl->getLocation(), DiagID)
1239 << MethodImpl->getDeclName()
1240 << MethodDecl->getResultType()
1241 << MethodImpl->getResultType()
1242 << getTypeRange(MethodImpl->getResultTypeSourceInfo());
1243 S.Diag(MethodDecl->getLocation(),
1244 IsOverridingMode ? diag::note_previous_declaration
1245 : diag::note_previous_definition)
1246 << getTypeRange(MethodDecl->getResultTypeSourceInfo());
1250 static bool CheckMethodOverrideParam(Sema &S,
1251 ObjCMethodDecl *MethodImpl,
1252 ObjCMethodDecl *MethodDecl,
1253 ParmVarDecl *ImplVar,
1254 ParmVarDecl *IfaceVar,
1255 bool IsProtocolMethodDecl,
1256 bool IsOverridingMode,
1258 if (IsProtocolMethodDecl &&
1259 (ImplVar->getObjCDeclQualifier() !=
1260 IfaceVar->getObjCDeclQualifier())) {
1262 if (IsOverridingMode)
1263 S.Diag(ImplVar->getLocation(),
1264 diag::warn_conflicting_overriding_param_modifiers)
1265 << getTypeRange(ImplVar->getTypeSourceInfo())
1266 << MethodImpl->getDeclName();
1267 else S.Diag(ImplVar->getLocation(),
1268 diag::warn_conflicting_param_modifiers)
1269 << getTypeRange(ImplVar->getTypeSourceInfo())
1270 << MethodImpl->getDeclName();
1271 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
1272 << getTypeRange(IfaceVar->getTypeSourceInfo());
1278 QualType ImplTy = ImplVar->getType();
1279 QualType IfaceTy = IfaceVar->getType();
1281 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
1287 IsOverridingMode ? diag::warn_conflicting_overriding_param_types
1288 : diag::warn_conflicting_param_types;
1290 // Mismatches between ObjC pointers go into a different warning
1291 // category, and sometimes they're even completely whitelisted.
1292 if (const ObjCObjectPointerType *ImplPtrTy =
1293 ImplTy->getAs<ObjCObjectPointerType>()) {
1294 if (const ObjCObjectPointerType *IfacePtrTy =
1295 IfaceTy->getAs<ObjCObjectPointerType>()) {
1296 // Allow non-matching argument types as long as they don't
1297 // violate the principle of substitutability. Specifically, the
1298 // implementation must accept any objects that the superclass
1299 // accepts, however it may also accept others.
1300 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
1304 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
1305 : diag::warn_non_contravariant_param_types;
1309 S.Diag(ImplVar->getLocation(), DiagID)
1310 << getTypeRange(ImplVar->getTypeSourceInfo())
1311 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
1312 S.Diag(IfaceVar->getLocation(),
1313 (IsOverridingMode ? diag::note_previous_declaration
1314 : diag::note_previous_definition))
1315 << getTypeRange(IfaceVar->getTypeSourceInfo());
1319 /// In ARC, check whether the conventional meanings of the two methods
1320 /// match. If they don't, it's a hard error.
1321 static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
1322 ObjCMethodDecl *decl) {
1323 ObjCMethodFamily implFamily = impl->getMethodFamily();
1324 ObjCMethodFamily declFamily = decl->getMethodFamily();
1325 if (implFamily == declFamily) return false;
1327 // Since conventions are sorted by selector, the only possibility is
1328 // that the types differ enough to cause one selector or the other
1329 // to fall out of the family.
1330 assert(implFamily == OMF_None || declFamily == OMF_None);
1332 // No further diagnostics required on invalid declarations.
1333 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
1335 const ObjCMethodDecl *unmatched = impl;
1336 ObjCMethodFamily family = declFamily;
1337 unsigned errorID = diag::err_arc_lost_method_convention;
1338 unsigned noteID = diag::note_arc_lost_method_convention;
1339 if (declFamily == OMF_None) {
1341 family = implFamily;
1342 errorID = diag::err_arc_gained_method_convention;
1343 noteID = diag::note_arc_gained_method_convention;
1346 // Indexes into a %select clause in the diagnostic.
1347 enum FamilySelector {
1348 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
1350 FamilySelector familySelector = FamilySelector();
1353 case OMF_None: llvm_unreachable("logic error, no method convention");
1356 case OMF_autorelease:
1359 case OMF_retainCount:
1361 case OMF_performSelector:
1362 // Mismatches for these methods don't change ownership
1363 // conventions, so we don't care.
1366 case OMF_init: familySelector = F_init; break;
1367 case OMF_alloc: familySelector = F_alloc; break;
1368 case OMF_copy: familySelector = F_copy; break;
1369 case OMF_mutableCopy: familySelector = F_mutableCopy; break;
1370 case OMF_new: familySelector = F_new; break;
1373 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
1374 ReasonSelector reasonSelector;
1376 // The only reason these methods don't fall within their families is
1377 // due to unusual result types.
1378 if (unmatched->getResultType()->isObjCObjectPointerType()) {
1379 reasonSelector = R_UnrelatedReturn;
1381 reasonSelector = R_NonObjectReturn;
1384 S.Diag(impl->getLocation(), errorID) << familySelector << reasonSelector;
1385 S.Diag(decl->getLocation(), noteID) << familySelector << reasonSelector;
1390 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
1391 ObjCMethodDecl *MethodDecl,
1392 bool IsProtocolMethodDecl) {
1393 if (getLangOpts().ObjCAutoRefCount &&
1394 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
1397 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
1398 IsProtocolMethodDecl, false,
1401 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
1402 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end();
1403 IM != EM; ++IM, ++IF) {
1404 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
1405 IsProtocolMethodDecl, false, true);
1408 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
1409 Diag(ImpMethodDecl->getLocation(),
1410 diag::warn_conflicting_variadic);
1411 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
1415 void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
1416 ObjCMethodDecl *Overridden,
1417 bool IsProtocolMethodDecl) {
1419 CheckMethodOverrideReturn(*this, Method, Overridden,
1420 IsProtocolMethodDecl, true,
1423 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
1424 IF = Overridden->param_begin(), EM = Method->param_end();
1425 IM != EM; ++IM, ++IF) {
1426 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
1427 IsProtocolMethodDecl, true, true);
1430 if (Method->isVariadic() != Overridden->isVariadic()) {
1431 Diag(Method->getLocation(),
1432 diag::warn_conflicting_overriding_variadic);
1433 Diag(Overridden->getLocation(), diag::note_previous_declaration);
1437 /// WarnExactTypedMethods - This routine issues a warning if method
1438 /// implementation declaration matches exactly that of its declaration.
1439 void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
1440 ObjCMethodDecl *MethodDecl,
1441 bool IsProtocolMethodDecl) {
1442 // don't issue warning when protocol method is optional because primary
1443 // class is not required to implement it and it is safe for protocol
1445 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
1447 // don't issue warning when primary class's method is
1448 // depecated/unavailable.
1449 if (MethodDecl->hasAttr<UnavailableAttr>() ||
1450 MethodDecl->hasAttr<DeprecatedAttr>())
1453 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
1454 IsProtocolMethodDecl, false, false);
1456 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
1457 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end();
1458 IM != EM; ++IM, ++IF) {
1459 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
1461 IsProtocolMethodDecl, false, false);
1466 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
1468 match = !(MethodDecl->isClassMethod() &&
1469 MethodDecl->getSelector() == GetNullarySelector("load", Context));
1472 Diag(ImpMethodDecl->getLocation(),
1473 diag::warn_category_method_impl_match);
1474 Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
1475 << MethodDecl->getDeclName();
1479 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
1480 /// improve the efficiency of selector lookups and type checking by associating
1481 /// with each protocol / interface / category the flattened instance tables. If
1482 /// we used an immutable set to keep the table then it wouldn't add significant
1483 /// memory cost and it would be handy for lookups.
1485 /// CheckProtocolMethodDefs - This routine checks unimplemented methods
1486 /// Declared in protocol, and those referenced by it.
1487 void Sema::CheckProtocolMethodDefs(SourceLocation ImpLoc,
1488 ObjCProtocolDecl *PDecl,
1489 bool& IncompleteImpl,
1490 const llvm::DenseSet<Selector> &InsMap,
1491 const llvm::DenseSet<Selector> &ClsMap,
1492 ObjCContainerDecl *CDecl) {
1493 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
1494 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
1495 : dyn_cast<ObjCInterfaceDecl>(CDecl);
1496 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
1498 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
1499 ObjCInterfaceDecl *NSIDecl = 0;
1500 if (getLangOpts().NeXTRuntime) {
1501 // check to see if class implements forwardInvocation method and objects
1502 // of this class are derived from 'NSProxy' so that to forward requests
1503 // from one object to another.
1504 // Under such conditions, which means that every method possible is
1505 // implemented in the class, we should not issue "Method definition not
1507 // FIXME: Use a general GetUnarySelector method for this.
1508 IdentifierInfo* II = &Context.Idents.get("forwardInvocation");
1509 Selector fISelector = Context.Selectors.getSelector(1, &II);
1510 if (InsMap.count(fISelector))
1511 // Is IDecl derived from 'NSProxy'? If so, no instance methods
1512 // need be implemented in the implementation.
1513 NSIDecl = IDecl->lookupInheritedClass(&Context.Idents.get("NSProxy"));
1516 // If a method lookup fails locally we still need to look and see if
1517 // the method was implemented by a base class or an inherited
1518 // protocol. This lookup is slow, but occurs rarely in correct code
1519 // and otherwise would terminate in a warning.
1521 // check unimplemented instance methods.
1523 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
1524 E = PDecl->instmeth_end(); I != E; ++I) {
1525 ObjCMethodDecl *method = *I;
1526 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1527 !method->isSynthesized() && !InsMap.count(method->getSelector()) &&
1529 !Super->lookupInstanceMethod(method->getSelector()))) {
1530 // If a method is not implemented in the category implementation but
1531 // has been declared in its primary class, superclass,
1532 // or in one of their protocols, no need to issue the warning.
1533 // This is because method will be implemented in the primary class
1534 // or one of its super class implementation.
1536 // Ugly, but necessary. Method declared in protcol might have
1537 // have been synthesized due to a property declared in the class which
1538 // uses the protocol.
1539 if (ObjCMethodDecl *MethodInClass =
1540 IDecl->lookupInstanceMethod(method->getSelector(),
1541 true /*shallowCategoryLookup*/))
1542 if (C || MethodInClass->isSynthesized())
1544 unsigned DIAG = diag::warn_unimplemented_protocol_method;
1545 if (Diags.getDiagnosticLevel(DIAG, ImpLoc)
1546 != DiagnosticsEngine::Ignored) {
1547 WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
1548 Diag(method->getLocation(), diag::note_method_declared_at)
1549 << method->getDeclName();
1550 Diag(CDecl->getLocation(), diag::note_required_for_protocol_at)
1551 << PDecl->getDeclName();
1555 // check unimplemented class methods
1556 for (ObjCProtocolDecl::classmeth_iterator
1557 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1559 ObjCMethodDecl *method = *I;
1560 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1561 !ClsMap.count(method->getSelector()) &&
1562 (!Super || !Super->lookupClassMethod(method->getSelector()))) {
1563 // See above comment for instance method lookups.
1564 if (C && IDecl->lookupClassMethod(method->getSelector(),
1565 true /*shallowCategoryLookup*/))
1567 unsigned DIAG = diag::warn_unimplemented_protocol_method;
1568 if (Diags.getDiagnosticLevel(DIAG, ImpLoc) !=
1569 DiagnosticsEngine::Ignored) {
1570 WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
1571 Diag(method->getLocation(), diag::note_method_declared_at)
1572 << method->getDeclName();
1573 Diag(IDecl->getLocation(), diag::note_required_for_protocol_at) <<
1574 PDecl->getDeclName();
1578 // Check on this protocols's referenced protocols, recursively.
1579 for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
1580 E = PDecl->protocol_end(); PI != E; ++PI)
1581 CheckProtocolMethodDefs(ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap, CDecl);
1584 /// MatchAllMethodDeclarations - Check methods declared in interface
1585 /// or protocol against those declared in their implementations.
1587 void Sema::MatchAllMethodDeclarations(const llvm::DenseSet<Selector> &InsMap,
1588 const llvm::DenseSet<Selector> &ClsMap,
1589 llvm::DenseSet<Selector> &InsMapSeen,
1590 llvm::DenseSet<Selector> &ClsMapSeen,
1591 ObjCImplDecl* IMPDecl,
1592 ObjCContainerDecl* CDecl,
1593 bool &IncompleteImpl,
1594 bool ImmediateClass,
1595 bool WarnCategoryMethodImpl) {
1596 // Check and see if instance methods in class interface have been
1597 // implemented in the implementation class. If so, their types match.
1598 for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(),
1599 E = CDecl->instmeth_end(); I != E; ++I) {
1600 if (InsMapSeen.count((*I)->getSelector()))
1602 InsMapSeen.insert((*I)->getSelector());
1603 if (!(*I)->isSynthesized() &&
1604 !InsMap.count((*I)->getSelector())) {
1606 WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl,
1607 diag::note_undef_method_impl);
1610 ObjCMethodDecl *ImpMethodDecl =
1611 IMPDecl->getInstanceMethod((*I)->getSelector());
1612 assert(CDecl->getInstanceMethod((*I)->getSelector()) &&
1613 "Expected to find the method through lookup as well");
1614 ObjCMethodDecl *MethodDecl = *I;
1615 // ImpMethodDecl may be null as in a @dynamic property.
1616 if (ImpMethodDecl) {
1617 if (!WarnCategoryMethodImpl)
1618 WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl,
1619 isa<ObjCProtocolDecl>(CDecl));
1620 else if (!MethodDecl->isSynthesized())
1621 WarnExactTypedMethods(ImpMethodDecl, MethodDecl,
1622 isa<ObjCProtocolDecl>(CDecl));
1627 // Check and see if class methods in class interface have been
1628 // implemented in the implementation class. If so, their types match.
1629 for (ObjCInterfaceDecl::classmeth_iterator
1630 I = CDecl->classmeth_begin(), E = CDecl->classmeth_end(); I != E; ++I) {
1631 if (ClsMapSeen.count((*I)->getSelector()))
1633 ClsMapSeen.insert((*I)->getSelector());
1634 if (!ClsMap.count((*I)->getSelector())) {
1636 WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl,
1637 diag::note_undef_method_impl);
1639 ObjCMethodDecl *ImpMethodDecl =
1640 IMPDecl->getClassMethod((*I)->getSelector());
1641 assert(CDecl->getClassMethod((*I)->getSelector()) &&
1642 "Expected to find the method through lookup as well");
1643 ObjCMethodDecl *MethodDecl = *I;
1644 if (!WarnCategoryMethodImpl)
1645 WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl,
1646 isa<ObjCProtocolDecl>(CDecl));
1648 WarnExactTypedMethods(ImpMethodDecl, MethodDecl,
1649 isa<ObjCProtocolDecl>(CDecl));
1653 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
1654 // Also methods in class extensions need be looked at next.
1655 for (const ObjCCategoryDecl *ClsExtDecl = I->getFirstClassExtension();
1656 ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension())
1657 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1659 const_cast<ObjCCategoryDecl *>(ClsExtDecl),
1660 IncompleteImpl, false,
1661 WarnCategoryMethodImpl);
1663 // Check for any implementation of a methods declared in protocol.
1664 for (ObjCInterfaceDecl::all_protocol_iterator
1665 PI = I->all_referenced_protocol_begin(),
1666 E = I->all_referenced_protocol_end(); PI != E; ++PI)
1667 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1669 (*PI), IncompleteImpl, false,
1670 WarnCategoryMethodImpl);
1672 // FIXME. For now, we are not checking for extact match of methods
1673 // in category implementation and its primary class's super class.
1674 if (!WarnCategoryMethodImpl && I->getSuperClass())
1675 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1677 I->getSuperClass(), IncompleteImpl, false);
1681 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
1682 /// category matches with those implemented in its primary class and
1683 /// warns each time an exact match is found.
1684 void Sema::CheckCategoryVsClassMethodMatches(
1685 ObjCCategoryImplDecl *CatIMPDecl) {
1686 llvm::DenseSet<Selector> InsMap, ClsMap;
1688 for (ObjCImplementationDecl::instmeth_iterator
1689 I = CatIMPDecl->instmeth_begin(),
1690 E = CatIMPDecl->instmeth_end(); I!=E; ++I)
1691 InsMap.insert((*I)->getSelector());
1693 for (ObjCImplementationDecl::classmeth_iterator
1694 I = CatIMPDecl->classmeth_begin(),
1695 E = CatIMPDecl->classmeth_end(); I != E; ++I)
1696 ClsMap.insert((*I)->getSelector());
1697 if (InsMap.empty() && ClsMap.empty())
1700 // Get category's primary class.
1701 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
1704 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
1707 llvm::DenseSet<Selector> InsMapSeen, ClsMapSeen;
1708 bool IncompleteImpl = false;
1709 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1711 IncompleteImpl, false,
1712 true /*WarnCategoryMethodImpl*/);
1715 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
1716 ObjCContainerDecl* CDecl,
1717 bool IncompleteImpl) {
1718 llvm::DenseSet<Selector> InsMap;
1719 // Check and see if instance methods in class interface have been
1720 // implemented in the implementation class.
1721 for (ObjCImplementationDecl::instmeth_iterator
1722 I = IMPDecl->instmeth_begin(), E = IMPDecl->instmeth_end(); I!=E; ++I)
1723 InsMap.insert((*I)->getSelector());
1725 // Check and see if properties declared in the interface have either 1)
1726 // an implementation or 2) there is a @synthesize/@dynamic implementation
1727 // of the property in the @implementation.
1728 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl))
1729 if (!(LangOpts.ObjCDefaultSynthProperties && LangOpts.ObjCNonFragileABI2) ||
1730 IDecl->isObjCRequiresPropertyDefs())
1731 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap);
1733 llvm::DenseSet<Selector> ClsMap;
1734 for (ObjCImplementationDecl::classmeth_iterator
1735 I = IMPDecl->classmeth_begin(),
1736 E = IMPDecl->classmeth_end(); I != E; ++I)
1737 ClsMap.insert((*I)->getSelector());
1739 // Check for type conflict of methods declared in a class/protocol and
1740 // its implementation; if any.
1741 llvm::DenseSet<Selector> InsMapSeen, ClsMapSeen;
1742 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1744 IncompleteImpl, true);
1746 // check all methods implemented in category against those declared
1747 // in its primary class.
1748 if (ObjCCategoryImplDecl *CatDecl =
1749 dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
1750 CheckCategoryVsClassMethodMatches(CatDecl);
1752 // Check the protocol list for unimplemented methods in the @implementation
1754 // Check and see if class methods in class interface have been
1755 // implemented in the implementation class.
1757 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
1758 for (ObjCInterfaceDecl::all_protocol_iterator
1759 PI = I->all_referenced_protocol_begin(),
1760 E = I->all_referenced_protocol_end(); PI != E; ++PI)
1761 CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
1763 // Check class extensions (unnamed categories)
1764 for (const ObjCCategoryDecl *Categories = I->getFirstClassExtension();
1765 Categories; Categories = Categories->getNextClassExtension())
1766 ImplMethodsVsClassMethods(S, IMPDecl,
1767 const_cast<ObjCCategoryDecl*>(Categories),
1769 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1770 // For extended class, unimplemented methods in its protocols will
1771 // be reported in the primary class.
1772 if (!C->IsClassExtension()) {
1773 for (ObjCCategoryDecl::protocol_iterator PI = C->protocol_begin(),
1774 E = C->protocol_end(); PI != E; ++PI)
1775 CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
1776 InsMap, ClsMap, CDecl);
1777 // Report unimplemented properties in the category as well.
1778 // When reporting on missing setter/getters, do not report when
1779 // setter/getter is implemented in category's primary class
1781 if (ObjCInterfaceDecl *ID = C->getClassInterface())
1782 if (ObjCImplDecl *IMP = ID->getImplementation()) {
1783 for (ObjCImplementationDecl::instmeth_iterator
1784 I = IMP->instmeth_begin(), E = IMP->instmeth_end(); I!=E; ++I)
1785 InsMap.insert((*I)->getSelector());
1787 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap);
1790 llvm_unreachable("invalid ObjCContainerDecl type.");
1793 /// ActOnForwardClassDeclaration -
1794 Sema::DeclGroupPtrTy
1795 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
1796 IdentifierInfo **IdentList,
1797 SourceLocation *IdentLocs,
1799 SmallVector<Decl *, 8> DeclsInGroup;
1800 for (unsigned i = 0; i != NumElts; ++i) {
1801 // Check for another declaration kind with the same name.
1803 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
1804 LookupOrdinaryName, ForRedeclaration);
1805 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1806 // Maybe we will complain about the shadowed template parameter.
1807 DiagnoseTemplateParameterShadow(AtClassLoc, PrevDecl);
1808 // Just pretend that we didn't see the previous declaration.
1812 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1813 // GCC apparently allows the following idiom:
1815 // typedef NSObject < XCElementTogglerP > XCElementToggler;
1816 // @class XCElementToggler;
1818 // Here we have chosen to ignore the forward class declaration
1819 // with a warning. Since this is the implied behavior.
1820 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
1821 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
1822 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
1823 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1825 // a forward class declaration matching a typedef name of a class refers
1826 // to the underlying class. Just ignore the forward class with a warning
1827 // as this will force the intended behavior which is to lookup the typedef
1829 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
1830 Diag(AtClassLoc, diag::warn_forward_class_redefinition) << IdentList[i];
1831 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1837 // Create a declaration to describe this forward declaration.
1838 ObjCInterfaceDecl *PrevIDecl
1839 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
1840 ObjCInterfaceDecl *IDecl
1841 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
1842 IdentList[i], PrevIDecl, IdentLocs[i]);
1843 IDecl->setAtEndRange(IdentLocs[i]);
1845 PushOnScopeChains(IDecl, TUScope);
1846 CheckObjCDeclScope(IDecl);
1847 DeclsInGroup.push_back(IDecl);
1850 return BuildDeclaratorGroup(DeclsInGroup.data(), DeclsInGroup.size(), false);
1853 static bool tryMatchRecordTypes(ASTContext &Context,
1854 Sema::MethodMatchStrategy strategy,
1855 const Type *left, const Type *right);
1857 static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
1858 QualType leftQT, QualType rightQT) {
1860 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
1862 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
1864 if (left == right) return true;
1866 // If we're doing a strict match, the types have to match exactly.
1867 if (strategy == Sema::MMS_strict) return false;
1869 if (left->isIncompleteType() || right->isIncompleteType()) return false;
1871 // Otherwise, use this absurdly complicated algorithm to try to
1872 // validate the basic, low-level compatibility of the two types.
1874 // As a minimum, require the sizes and alignments to match.
1875 if (Context.getTypeInfo(left) != Context.getTypeInfo(right))
1878 // Consider all the kinds of non-dependent canonical types:
1879 // - functions and arrays aren't possible as return and parameter types
1881 // - vector types of equal size can be arbitrarily mixed
1882 if (isa<VectorType>(left)) return isa<VectorType>(right);
1883 if (isa<VectorType>(right)) return false;
1885 // - references should only match references of identical type
1886 // - structs, unions, and Objective-C objects must match more-or-less
1888 // - everything else should be a scalar
1889 if (!left->isScalarType() || !right->isScalarType())
1890 return tryMatchRecordTypes(Context, strategy, left, right);
1892 // Make scalars agree in kind, except count bools as chars, and group
1893 // all non-member pointers together.
1894 Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
1895 Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
1896 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
1897 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
1898 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
1899 leftSK = Type::STK_ObjCObjectPointer;
1900 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
1901 rightSK = Type::STK_ObjCObjectPointer;
1903 // Note that data member pointers and function member pointers don't
1904 // intermix because of the size differences.
1906 return (leftSK == rightSK);
1909 static bool tryMatchRecordTypes(ASTContext &Context,
1910 Sema::MethodMatchStrategy strategy,
1911 const Type *lt, const Type *rt) {
1912 assert(lt && rt && lt != rt);
1914 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
1915 RecordDecl *left = cast<RecordType>(lt)->getDecl();
1916 RecordDecl *right = cast<RecordType>(rt)->getDecl();
1918 // Require union-hood to match.
1919 if (left->isUnion() != right->isUnion()) return false;
1921 // Require an exact match if either is non-POD.
1922 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
1923 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
1926 // Require size and alignment to match.
1927 if (Context.getTypeInfo(lt) != Context.getTypeInfo(rt)) return false;
1929 // Require fields to match.
1930 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
1931 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
1932 for (; li != le && ri != re; ++li, ++ri) {
1933 if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
1936 return (li == le && ri == re);
1939 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and
1940 /// returns true, or false, accordingly.
1941 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
1942 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
1943 const ObjCMethodDecl *right,
1944 MethodMatchStrategy strategy) {
1945 if (!matchTypes(Context, strategy,
1946 left->getResultType(), right->getResultType()))
1949 if (getLangOpts().ObjCAutoRefCount &&
1950 (left->hasAttr<NSReturnsRetainedAttr>()
1951 != right->hasAttr<NSReturnsRetainedAttr>() ||
1952 left->hasAttr<NSConsumesSelfAttr>()
1953 != right->hasAttr<NSConsumesSelfAttr>()))
1956 ObjCMethodDecl::param_const_iterator
1957 li = left->param_begin(), le = left->param_end(), ri = right->param_begin();
1959 for (; li != le; ++li, ++ri) {
1960 assert(ri != right->param_end() && "Param mismatch");
1961 const ParmVarDecl *lparm = *li, *rparm = *ri;
1963 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
1966 if (getLangOpts().ObjCAutoRefCount &&
1967 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
1973 void Sema::addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method) {
1974 // If the list is empty, make it a singleton list.
1975 if (List->Method == 0) {
1976 List->Method = Method;
1981 // We've seen a method with this name, see if we have already seen this type
1983 ObjCMethodList *Previous = List;
1984 for (; List; Previous = List, List = List->Next) {
1985 if (!MatchTwoMethodDeclarations(Method, List->Method))
1988 ObjCMethodDecl *PrevObjCMethod = List->Method;
1990 // Propagate the 'defined' bit.
1991 if (Method->isDefined())
1992 PrevObjCMethod->setDefined(true);
1994 // If a method is deprecated, push it in the global pool.
1995 // This is used for better diagnostics.
1996 if (Method->isDeprecated()) {
1997 if (!PrevObjCMethod->isDeprecated())
1998 List->Method = Method;
2000 // If new method is unavailable, push it into global pool
2001 // unless previous one is deprecated.
2002 if (Method->isUnavailable()) {
2003 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
2004 List->Method = Method;
2010 // We have a new signature for an existing method - add it.
2011 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
2012 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
2013 Previous->Next = new (Mem) ObjCMethodList(Method, 0);
2016 /// \brief Read the contents of the method pool for a given selector from
2017 /// external storage.
2018 void Sema::ReadMethodPool(Selector Sel) {
2019 assert(ExternalSource && "We need an external AST source");
2020 ExternalSource->ReadMethodPool(Sel);
2023 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
2025 // Ignore methods of invalid containers.
2026 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
2030 ReadMethodPool(Method->getSelector());
2032 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
2033 if (Pos == MethodPool.end())
2034 Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
2035 GlobalMethods())).first;
2037 Method->setDefined(impl);
2039 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
2040 addMethodToGlobalList(&Entry, Method);
2043 /// Determines if this is an "acceptable" loose mismatch in the global
2044 /// method pool. This exists mostly as a hack to get around certain
2045 /// global mismatches which we can't afford to make warnings / errors.
2046 /// Really, what we want is a way to take a method out of the global
2048 static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
2049 ObjCMethodDecl *other) {
2050 if (!chosen->isInstanceMethod())
2053 Selector sel = chosen->getSelector();
2054 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
2057 // Don't complain about mismatches for -length if the method we
2058 // chose has an integral result type.
2059 return (chosen->getResultType()->isIntegerType());
2062 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
2063 bool receiverIdOrClass,
2064 bool warn, bool instance) {
2066 ReadMethodPool(Sel);
2068 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2069 if (Pos == MethodPool.end())
2072 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
2074 if (warn && MethList.Method && MethList.Next) {
2075 bool issueDiagnostic = false, issueError = false;
2077 // We support a warning which complains about *any* difference in
2078 // method signature.
2079 bool strictSelectorMatch =
2080 (receiverIdOrClass && warn &&
2081 (Diags.getDiagnosticLevel(diag::warn_strict_multiple_method_decl,
2083 DiagnosticsEngine::Ignored));
2084 if (strictSelectorMatch)
2085 for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next) {
2086 if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method,
2088 issueDiagnostic = true;
2093 // If we didn't see any strict differences, we won't see any loose
2094 // differences. In ARC, however, we also need to check for loose
2095 // mismatches, because most of them are errors.
2096 if (!strictSelectorMatch ||
2097 (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
2098 for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next) {
2099 // This checks if the methods differ in type mismatch.
2100 if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method,
2102 !isAcceptableMethodMismatch(MethList.Method, Next->Method)) {
2103 issueDiagnostic = true;
2104 if (getLangOpts().ObjCAutoRefCount)
2110 if (issueDiagnostic) {
2112 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
2113 else if (strictSelectorMatch)
2114 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
2116 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
2118 Diag(MethList.Method->getLocStart(),
2119 issueError ? diag::note_possibility : diag::note_using)
2120 << MethList.Method->getSourceRange();
2121 for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
2122 Diag(Next->Method->getLocStart(), diag::note_also_found)
2123 << Next->Method->getSourceRange();
2126 return MethList.Method;
2129 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
2130 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2131 if (Pos == MethodPool.end())
2134 GlobalMethods &Methods = Pos->second;
2136 if (Methods.first.Method && Methods.first.Method->isDefined())
2137 return Methods.first.Method;
2138 if (Methods.second.Method && Methods.second.Method->isDefined())
2139 return Methods.second.Method;
2143 /// CompareMethodParamsInBaseAndSuper - This routine compares methods with
2144 /// identical selector names in current and its super classes and issues
2145 /// a warning if any of their argument types are incompatible.
2146 void Sema::CompareMethodParamsInBaseAndSuper(Decl *ClassDecl,
2147 ObjCMethodDecl *Method,
2149 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
2150 if (ID == 0) return;
2152 while (ObjCInterfaceDecl *SD = ID->getSuperClass()) {
2153 ObjCMethodDecl *SuperMethodDecl =
2154 SD->lookupMethod(Method->getSelector(), IsInstance);
2155 if (SuperMethodDecl == 0) {
2159 ObjCMethodDecl::param_iterator ParamI = Method->param_begin(),
2160 E = Method->param_end();
2161 ObjCMethodDecl::param_iterator PrevI = SuperMethodDecl->param_begin();
2162 for (; ParamI != E; ++ParamI, ++PrevI) {
2163 // Number of parameters are the same and is guaranteed by selector match.
2164 assert(PrevI != SuperMethodDecl->param_end() && "Param mismatch");
2165 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
2166 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
2167 // If type of argument of method in this class does not match its
2168 // respective argument type in the super class method, issue warning;
2169 if (!Context.typesAreCompatible(T1, T2)) {
2170 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
2172 Diag(SuperMethodDecl->getLocation(), diag::note_previous_declaration);
2180 /// DiagnoseDuplicateIvars -
2181 /// Check for duplicate ivars in the entire class at the start of
2182 /// @implementation. This becomes necesssary because class extension can
2183 /// add ivars to a class in random order which will not be known until
2184 /// class's @implementation is seen.
2185 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
2186 ObjCInterfaceDecl *SID) {
2187 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
2188 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
2189 ObjCIvarDecl* Ivar = (*IVI);
2190 if (Ivar->isInvalidDecl())
2192 if (IdentifierInfo *II = Ivar->getIdentifier()) {
2193 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
2195 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
2196 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
2197 Ivar->setInvalidDecl();
2203 Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
2204 switch (CurContext->getDeclKind()) {
2205 case Decl::ObjCInterface:
2206 return Sema::OCK_Interface;
2207 case Decl::ObjCProtocol:
2208 return Sema::OCK_Protocol;
2209 case Decl::ObjCCategory:
2210 if (dyn_cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
2211 return Sema::OCK_ClassExtension;
2213 return Sema::OCK_Category;
2214 case Decl::ObjCImplementation:
2215 return Sema::OCK_Implementation;
2216 case Decl::ObjCCategoryImpl:
2217 return Sema::OCK_CategoryImplementation;
2220 return Sema::OCK_None;
2224 // Note: For class/category implemenations, allMethods/allProperties is
2226 Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd,
2227 Decl **allMethods, unsigned allNum,
2228 Decl **allProperties, unsigned pNum,
2229 DeclGroupPtrTy *allTUVars, unsigned tuvNum) {
2231 if (getObjCContainerKind() == Sema::OCK_None)
2234 assert(AtEnd.isValid() && "Invalid location for '@end'");
2236 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
2237 Decl *ClassDecl = cast<Decl>(OCD);
2239 bool isInterfaceDeclKind =
2240 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
2241 || isa<ObjCProtocolDecl>(ClassDecl);
2242 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
2244 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
2245 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
2246 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
2248 for (unsigned i = 0; i < allNum; i++ ) {
2249 ObjCMethodDecl *Method =
2250 cast_or_null<ObjCMethodDecl>(allMethods[i]);
2252 if (!Method) continue; // Already issued a diagnostic.
2253 if (Method->isInstanceMethod()) {
2254 /// Check for instance method of the same name with incompatible types
2255 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
2256 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
2258 if ((isInterfaceDeclKind && PrevMethod && !match)
2259 || (checkIdenticalMethods && match)) {
2260 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
2261 << Method->getDeclName();
2262 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2263 Method->setInvalidDecl();
2266 Method->setAsRedeclaration(PrevMethod);
2267 if (!Context.getSourceManager().isInSystemHeader(
2268 Method->getLocation()))
2269 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
2270 << Method->getDeclName();
2271 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2273 InsMap[Method->getSelector()] = Method;
2274 /// The following allows us to typecheck messages to "id".
2275 AddInstanceMethodToGlobalPool(Method);
2276 // verify that the instance method conforms to the same definition of
2277 // parent methods if it shadows one.
2278 CompareMethodParamsInBaseAndSuper(ClassDecl, Method, true);
2281 /// Check for class method of the same name with incompatible types
2282 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
2283 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
2285 if ((isInterfaceDeclKind && PrevMethod && !match)
2286 || (checkIdenticalMethods && match)) {
2287 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
2288 << Method->getDeclName();
2289 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2290 Method->setInvalidDecl();
2293 Method->setAsRedeclaration(PrevMethod);
2294 if (!Context.getSourceManager().isInSystemHeader(
2295 Method->getLocation()))
2296 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
2297 << Method->getDeclName();
2298 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2300 ClsMap[Method->getSelector()] = Method;
2301 /// The following allows us to typecheck messages to "Class".
2302 AddFactoryMethodToGlobalPool(Method);
2303 // verify that the class method conforms to the same definition of
2304 // parent methods if it shadows one.
2305 CompareMethodParamsInBaseAndSuper(ClassDecl, Method, false);
2309 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
2310 // Compares properties declared in this class to those of its
2312 ComparePropertiesInBaseAndSuper(I);
2313 CompareProperties(I, I);
2314 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
2315 // Categories are used to extend the class by declaring new methods.
2316 // By the same token, they are also used to add new properties. No
2317 // need to compare the added property to those in the class.
2319 // Compare protocol properties with those in category
2320 CompareProperties(C, C);
2321 if (C->IsClassExtension()) {
2322 ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
2323 DiagnoseClassExtensionDupMethods(C, CCPrimary);
2326 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
2327 if (CDecl->getIdentifier())
2328 // ProcessPropertyDecl is responsible for diagnosing conflicts with any
2329 // user-defined setter/getter. It also synthesizes setter/getter methods
2330 // and adds them to the DeclContext and global method pools.
2331 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
2332 E = CDecl->prop_end();
2334 ProcessPropertyDecl(*I, CDecl);
2335 CDecl->setAtEndRange(AtEnd);
2337 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
2338 IC->setAtEndRange(AtEnd);
2339 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
2340 // Any property declared in a class extension might have user
2341 // declared setter or getter in current class extension or one
2342 // of the other class extensions. Mark them as synthesized as
2343 // property will be synthesized when property with same name is
2344 // seen in the @implementation.
2345 for (const ObjCCategoryDecl *ClsExtDecl =
2346 IDecl->getFirstClassExtension();
2347 ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
2348 for (ObjCContainerDecl::prop_iterator I = ClsExtDecl->prop_begin(),
2349 E = ClsExtDecl->prop_end(); I != E; ++I) {
2350 ObjCPropertyDecl *Property = (*I);
2351 // Skip over properties declared @dynamic
2352 if (const ObjCPropertyImplDecl *PIDecl
2353 = IC->FindPropertyImplDecl(Property->getIdentifier()))
2354 if (PIDecl->getPropertyImplementation()
2355 == ObjCPropertyImplDecl::Dynamic)
2358 for (const ObjCCategoryDecl *CExtDecl =
2359 IDecl->getFirstClassExtension();
2360 CExtDecl; CExtDecl = CExtDecl->getNextClassExtension()) {
2361 if (ObjCMethodDecl *GetterMethod =
2362 CExtDecl->getInstanceMethod(Property->getGetterName()))
2363 GetterMethod->setSynthesized(true);
2364 if (!Property->isReadOnly())
2365 if (ObjCMethodDecl *SetterMethod =
2366 CExtDecl->getInstanceMethod(Property->getSetterName()))
2367 SetterMethod->setSynthesized(true);
2371 ImplMethodsVsClassMethods(S, IC, IDecl);
2372 AtomicPropertySetterGetterRules(IC, IDecl);
2373 DiagnoseOwningPropertyGetterSynthesis(IC);
2375 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
2376 if (IDecl->getSuperClass() == NULL) {
2377 // This class has no superclass, so check that it has been marked with
2378 // __attribute((objc_root_class)).
2379 if (!HasRootClassAttr) {
2380 SourceLocation DeclLoc(IDecl->getLocation());
2381 SourceLocation SuperClassLoc(PP.getLocForEndOfToken(DeclLoc));
2382 Diag(DeclLoc, diag::warn_objc_root_class_missing)
2383 << IDecl->getIdentifier();
2384 // See if NSObject is in the current scope, and if it is, suggest
2385 // adding " : NSObject " to the class declaration.
2386 NamedDecl *IF = LookupSingleName(TUScope,
2387 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
2388 DeclLoc, LookupOrdinaryName);
2389 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
2390 if (NSObjectDecl && NSObjectDecl->getDefinition()) {
2391 Diag(SuperClassLoc, diag::note_objc_needs_superclass)
2392 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
2394 Diag(SuperClassLoc, diag::note_objc_needs_superclass);
2397 } else if (HasRootClassAttr) {
2398 // Complain that only root classes may have this attribute.
2399 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
2402 if (LangOpts.ObjCNonFragileABI2) {
2403 while (IDecl->getSuperClass()) {
2404 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
2405 IDecl = IDecl->getSuperClass();
2409 SetIvarInitializers(IC);
2410 } else if (ObjCCategoryImplDecl* CatImplClass =
2411 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
2412 CatImplClass->setAtEndRange(AtEnd);
2414 // Find category interface decl and then check that all methods declared
2415 // in this interface are implemented in the category @implementation.
2416 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
2417 for (ObjCCategoryDecl *Categories = IDecl->getCategoryList();
2418 Categories; Categories = Categories->getNextClassCategory()) {
2419 if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
2420 ImplMethodsVsClassMethods(S, CatImplClass, Categories);
2426 if (isInterfaceDeclKind) {
2427 // Reject invalid vardecls.
2428 for (unsigned i = 0; i != tuvNum; i++) {
2429 DeclGroupRef DG = allTUVars[i].getAsVal<DeclGroupRef>();
2430 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
2431 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
2432 if (!VDecl->hasExternalStorage())
2433 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
2437 ActOnObjCContainerFinishDefinition();
2439 for (unsigned i = 0; i != tuvNum; i++) {
2440 DeclGroupRef DG = allTUVars[i].getAsVal<DeclGroupRef>();
2441 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
2442 (*I)->setTopLevelDeclInObjCContainer();
2443 Consumer.HandleTopLevelDeclInObjCContainer(DG);
2450 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
2451 /// objective-c's type qualifier from the parser version of the same info.
2452 static Decl::ObjCDeclQualifier
2453 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
2454 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
2458 bool containsInvalidMethodImplAttribute(ObjCMethodDecl *IMD,
2460 // If method is only declared in implementation (private method),
2461 // No need to issue any diagnostics on method definition with attributes.
2465 // method declared in interface has no attribute.
2466 // But implementation has attributes. This is invalid
2467 if (!IMD->hasAttrs())
2470 const AttrVec &D = IMD->getAttrs();
2471 if (D.size() != A.size())
2474 // attributes on method declaration and definition must match exactly.
2475 // Note that we have at most a couple of attributes on methods, so this
2476 // n*n search is good enough.
2477 for (AttrVec::const_iterator i = A.begin(), e = A.end(); i != e; ++i) {
2479 for (AttrVec::const_iterator i1 = D.begin(), e1 = D.end(); i1 != e1; ++i1) {
2480 if ((*i)->getKind() == (*i1)->getKind()) {
2492 /// \brief Describes the compatibility of a result type with its method.
2493 enum ResultTypeCompatibilityKind {
2500 /// \brief Check whether the declared result type of the given Objective-C
2501 /// method declaration is compatible with the method's class.
2503 static ResultTypeCompatibilityKind
2504 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
2505 ObjCInterfaceDecl *CurrentClass) {
2506 QualType ResultType = Method->getResultType();
2508 // If an Objective-C method inherits its related result type, then its
2509 // declared result type must be compatible with its own class type. The
2510 // declared result type is compatible if:
2511 if (const ObjCObjectPointerType *ResultObjectType
2512 = ResultType->getAs<ObjCObjectPointerType>()) {
2513 // - it is id or qualified id, or
2514 if (ResultObjectType->isObjCIdType() ||
2515 ResultObjectType->isObjCQualifiedIdType())
2516 return RTC_Compatible;
2519 if (ObjCInterfaceDecl *ResultClass
2520 = ResultObjectType->getInterfaceDecl()) {
2521 // - it is the same as the method's class type, or
2522 if (declaresSameEntity(CurrentClass, ResultClass))
2523 return RTC_Compatible;
2525 // - it is a superclass of the method's class type
2526 if (ResultClass->isSuperClassOf(CurrentClass))
2527 return RTC_Compatible;
2530 // Any Objective-C pointer type might be acceptable for a protocol
2531 // method; we just don't know.
2536 return RTC_Incompatible;
2540 /// A helper class for searching for methods which a particular method
2542 class OverrideSearch {
2545 ObjCMethodDecl *Method;
2546 llvm::SmallPtrSet<ObjCContainerDecl*, 128> Searched;
2547 llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden;
2551 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
2552 Selector selector = method->getSelector();
2554 // Bypass this search if we've never seen an instance/class method
2555 // with this selector before.
2556 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
2557 if (it == S.MethodPool.end()) {
2558 if (!S.ExternalSource) return;
2559 S.ReadMethodPool(selector);
2561 it = S.MethodPool.find(selector);
2562 if (it == S.MethodPool.end())
2565 ObjCMethodList &list =
2566 method->isInstanceMethod() ? it->second.first : it->second.second;
2567 if (!list.Method) return;
2569 ObjCContainerDecl *container
2570 = cast<ObjCContainerDecl>(method->getDeclContext());
2572 // Prevent the search from reaching this container again. This is
2573 // important with categories, which override methods from the
2574 // interface and each other.
2575 Searched.insert(container);
2576 searchFromContainer(container);
2579 typedef llvm::SmallPtrSet<ObjCMethodDecl*, 128>::iterator iterator;
2580 iterator begin() const { return Overridden.begin(); }
2581 iterator end() const { return Overridden.end(); }
2584 void searchFromContainer(ObjCContainerDecl *container) {
2585 if (container->isInvalidDecl()) return;
2587 switch (container->getDeclKind()) {
2588 #define OBJCCONTAINER(type, base) \
2590 searchFrom(cast<type##Decl>(container)); \
2592 #define ABSTRACT_DECL(expansion)
2593 #define DECL(type, base) \
2595 #include "clang/AST/DeclNodes.inc"
2596 llvm_unreachable("not an ObjC container!");
2600 void searchFrom(ObjCProtocolDecl *protocol) {
2601 if (!protocol->hasDefinition())
2604 // A method in a protocol declaration overrides declarations from
2605 // referenced ("parent") protocols.
2606 search(protocol->getReferencedProtocols());
2609 void searchFrom(ObjCCategoryDecl *category) {
2610 // A method in a category declaration overrides declarations from
2611 // the main class and from protocols the category references.
2612 search(category->getClassInterface());
2613 search(category->getReferencedProtocols());
2616 void searchFrom(ObjCCategoryImplDecl *impl) {
2617 // A method in a category definition that has a category
2618 // declaration overrides declarations from the category
2620 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
2623 // Otherwise it overrides declarations from the class.
2625 search(impl->getClassInterface());
2629 void searchFrom(ObjCInterfaceDecl *iface) {
2630 // A method in a class declaration overrides declarations from
2631 if (!iface->hasDefinition())
2635 for (ObjCCategoryDecl *category = iface->getCategoryList();
2636 category; category = category->getNextClassCategory())
2639 // - the super class, and
2640 if (ObjCInterfaceDecl *super = iface->getSuperClass())
2643 // - any referenced protocols.
2644 search(iface->getReferencedProtocols());
2647 void searchFrom(ObjCImplementationDecl *impl) {
2648 // A method in a class implementation overrides declarations from
2649 // the class interface.
2650 search(impl->getClassInterface());
2654 void search(const ObjCProtocolList &protocols) {
2655 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
2660 void search(ObjCContainerDecl *container) {
2661 // Abort if we've already searched this container.
2662 if (!Searched.insert(container)) return;
2664 // Check for a method in this container which matches this selector.
2665 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
2666 Method->isInstanceMethod());
2668 // If we find one, record it and bail out.
2670 Overridden.insert(meth);
2674 // Otherwise, search for methods that a hypothetical method here
2675 // would have overridden.
2677 // Note that we're now in a recursive case.
2680 searchFromContainer(container);
2685 Decl *Sema::ActOnMethodDeclaration(
2687 SourceLocation MethodLoc, SourceLocation EndLoc,
2688 tok::TokenKind MethodType,
2689 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
2690 ArrayRef<SourceLocation> SelectorLocs,
2692 // optional arguments. The number of types/arguments is obtained
2693 // from the Sel.getNumArgs().
2694 ObjCArgInfo *ArgInfo,
2695 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
2696 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
2697 bool isVariadic, bool MethodDefinition) {
2698 // Make sure we can establish a context for the method.
2699 if (!CurContext->isObjCContainer()) {
2700 Diag(MethodLoc, diag::error_missing_method_context);
2703 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
2704 Decl *ClassDecl = cast<Decl>(OCD);
2705 QualType resultDeclType;
2707 bool HasRelatedResultType = false;
2708 TypeSourceInfo *ResultTInfo = 0;
2710 resultDeclType = GetTypeFromParser(ReturnType, &ResultTInfo);
2712 // Methods cannot return interface types. All ObjC objects are
2713 // passed by reference.
2714 if (resultDeclType->isObjCObjectType()) {
2715 Diag(MethodLoc, diag::err_object_cannot_be_passed_returned_by_value)
2716 << 0 << resultDeclType;
2720 HasRelatedResultType = (resultDeclType == Context.getObjCInstanceType());
2721 } else { // get the type for "id".
2722 resultDeclType = Context.getObjCIdType();
2723 Diag(MethodLoc, diag::warn_missing_method_return_type)
2724 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
2727 ObjCMethodDecl* ObjCMethod =
2728 ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel,
2732 MethodType == tok::minus, isVariadic,
2733 /*isSynthesized=*/false,
2734 /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
2735 MethodDeclKind == tok::objc_optional
2736 ? ObjCMethodDecl::Optional
2737 : ObjCMethodDecl::Required,
2738 HasRelatedResultType);
2740 SmallVector<ParmVarDecl*, 16> Params;
2742 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
2746 if (ArgInfo[i].Type == 0) {
2747 ArgType = Context.getObjCIdType();
2750 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
2751 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
2752 ArgType = Context.getAdjustedParameterType(ArgType);
2755 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
2756 LookupOrdinaryName, ForRedeclaration);
2758 if (R.isSingleResult()) {
2759 NamedDecl *PrevDecl = R.getFoundDecl();
2760 if (S->isDeclScope(PrevDecl)) {
2761 Diag(ArgInfo[i].NameLoc,
2762 (MethodDefinition ? diag::warn_method_param_redefinition
2763 : diag::warn_method_param_declaration))
2765 Diag(PrevDecl->getLocation(),
2766 diag::note_previous_declaration);
2770 SourceLocation StartLoc = DI
2771 ? DI->getTypeLoc().getBeginLoc()
2772 : ArgInfo[i].NameLoc;
2774 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
2775 ArgInfo[i].NameLoc, ArgInfo[i].Name,
2776 ArgType, DI, SC_None, SC_None);
2778 Param->setObjCMethodScopeInfo(i);
2780 Param->setObjCDeclQualifier(
2781 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
2783 // Apply the attributes to the parameter.
2784 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
2786 if (Param->hasAttr<BlocksAttr>()) {
2787 Diag(Param->getLocation(), diag::err_block_on_nonlocal);
2788 Param->setInvalidDecl();
2791 IdResolver.AddDecl(Param);
2793 Params.push_back(Param);
2796 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
2797 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
2798 QualType ArgType = Param->getType();
2799 if (ArgType.isNull())
2800 ArgType = Context.getObjCIdType();
2802 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
2803 ArgType = Context.getAdjustedParameterType(ArgType);
2804 if (ArgType->isObjCObjectType()) {
2805 Diag(Param->getLocation(),
2806 diag::err_object_cannot_be_passed_returned_by_value)
2808 Param->setInvalidDecl();
2810 Param->setDeclContext(ObjCMethod);
2812 Params.push_back(Param);
2815 ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
2816 ObjCMethod->setObjCDeclQualifier(
2817 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
2820 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
2822 // Add the method now.
2823 const ObjCMethodDecl *PrevMethod = 0;
2824 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
2825 if (MethodType == tok::minus) {
2826 PrevMethod = ImpDecl->getInstanceMethod(Sel);
2827 ImpDecl->addInstanceMethod(ObjCMethod);
2829 PrevMethod = ImpDecl->getClassMethod(Sel);
2830 ImpDecl->addClassMethod(ObjCMethod);
2833 ObjCMethodDecl *IMD = 0;
2834 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface())
2835 IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
2836 ObjCMethod->isInstanceMethod());
2837 if (ObjCMethod->hasAttrs() &&
2838 containsInvalidMethodImplAttribute(IMD, ObjCMethod->getAttrs())) {
2839 SourceLocation MethodLoc = IMD->getLocation();
2840 if (!getSourceManager().isInSystemHeader(MethodLoc)) {
2841 Diag(EndLoc, diag::warn_attribute_method_def);
2842 Diag(MethodLoc, diag::note_method_declared_at)
2843 << ObjCMethod->getDeclName();
2847 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
2851 // You can never have two method definitions with the same name.
2852 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
2853 << ObjCMethod->getDeclName();
2854 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2857 // If this Objective-C method does not have a related result type, but we
2858 // are allowed to infer related result types, try to do so based on the
2860 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
2861 if (!CurrentClass) {
2862 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
2863 CurrentClass = Cat->getClassInterface();
2864 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
2865 CurrentClass = Impl->getClassInterface();
2866 else if (ObjCCategoryImplDecl *CatImpl
2867 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
2868 CurrentClass = CatImpl->getClassInterface();
2871 ResultTypeCompatibilityKind RTC
2872 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
2874 // Search for overridden methods and merge information down from them.
2875 OverrideSearch overrides(*this, ObjCMethod);
2876 for (OverrideSearch::iterator
2877 i = overrides.begin(), e = overrides.end(); i != e; ++i) {
2878 ObjCMethodDecl *overridden = *i;
2880 // Propagate down the 'related result type' bit from overridden methods.
2881 if (RTC != RTC_Incompatible && overridden->hasRelatedResultType())
2882 ObjCMethod->SetRelatedResultType();
2884 // Then merge the declarations.
2885 mergeObjCMethodDecls(ObjCMethod, overridden);
2887 // Check for overriding methods
2888 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
2889 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
2890 CheckConflictingOverridingMethod(ObjCMethod, overridden,
2891 isa<ObjCProtocolDecl>(overridden->getDeclContext()));
2894 bool ARCError = false;
2895 if (getLangOpts().ObjCAutoRefCount)
2896 ARCError = CheckARCMethodDecl(*this, ObjCMethod);
2898 // Infer the related result type when possible.
2899 if (!ARCError && RTC == RTC_Compatible &&
2900 !ObjCMethod->hasRelatedResultType() &&
2901 LangOpts.ObjCInferRelatedResultType) {
2902 bool InferRelatedResultType = false;
2903 switch (ObjCMethod->getMethodFamily()) {
2908 case OMF_mutableCopy:
2910 case OMF_retainCount:
2911 case OMF_performSelector:
2916 InferRelatedResultType = ObjCMethod->isClassMethod();
2920 case OMF_autorelease:
2923 InferRelatedResultType = ObjCMethod->isInstanceMethod();
2927 if (InferRelatedResultType)
2928 ObjCMethod->SetRelatedResultType();
2934 bool Sema::CheckObjCDeclScope(Decl *D) {
2935 // Following is also an error. But it is caused by a missing @end
2936 // and diagnostic is issued elsewhere.
2937 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
2940 // If we switched context to translation unit while we are still lexically in
2941 // an objc container, it means the parser missed emitting an error.
2942 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
2945 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
2946 D->setInvalidDecl();
2951 /// Called whenever @defs(ClassName) is encountered in the source. Inserts the
2952 /// instance variables of ClassName into Decls.
2953 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2954 IdentifierInfo *ClassName,
2955 SmallVectorImpl<Decl*> &Decls) {
2956 // Check that ClassName is a valid class
2957 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
2959 Diag(DeclStart, diag::err_undef_interface) << ClassName;
2962 if (LangOpts.ObjCNonFragileABI) {
2963 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
2967 // Collect the instance variables
2968 SmallVector<const ObjCIvarDecl*, 32> Ivars;
2969 Context.DeepCollectObjCIvars(Class, true, Ivars);
2970 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
2971 for (unsigned i = 0; i < Ivars.size(); i++) {
2972 const FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
2973 RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
2974 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
2975 /*FIXME: StartL=*/ID->getLocation(),
2977 ID->getIdentifier(), ID->getType(),
2979 Decls.push_back(FD);
2982 // Introduce all of these fields into the appropriate scope.
2983 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
2984 D != Decls.end(); ++D) {
2985 FieldDecl *FD = cast<FieldDecl>(*D);
2986 if (getLangOpts().CPlusPlus)
2987 PushOnScopeChains(cast<FieldDecl>(FD), S);
2988 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
2989 Record->addDecl(FD);
2993 /// \brief Build a type-check a new Objective-C exception variable declaration.
2994 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
2995 SourceLocation StartLoc,
2996 SourceLocation IdLoc,
2999 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
3000 // duration shall not be qualified by an address-space qualifier."
3001 // Since all parameters have automatic store duration, they can not have
3002 // an address space.
3003 if (T.getAddressSpace() != 0) {
3004 Diag(IdLoc, diag::err_arg_with_address_space);
3008 // An @catch parameter must be an unqualified object pointer type;
3009 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
3011 // Don't do any further checking.
3012 } else if (T->isDependentType()) {
3013 // Okay: we don't know what this type will instantiate to.
3014 } else if (!T->isObjCObjectPointerType()) {
3016 Diag(IdLoc ,diag::err_catch_param_not_objc_type);
3017 } else if (T->isObjCQualifiedIdType()) {
3019 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
3022 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
3023 T, TInfo, SC_None, SC_None);
3024 New->setExceptionVariable(true);
3026 // In ARC, infer 'retaining' for variables of retainable type.
3027 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
3031 New->setInvalidDecl();
3035 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
3036 const DeclSpec &DS = D.getDeclSpec();
3038 // We allow the "register" storage class on exception variables because
3039 // GCC did, but we drop it completely. Any other storage class is an error.
3040 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
3041 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
3042 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
3043 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
3044 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
3045 << DS.getStorageClassSpec();
3047 if (D.getDeclSpec().isThreadSpecified())
3048 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
3049 D.getMutableDeclSpec().ClearStorageClassSpecs();
3051 DiagnoseFunctionSpecifiers(D);
3053 // Check that there are no default arguments inside the type of this
3054 // exception object (C++ only).
3055 if (getLangOpts().CPlusPlus)
3056 CheckExtraCXXDefaultArguments(D);
3058 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3059 QualType ExceptionType = TInfo->getType();
3061 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
3062 D.getSourceRange().getBegin(),
3063 D.getIdentifierLoc(),
3067 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
3068 if (D.getCXXScopeSpec().isSet()) {
3069 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
3070 << D.getCXXScopeSpec().getRange();
3071 New->setInvalidDecl();
3074 // Add the parameter declaration into this scope.
3076 if (D.getIdentifier())
3077 IdResolver.AddDecl(New);
3079 ProcessDeclAttributes(S, New, D);
3081 if (New->hasAttr<BlocksAttr>())
3082 Diag(New->getLocation(), diag::err_block_on_nonlocal);
3086 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3088 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3089 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
3090 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
3091 Iv= Iv->getNextIvar()) {
3092 QualType QT = Context.getBaseElementType(Iv->getType());
3093 if (QT->isRecordType())
3094 Ivars.push_back(Iv);
3098 void Sema::DiagnoseUseOfUnimplementedSelectors() {
3099 // Load referenced selectors from the external source.
3100 if (ExternalSource) {
3101 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
3102 ExternalSource->ReadReferencedSelectors(Sels);
3103 for (unsigned I = 0, N = Sels.size(); I != N; ++I)
3104 ReferencedSelectors[Sels[I].first] = Sels[I].second;
3107 // Warning will be issued only when selector table is
3108 // generated (which means there is at lease one implementation
3109 // in the TU). This is to match gcc's behavior.
3110 if (ReferencedSelectors.empty() ||
3111 !Context.AnyObjCImplementation())
3113 for (llvm::DenseMap<Selector, SourceLocation>::iterator S =
3114 ReferencedSelectors.begin(),
3115 E = ReferencedSelectors.end(); S != E; ++S) {
3116 Selector Sel = (*S).first;
3117 if (!LookupImplementedMethodInGlobalPool(Sel))
3118 Diag((*S).second, diag::warn_unimplemented_selector) << Sel;