1 //===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for Objective C declarations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/SemaInternal.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/DeclObjC.h" 19 #include "clang/AST/Expr.h" 20 #include "clang/AST/ExprObjC.h" 21 #include "clang/Basic/SourceManager.h" 22 #include "clang/Lex/Preprocessor.h" 23 #include "clang/Sema/DeclSpec.h" 24 #include "clang/Sema/ExternalSemaSource.h" 25 #include "clang/Sema/Lookup.h" 26 #include "clang/Sema/Scope.h" 27 #include "clang/Sema/ScopeInfo.h" 28 #include "llvm/ADT/DenseSet.h" 29 30 using namespace clang; 31 32 /// Check whether the given method, which must be in the 'init' 33 /// family, is a valid member of that family. 34 /// 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 37 /// receiver type 38 /// 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; 44 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). 48 49 // We ignore protocols here. Should we? What about Class? 50 51 const ObjCObjectType *result = method->getResultType() 52 ->castAs<ObjCObjectPointerType>()->getObjectType(); 53 54 if (result->isObjCId()) { 55 return false; 56 } else if (result->isObjCClass()) { 57 // fall through: always an error 58 } else { 59 ObjCInterfaceDecl *resultClass = result->getInterface(); 60 assert(resultClass && "unexpected object type!"); 61 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())) 67 return false; 68 69 // Otherwise, we try to compare class types. 70 } else { 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()) 76 return false; 77 78 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>() 79 ->getInterfaceDecl(); 80 81 // This can be null for calls to e.g. id<Foo>. 82 if (!receiverClass) return false; 83 } else { 84 receiverClass = method->getClassInterface(); 85 assert(receiverClass && "method not associated with a class!"); 86 } 87 88 // If either class is a subclass of the other, it's fine. 89 if (receiverClass->isSuperClassOf(resultClass) || 90 resultClass->isSuperClassOf(receiverClass)) 91 return false; 92 } 93 } 94 95 SourceLocation loc = method->getLocation(); 96 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")); 102 return true; 103 } 104 105 // Otherwise, it's an error. 106 Diag(loc, diag::err_arc_init_method_unrelated_result_type); 107 method->setInvalidDecl(); 108 return true; 109 } 110 111 void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, 112 const ObjCMethodDecl *Overridden) { 113 if (Overridden->hasRelatedResultType() && 114 !NewMethod->hasRelatedResultType()) { 115 // This can only happen when the method follows a naming convention that 116 // implies a related result type, and the original (overridden) method has 117 // a suitable return type, but the new (overriding) method does not have 118 // a suitable return type. 119 QualType ResultType = NewMethod->getResultType(); 120 SourceRange ResultTypeRange; 121 if (const TypeSourceInfo *ResultTypeInfo 122 = NewMethod->getResultTypeSourceInfo()) 123 ResultTypeRange = ResultTypeInfo->getTypeLoc().getSourceRange(); 124 125 // Figure out which class this method is part of, if any. 126 ObjCInterfaceDecl *CurrentClass 127 = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext()); 128 if (!CurrentClass) { 129 DeclContext *DC = NewMethod->getDeclContext(); 130 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC)) 131 CurrentClass = Cat->getClassInterface(); 132 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC)) 133 CurrentClass = Impl->getClassInterface(); 134 else if (ObjCCategoryImplDecl *CatImpl 135 = dyn_cast<ObjCCategoryImplDecl>(DC)) 136 CurrentClass = CatImpl->getClassInterface(); 137 } 138 139 if (CurrentClass) { 140 Diag(NewMethod->getLocation(), 141 diag::warn_related_result_type_compatibility_class) 142 << Context.getObjCInterfaceType(CurrentClass) 143 << ResultType 144 << ResultTypeRange; 145 } else { 146 Diag(NewMethod->getLocation(), 147 diag::warn_related_result_type_compatibility_protocol) 148 << ResultType 149 << ResultTypeRange; 150 } 151 152 if (ObjCMethodFamily Family = Overridden->getMethodFamily()) 153 Diag(Overridden->getLocation(), 154 diag::note_related_result_type_family) 155 << /*overridden method*/ 0 156 << Family; 157 else 158 Diag(Overridden->getLocation(), 159 diag::note_related_result_type_overridden); 160 } 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) 167 << "method"; 168 } 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) 174 << "method"; 175 } 176 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(), 177 oe = Overridden->param_end(); 178 for (ObjCMethodDecl::param_iterator 179 ni = NewMethod->param_begin(), ne = NewMethod->param_end(); 180 ni != ne && oi != oe; ++ni, ++oi) { 181 const ParmVarDecl *oldDecl = (*oi); 182 ParmVarDecl *newDecl = (*ni); 183 if (newDecl->hasAttr<NSConsumedAttr>() != 184 oldDecl->hasAttr<NSConsumedAttr>()) { 185 Diag(newDecl->getLocation(), 186 diag::err_nsconsumed_attribute_mismatch); 187 Diag(oldDecl->getLocation(), diag::note_previous_decl) 188 << "parameter"; 189 } 190 } 191 } 192 } 193 194 /// \brief Check a method declaration for compatibility with the Objective-C 195 /// ARC conventions. 196 static bool CheckARCMethodDecl(Sema &S, ObjCMethodDecl *method) { 197 ObjCMethodFamily family = method->getMethodFamily(); 198 switch (family) { 199 case OMF_None: 200 case OMF_finalize: 201 case OMF_retain: 202 case OMF_release: 203 case OMF_autorelease: 204 case OMF_retainCount: 205 case OMF_self: 206 case OMF_performSelector: 207 return false; 208 209 case OMF_dealloc: 210 if (!S.Context.hasSameType(method->getResultType(), S.Context.VoidTy)) { 211 SourceRange ResultTypeRange; 212 if (const TypeSourceInfo *ResultTypeInfo 213 = method->getResultTypeSourceInfo()) 214 ResultTypeRange = ResultTypeInfo->getTypeLoc().getSourceRange(); 215 if (ResultTypeRange.isInvalid()) 216 S.Diag(method->getLocation(), diag::error_dealloc_bad_result_type) 217 << method->getResultType() 218 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)"); 219 else 220 S.Diag(method->getLocation(), diag::error_dealloc_bad_result_type) 221 << method->getResultType() 222 << FixItHint::CreateReplacement(ResultTypeRange, "void"); 223 return true; 224 } 225 return false; 226 227 case OMF_init: 228 // If the method doesn't obey the init rules, don't bother annotating it. 229 if (S.checkInitMethod(method, QualType())) 230 return true; 231 232 method->addAttr(new (S.Context) NSConsumesSelfAttr(SourceLocation(), 233 S.Context)); 234 235 // Don't add a second copy of this attribute, but otherwise don't 236 // let it be suppressed. 237 if (method->hasAttr<NSReturnsRetainedAttr>()) 238 return false; 239 break; 240 241 case OMF_alloc: 242 case OMF_copy: 243 case OMF_mutableCopy: 244 case OMF_new: 245 if (method->hasAttr<NSReturnsRetainedAttr>() || 246 method->hasAttr<NSReturnsNotRetainedAttr>() || 247 method->hasAttr<NSReturnsAutoreleasedAttr>()) 248 return false; 249 break; 250 } 251 252 method->addAttr(new (S.Context) NSReturnsRetainedAttr(SourceLocation(), 253 S.Context)); 254 return false; 255 } 256 257 static void DiagnoseObjCImplementedDeprecations(Sema &S, 258 NamedDecl *ND, 259 SourceLocation ImplLoc, 260 int select) { 261 if (ND && ND->isDeprecated()) { 262 S.Diag(ImplLoc, diag::warn_deprecated_def) << select; 263 if (select == 0) 264 S.Diag(ND->getLocation(), diag::note_method_declared_at) 265 << ND->getDeclName(); 266 else 267 S.Diag(ND->getLocation(), diag::note_previous_decl) << "class"; 268 } 269 } 270 271 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global 272 /// pool. 273 void Sema::AddAnyMethodToGlobalPool(Decl *D) { 274 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D); 275 276 // If we don't have a valid method decl, simply return. 277 if (!MDecl) 278 return; 279 if (MDecl->isInstanceMethod()) 280 AddInstanceMethodToGlobalPool(MDecl, true); 281 else 282 AddFactoryMethodToGlobalPool(MDecl, true); 283 } 284 285 /// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer 286 /// has explicit ownership attribute; false otherwise. 287 static bool 288 HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) { 289 QualType T = Param->getType(); 290 291 if (const PointerType *PT = T->getAs<PointerType>()) { 292 T = PT->getPointeeType(); 293 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) { 294 T = RT->getPointeeType(); 295 } else { 296 return true; 297 } 298 299 // If we have a lifetime qualifier, but it's local, we must have 300 // inferred it. So, it is implicit. 301 return !T.getLocalQualifiers().hasObjCLifetime(); 302 } 303 304 /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible 305 /// and user declared, in the method definition's AST. 306 void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) { 307 assert((getCurMethodDecl() == 0) && "Methodparsing confused"); 308 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D); 309 310 // If we don't have a valid method decl, simply return. 311 if (!MDecl) 312 return; 313 314 // Allow all of Sema to see that we are entering a method definition. 315 PushDeclContext(FnBodyScope, MDecl); 316 PushFunctionScope(); 317 318 // Create Decl objects for each parameter, entrring them in the scope for 319 // binding to their use. 320 321 // Insert the invisible arguments, self and _cmd! 322 MDecl->createImplicitParams(Context, MDecl->getClassInterface()); 323 324 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope); 325 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope); 326 327 // Introduce all of the other parameters into this scope. 328 for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(), 329 E = MDecl->param_end(); PI != E; ++PI) { 330 ParmVarDecl *Param = (*PI); 331 if (!Param->isInvalidDecl() && 332 RequireCompleteType(Param->getLocation(), Param->getType(), 333 diag::err_typecheck_decl_incomplete_type)) 334 Param->setInvalidDecl(); 335 if (!Param->isInvalidDecl() && 336 getLangOpts().ObjCAutoRefCount && 337 !HasExplicitOwnershipAttr(*this, Param)) 338 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) << 339 Param->getType(); 340 341 if ((*PI)->getIdentifier()) 342 PushOnScopeChains(*PI, FnBodyScope); 343 } 344 345 // In ARC, disallow definition of retain/release/autorelease/retainCount 346 if (getLangOpts().ObjCAutoRefCount) { 347 switch (MDecl->getMethodFamily()) { 348 case OMF_retain: 349 case OMF_retainCount: 350 case OMF_release: 351 case OMF_autorelease: 352 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def) 353 << MDecl->getSelector(); 354 break; 355 356 case OMF_None: 357 case OMF_dealloc: 358 case OMF_finalize: 359 case OMF_alloc: 360 case OMF_init: 361 case OMF_mutableCopy: 362 case OMF_copy: 363 case OMF_new: 364 case OMF_self: 365 case OMF_performSelector: 366 break; 367 } 368 } 369 370 // Warn on deprecated methods under -Wdeprecated-implementations, 371 // and prepare for warning on missing super calls. 372 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) { 373 ObjCMethodDecl *IMD = 374 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod()); 375 376 if (IMD) { 377 ObjCImplDecl *ImplDeclOfMethodDef = 378 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext()); 379 ObjCContainerDecl *ContDeclOfMethodDecl = 380 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext()); 381 ObjCImplDecl *ImplDeclOfMethodDecl = 0; 382 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl)) 383 ImplDeclOfMethodDecl = OID->getImplementation(); 384 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) 385 ImplDeclOfMethodDecl = CD->getImplementation(); 386 // No need to issue deprecated warning if deprecated mehod in class/category 387 // is being implemented in its own implementation (no overriding is involved). 388 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef) 389 DiagnoseObjCImplementedDeprecations(*this, 390 dyn_cast<NamedDecl>(IMD), 391 MDecl->getLocation(), 0); 392 } 393 394 // If this is "dealloc" or "finalize", set some bit here. 395 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false. 396 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set. 397 // Only do this if the current class actually has a superclass. 398 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) { 399 ObjCMethodFamily Family = MDecl->getMethodFamily(); 400 if (Family == OMF_dealloc) { 401 if (!(getLangOpts().ObjCAutoRefCount || 402 getLangOpts().getGC() == LangOptions::GCOnly)) 403 getCurFunction()->ObjCShouldCallSuper = true; 404 405 } else if (Family == OMF_finalize) { 406 if (Context.getLangOpts().getGC() != LangOptions::NonGC) 407 getCurFunction()->ObjCShouldCallSuper = true; 408 409 } else { 410 const ObjCMethodDecl *SuperMethod = 411 SuperClass->lookupMethod(MDecl->getSelector(), 412 MDecl->isInstanceMethod()); 413 getCurFunction()->ObjCShouldCallSuper = 414 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>()); 415 } 416 } 417 } 418 } 419 420 namespace { 421 422 // Callback to only accept typo corrections that are Objective-C classes. 423 // If an ObjCInterfaceDecl* is given to the constructor, then the validation 424 // function will reject corrections to that class. 425 class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback { 426 public: 427 ObjCInterfaceValidatorCCC() : CurrentIDecl(0) {} 428 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl) 429 : CurrentIDecl(IDecl) {} 430 431 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 432 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>(); 433 return ID && !declaresSameEntity(ID, CurrentIDecl); 434 } 435 436 private: 437 ObjCInterfaceDecl *CurrentIDecl; 438 }; 439 440 } 441 442 Decl *Sema:: 443 ActOnStartClassInterface(SourceLocation AtInterfaceLoc, 444 IdentifierInfo *ClassName, SourceLocation ClassLoc, 445 IdentifierInfo *SuperName, SourceLocation SuperLoc, 446 Decl * const *ProtoRefs, unsigned NumProtoRefs, 447 const SourceLocation *ProtoLocs, 448 SourceLocation EndProtoLoc, AttributeList *AttrList) { 449 assert(ClassName && "Missing class identifier"); 450 451 // Check for another declaration kind with the same name. 452 NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc, 453 LookupOrdinaryName, ForRedeclaration); 454 455 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 456 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName; 457 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 458 } 459 460 // Create a declaration to describe this @interface. 461 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 462 ObjCInterfaceDecl *IDecl 463 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName, 464 PrevIDecl, ClassLoc); 465 466 if (PrevIDecl) { 467 // Class already seen. Was it a definition? 468 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) { 469 Diag(AtInterfaceLoc, diag::err_duplicate_class_def) 470 << PrevIDecl->getDeclName(); 471 Diag(Def->getLocation(), diag::note_previous_definition); 472 IDecl->setInvalidDecl(); 473 } 474 } 475 476 if (AttrList) 477 ProcessDeclAttributeList(TUScope, IDecl, AttrList); 478 PushOnScopeChains(IDecl, TUScope); 479 480 // Start the definition of this class. If we're in a redefinition case, there 481 // may already be a definition, so we'll end up adding to it. 482 if (!IDecl->hasDefinition()) 483 IDecl->startDefinition(); 484 485 if (SuperName) { 486 // Check if a different kind of symbol declared in this scope. 487 PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc, 488 LookupOrdinaryName); 489 490 if (!PrevDecl) { 491 // Try to correct for a typo in the superclass name without correcting 492 // to the class we're defining. 493 ObjCInterfaceValidatorCCC Validator(IDecl); 494 if (TypoCorrection Corrected = CorrectTypo( 495 DeclarationNameInfo(SuperName, SuperLoc), LookupOrdinaryName, TUScope, 496 NULL, Validator)) { 497 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>(); 498 Diag(SuperLoc, diag::err_undef_superclass_suggest) 499 << SuperName << ClassName << PrevDecl->getDeclName(); 500 Diag(PrevDecl->getLocation(), diag::note_previous_decl) 501 << PrevDecl->getDeclName(); 502 } 503 } 504 505 if (declaresSameEntity(PrevDecl, IDecl)) { 506 Diag(SuperLoc, diag::err_recursive_superclass) 507 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc); 508 IDecl->setEndOfDefinitionLoc(ClassLoc); 509 } else { 510 ObjCInterfaceDecl *SuperClassDecl = 511 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 512 513 // Diagnose classes that inherit from deprecated classes. 514 if (SuperClassDecl) 515 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc); 516 517 if (PrevDecl && SuperClassDecl == 0) { 518 // The previous declaration was not a class decl. Check if we have a 519 // typedef. If we do, get the underlying class type. 520 if (const TypedefNameDecl *TDecl = 521 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) { 522 QualType T = TDecl->getUnderlyingType(); 523 if (T->isObjCObjectType()) { 524 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) 525 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl); 526 } 527 } 528 529 // This handles the following case: 530 // 531 // typedef int SuperClass; 532 // @interface MyClass : SuperClass {} @end 533 // 534 if (!SuperClassDecl) { 535 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName; 536 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 537 } 538 } 539 540 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) { 541 if (!SuperClassDecl) 542 Diag(SuperLoc, diag::err_undef_superclass) 543 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc); 544 else if (RequireCompleteType(SuperLoc, 545 Context.getObjCInterfaceType(SuperClassDecl), 546 diag::err_forward_superclass, 547 SuperClassDecl->getDeclName(), 548 ClassName, 549 SourceRange(AtInterfaceLoc, ClassLoc))) { 550 SuperClassDecl = 0; 551 } 552 } 553 IDecl->setSuperClass(SuperClassDecl); 554 IDecl->setSuperClassLoc(SuperLoc); 555 IDecl->setEndOfDefinitionLoc(SuperLoc); 556 } 557 } else { // we have a root class. 558 IDecl->setEndOfDefinitionLoc(ClassLoc); 559 } 560 561 // Check then save referenced protocols. 562 if (NumProtoRefs) { 563 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs, 564 ProtoLocs, Context); 565 IDecl->setEndOfDefinitionLoc(EndProtoLoc); 566 } 567 568 CheckObjCDeclScope(IDecl); 569 return ActOnObjCContainerStartDefinition(IDecl); 570 } 571 572 /// ActOnCompatibilityAlias - this action is called after complete parsing of 573 /// a \@compatibility_alias declaration. It sets up the alias relationships. 574 Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc, 575 IdentifierInfo *AliasName, 576 SourceLocation AliasLocation, 577 IdentifierInfo *ClassName, 578 SourceLocation ClassLocation) { 579 // Look for previous declaration of alias name 580 NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation, 581 LookupOrdinaryName, ForRedeclaration); 582 if (ADecl) { 583 if (isa<ObjCCompatibleAliasDecl>(ADecl)) 584 Diag(AliasLocation, diag::warn_previous_alias_decl); 585 else 586 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName; 587 Diag(ADecl->getLocation(), diag::note_previous_declaration); 588 return 0; 589 } 590 // Check for class declaration 591 NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation, 592 LookupOrdinaryName, ForRedeclaration); 593 if (const TypedefNameDecl *TDecl = 594 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) { 595 QualType T = TDecl->getUnderlyingType(); 596 if (T->isObjCObjectType()) { 597 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) { 598 ClassName = IDecl->getIdentifier(); 599 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation, 600 LookupOrdinaryName, ForRedeclaration); 601 } 602 } 603 } 604 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU); 605 if (CDecl == 0) { 606 Diag(ClassLocation, diag::warn_undef_interface) << ClassName; 607 if (CDeclU) 608 Diag(CDeclU->getLocation(), diag::note_previous_declaration); 609 return 0; 610 } 611 612 // Everything checked out, instantiate a new alias declaration AST. 613 ObjCCompatibleAliasDecl *AliasDecl = 614 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl); 615 616 if (!CheckObjCDeclScope(AliasDecl)) 617 PushOnScopeChains(AliasDecl, TUScope); 618 619 return AliasDecl; 620 } 621 622 bool Sema::CheckForwardProtocolDeclarationForCircularDependency( 623 IdentifierInfo *PName, 624 SourceLocation &Ploc, SourceLocation PrevLoc, 625 const ObjCList<ObjCProtocolDecl> &PList) { 626 627 bool res = false; 628 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(), 629 E = PList.end(); I != E; ++I) { 630 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(), 631 Ploc)) { 632 if (PDecl->getIdentifier() == PName) { 633 Diag(Ploc, diag::err_protocol_has_circular_dependency); 634 Diag(PrevLoc, diag::note_previous_definition); 635 res = true; 636 } 637 638 if (!PDecl->hasDefinition()) 639 continue; 640 641 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc, 642 PDecl->getLocation(), PDecl->getReferencedProtocols())) 643 res = true; 644 } 645 } 646 return res; 647 } 648 649 Decl * 650 Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc, 651 IdentifierInfo *ProtocolName, 652 SourceLocation ProtocolLoc, 653 Decl * const *ProtoRefs, 654 unsigned NumProtoRefs, 655 const SourceLocation *ProtoLocs, 656 SourceLocation EndProtoLoc, 657 AttributeList *AttrList) { 658 bool err = false; 659 // FIXME: Deal with AttrList. 660 assert(ProtocolName && "Missing protocol identifier"); 661 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc, 662 ForRedeclaration); 663 ObjCProtocolDecl *PDecl = 0; 664 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : 0) { 665 // If we already have a definition, complain. 666 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName; 667 Diag(Def->getLocation(), diag::note_previous_definition); 668 669 // Create a new protocol that is completely distinct from previous 670 // declarations, and do not make this protocol available for name lookup. 671 // That way, we'll end up completely ignoring the duplicate. 672 // FIXME: Can we turn this into an error? 673 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName, 674 ProtocolLoc, AtProtoInterfaceLoc, 675 /*PrevDecl=*/0); 676 PDecl->startDefinition(); 677 } else { 678 if (PrevDecl) { 679 // Check for circular dependencies among protocol declarations. This can 680 // only happen if this protocol was forward-declared. 681 ObjCList<ObjCProtocolDecl> PList; 682 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context); 683 err = CheckForwardProtocolDeclarationForCircularDependency( 684 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList); 685 } 686 687 // Create the new declaration. 688 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName, 689 ProtocolLoc, AtProtoInterfaceLoc, 690 /*PrevDecl=*/PrevDecl); 691 692 PushOnScopeChains(PDecl, TUScope); 693 PDecl->startDefinition(); 694 } 695 696 if (AttrList) 697 ProcessDeclAttributeList(TUScope, PDecl, AttrList); 698 699 // Merge attributes from previous declarations. 700 if (PrevDecl) 701 mergeDeclAttributes(PDecl, PrevDecl); 702 703 if (!err && NumProtoRefs ) { 704 /// Check then save referenced protocols. 705 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs, 706 ProtoLocs, Context); 707 } 708 709 CheckObjCDeclScope(PDecl); 710 return ActOnObjCContainerStartDefinition(PDecl); 711 } 712 713 /// FindProtocolDeclaration - This routine looks up protocols and 714 /// issues an error if they are not declared. It returns list of 715 /// protocol declarations in its 'Protocols' argument. 716 void 717 Sema::FindProtocolDeclaration(bool WarnOnDeclarations, 718 const IdentifierLocPair *ProtocolId, 719 unsigned NumProtocols, 720 SmallVectorImpl<Decl *> &Protocols) { 721 for (unsigned i = 0; i != NumProtocols; ++i) { 722 ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first, 723 ProtocolId[i].second); 724 if (!PDecl) { 725 DeclFilterCCC<ObjCProtocolDecl> Validator; 726 TypoCorrection Corrected = CorrectTypo( 727 DeclarationNameInfo(ProtocolId[i].first, ProtocolId[i].second), 728 LookupObjCProtocolName, TUScope, NULL, Validator); 729 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>())) { 730 Diag(ProtocolId[i].second, diag::err_undeclared_protocol_suggest) 731 << ProtocolId[i].first << Corrected.getCorrection(); 732 Diag(PDecl->getLocation(), diag::note_previous_decl) 733 << PDecl->getDeclName(); 734 } 735 } 736 737 if (!PDecl) { 738 Diag(ProtocolId[i].second, diag::err_undeclared_protocol) 739 << ProtocolId[i].first; 740 continue; 741 } 742 743 (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second); 744 745 // If this is a forward declaration and we are supposed to warn in this 746 // case, do it. 747 // FIXME: Recover nicely in the hidden case. 748 if (WarnOnDeclarations && 749 (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden())) 750 Diag(ProtocolId[i].second, diag::warn_undef_protocolref) 751 << ProtocolId[i].first; 752 Protocols.push_back(PDecl); 753 } 754 } 755 756 /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of 757 /// a class method in its extension. 758 /// 759 void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, 760 ObjCInterfaceDecl *ID) { 761 if (!ID) 762 return; // Possibly due to previous error 763 764 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap; 765 for (ObjCInterfaceDecl::method_iterator i = ID->meth_begin(), 766 e = ID->meth_end(); i != e; ++i) { 767 ObjCMethodDecl *MD = *i; 768 MethodMap[MD->getSelector()] = MD; 769 } 770 771 if (MethodMap.empty()) 772 return; 773 for (ObjCCategoryDecl::method_iterator i = CAT->meth_begin(), 774 e = CAT->meth_end(); i != e; ++i) { 775 ObjCMethodDecl *Method = *i; 776 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()]; 777 if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) { 778 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 779 << Method->getDeclName(); 780 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 781 } 782 } 783 } 784 785 /// ActOnForwardProtocolDeclaration - Handle \@protocol foo; 786 Sema::DeclGroupPtrTy 787 Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc, 788 const IdentifierLocPair *IdentList, 789 unsigned NumElts, 790 AttributeList *attrList) { 791 SmallVector<Decl *, 8> DeclsInGroup; 792 for (unsigned i = 0; i != NumElts; ++i) { 793 IdentifierInfo *Ident = IdentList[i].first; 794 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentList[i].second, 795 ForRedeclaration); 796 ObjCProtocolDecl *PDecl 797 = ObjCProtocolDecl::Create(Context, CurContext, Ident, 798 IdentList[i].second, AtProtocolLoc, 799 PrevDecl); 800 801 PushOnScopeChains(PDecl, TUScope); 802 CheckObjCDeclScope(PDecl); 803 804 if (attrList) 805 ProcessDeclAttributeList(TUScope, PDecl, attrList); 806 807 if (PrevDecl) 808 mergeDeclAttributes(PDecl, PrevDecl); 809 810 DeclsInGroup.push_back(PDecl); 811 } 812 813 return BuildDeclaratorGroup(DeclsInGroup.data(), DeclsInGroup.size(), false); 814 } 815 816 Decl *Sema:: 817 ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc, 818 IdentifierInfo *ClassName, SourceLocation ClassLoc, 819 IdentifierInfo *CategoryName, 820 SourceLocation CategoryLoc, 821 Decl * const *ProtoRefs, 822 unsigned NumProtoRefs, 823 const SourceLocation *ProtoLocs, 824 SourceLocation EndProtoLoc) { 825 ObjCCategoryDecl *CDecl; 826 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true); 827 828 /// Check that class of this category is already completely declared. 829 830 if (!IDecl 831 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl), 832 diag::err_category_forward_interface, 833 CategoryName == 0)) { 834 // Create an invalid ObjCCategoryDecl to serve as context for 835 // the enclosing method declarations. We mark the decl invalid 836 // to make it clear that this isn't a valid AST. 837 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc, 838 ClassLoc, CategoryLoc, CategoryName,IDecl); 839 CDecl->setInvalidDecl(); 840 CurContext->addDecl(CDecl); 841 842 if (!IDecl) 843 Diag(ClassLoc, diag::err_undef_interface) << ClassName; 844 return ActOnObjCContainerStartDefinition(CDecl); 845 } 846 847 if (!CategoryName && IDecl->getImplementation()) { 848 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName; 849 Diag(IDecl->getImplementation()->getLocation(), 850 diag::note_implementation_declared); 851 } 852 853 if (CategoryName) { 854 /// Check for duplicate interface declaration for this category 855 if (ObjCCategoryDecl *Previous 856 = IDecl->FindCategoryDeclaration(CategoryName)) { 857 // Class extensions can be declared multiple times, categories cannot. 858 Diag(CategoryLoc, diag::warn_dup_category_def) 859 << ClassName << CategoryName; 860 Diag(Previous->getLocation(), diag::note_previous_definition); 861 } 862 } 863 864 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc, 865 ClassLoc, CategoryLoc, CategoryName, IDecl); 866 // FIXME: PushOnScopeChains? 867 CurContext->addDecl(CDecl); 868 869 if (NumProtoRefs) { 870 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs, 871 ProtoLocs, Context); 872 // Protocols in the class extension belong to the class. 873 if (CDecl->IsClassExtension()) 874 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs, 875 NumProtoRefs, Context); 876 } 877 878 CheckObjCDeclScope(CDecl); 879 return ActOnObjCContainerStartDefinition(CDecl); 880 } 881 882 /// ActOnStartCategoryImplementation - Perform semantic checks on the 883 /// category implementation declaration and build an ObjCCategoryImplDecl 884 /// object. 885 Decl *Sema::ActOnStartCategoryImplementation( 886 SourceLocation AtCatImplLoc, 887 IdentifierInfo *ClassName, SourceLocation ClassLoc, 888 IdentifierInfo *CatName, SourceLocation CatLoc) { 889 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true); 890 ObjCCategoryDecl *CatIDecl = 0; 891 if (IDecl && IDecl->hasDefinition()) { 892 CatIDecl = IDecl->FindCategoryDeclaration(CatName); 893 if (!CatIDecl) { 894 // Category @implementation with no corresponding @interface. 895 // Create and install one. 896 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc, 897 ClassLoc, CatLoc, 898 CatName, IDecl); 899 CatIDecl->setImplicit(); 900 } 901 } 902 903 ObjCCategoryImplDecl *CDecl = 904 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl, 905 ClassLoc, AtCatImplLoc, CatLoc); 906 /// Check that class of this category is already completely declared. 907 if (!IDecl) { 908 Diag(ClassLoc, diag::err_undef_interface) << ClassName; 909 CDecl->setInvalidDecl(); 910 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl), 911 diag::err_undef_interface)) { 912 CDecl->setInvalidDecl(); 913 } 914 915 // FIXME: PushOnScopeChains? 916 CurContext->addDecl(CDecl); 917 918 // If the interface is deprecated/unavailable, warn/error about it. 919 if (IDecl) 920 DiagnoseUseOfDecl(IDecl, ClassLoc); 921 922 /// Check that CatName, category name, is not used in another implementation. 923 if (CatIDecl) { 924 if (CatIDecl->getImplementation()) { 925 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName 926 << CatName; 927 Diag(CatIDecl->getImplementation()->getLocation(), 928 diag::note_previous_definition); 929 } else { 930 CatIDecl->setImplementation(CDecl); 931 // Warn on implementating category of deprecated class under 932 // -Wdeprecated-implementations flag. 933 DiagnoseObjCImplementedDeprecations(*this, 934 dyn_cast<NamedDecl>(IDecl), 935 CDecl->getLocation(), 2); 936 } 937 } 938 939 CheckObjCDeclScope(CDecl); 940 return ActOnObjCContainerStartDefinition(CDecl); 941 } 942 943 Decl *Sema::ActOnStartClassImplementation( 944 SourceLocation AtClassImplLoc, 945 IdentifierInfo *ClassName, SourceLocation ClassLoc, 946 IdentifierInfo *SuperClassname, 947 SourceLocation SuperClassLoc) { 948 ObjCInterfaceDecl* IDecl = 0; 949 // Check for another declaration kind with the same name. 950 NamedDecl *PrevDecl 951 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName, 952 ForRedeclaration); 953 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 954 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName; 955 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 956 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) { 957 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl), 958 diag::warn_undef_interface); 959 } else { 960 // We did not find anything with the name ClassName; try to correct for 961 // typos in the class name. 962 ObjCInterfaceValidatorCCC Validator; 963 if (TypoCorrection Corrected = CorrectTypo( 964 DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope, 965 NULL, Validator)) { 966 // Suggest the (potentially) correct interface name. However, put the 967 // fix-it hint itself in a separate note, since changing the name in 968 // the warning would make the fix-it change semantics.However, don't 969 // provide a code-modification hint or use the typo name for recovery, 970 // because this is just a warning. The program may actually be correct. 971 IDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>(); 972 DeclarationName CorrectedName = Corrected.getCorrection(); 973 Diag(ClassLoc, diag::warn_undef_interface_suggest) 974 << ClassName << CorrectedName; 975 Diag(IDecl->getLocation(), diag::note_previous_decl) << CorrectedName 976 << FixItHint::CreateReplacement(ClassLoc, CorrectedName.getAsString()); 977 IDecl = 0; 978 } else { 979 Diag(ClassLoc, diag::warn_undef_interface) << ClassName; 980 } 981 } 982 983 // Check that super class name is valid class name 984 ObjCInterfaceDecl* SDecl = 0; 985 if (SuperClassname) { 986 // Check if a different kind of symbol declared in this scope. 987 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc, 988 LookupOrdinaryName); 989 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 990 Diag(SuperClassLoc, diag::err_redefinition_different_kind) 991 << SuperClassname; 992 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 993 } else { 994 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 995 if (SDecl && !SDecl->hasDefinition()) 996 SDecl = 0; 997 if (!SDecl) 998 Diag(SuperClassLoc, diag::err_undef_superclass) 999 << SuperClassname << ClassName; 1000 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) { 1001 // This implementation and its interface do not have the same 1002 // super class. 1003 Diag(SuperClassLoc, diag::err_conflicting_super_class) 1004 << SDecl->getDeclName(); 1005 Diag(SDecl->getLocation(), diag::note_previous_definition); 1006 } 1007 } 1008 } 1009 1010 if (!IDecl) { 1011 // Legacy case of @implementation with no corresponding @interface. 1012 // Build, chain & install the interface decl into the identifier. 1013 1014 // FIXME: Do we support attributes on the @implementation? If so we should 1015 // copy them over. 1016 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc, 1017 ClassName, /*PrevDecl=*/0, ClassLoc, 1018 true); 1019 IDecl->startDefinition(); 1020 if (SDecl) { 1021 IDecl->setSuperClass(SDecl); 1022 IDecl->setSuperClassLoc(SuperClassLoc); 1023 IDecl->setEndOfDefinitionLoc(SuperClassLoc); 1024 } else { 1025 IDecl->setEndOfDefinitionLoc(ClassLoc); 1026 } 1027 1028 PushOnScopeChains(IDecl, TUScope); 1029 } else { 1030 // Mark the interface as being completed, even if it was just as 1031 // @class ....; 1032 // declaration; the user cannot reopen it. 1033 if (!IDecl->hasDefinition()) 1034 IDecl->startDefinition(); 1035 } 1036 1037 ObjCImplementationDecl* IMPDecl = 1038 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl, 1039 ClassLoc, AtClassImplLoc); 1040 1041 if (CheckObjCDeclScope(IMPDecl)) 1042 return ActOnObjCContainerStartDefinition(IMPDecl); 1043 1044 // Check that there is no duplicate implementation of this class. 1045 if (IDecl->getImplementation()) { 1046 // FIXME: Don't leak everything! 1047 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName; 1048 Diag(IDecl->getImplementation()->getLocation(), 1049 diag::note_previous_definition); 1050 } else { // add it to the list. 1051 IDecl->setImplementation(IMPDecl); 1052 PushOnScopeChains(IMPDecl, TUScope); 1053 // Warn on implementating deprecated class under 1054 // -Wdeprecated-implementations flag. 1055 DiagnoseObjCImplementedDeprecations(*this, 1056 dyn_cast<NamedDecl>(IDecl), 1057 IMPDecl->getLocation(), 1); 1058 } 1059 return ActOnObjCContainerStartDefinition(IMPDecl); 1060 } 1061 1062 Sema::DeclGroupPtrTy 1063 Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) { 1064 SmallVector<Decl *, 64> DeclsInGroup; 1065 DeclsInGroup.reserve(Decls.size() + 1); 1066 1067 for (unsigned i = 0, e = Decls.size(); i != e; ++i) { 1068 Decl *Dcl = Decls[i]; 1069 if (!Dcl) 1070 continue; 1071 if (Dcl->getDeclContext()->isFileContext()) 1072 Dcl->setTopLevelDeclInObjCContainer(); 1073 DeclsInGroup.push_back(Dcl); 1074 } 1075 1076 DeclsInGroup.push_back(ObjCImpDecl); 1077 1078 return BuildDeclaratorGroup(DeclsInGroup.data(), DeclsInGroup.size(), false); 1079 } 1080 1081 void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, 1082 ObjCIvarDecl **ivars, unsigned numIvars, 1083 SourceLocation RBrace) { 1084 assert(ImpDecl && "missing implementation decl"); 1085 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface(); 1086 if (!IDecl) 1087 return; 1088 /// Check case of non-existing \@interface decl. 1089 /// (legacy objective-c \@implementation decl without an \@interface decl). 1090 /// Add implementations's ivar to the synthesize class's ivar list. 1091 if (IDecl->isImplicitInterfaceDecl()) { 1092 IDecl->setEndOfDefinitionLoc(RBrace); 1093 // Add ivar's to class's DeclContext. 1094 for (unsigned i = 0, e = numIvars; i != e; ++i) { 1095 ivars[i]->setLexicalDeclContext(ImpDecl); 1096 IDecl->makeDeclVisibleInContext(ivars[i]); 1097 ImpDecl->addDecl(ivars[i]); 1098 } 1099 1100 return; 1101 } 1102 // If implementation has empty ivar list, just return. 1103 if (numIvars == 0) 1104 return; 1105 1106 assert(ivars && "missing @implementation ivars"); 1107 if (LangOpts.ObjCRuntime.isNonFragile()) { 1108 if (ImpDecl->getSuperClass()) 1109 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use); 1110 for (unsigned i = 0; i < numIvars; i++) { 1111 ObjCIvarDecl* ImplIvar = ivars[i]; 1112 if (const ObjCIvarDecl *ClsIvar = 1113 IDecl->getIvarDecl(ImplIvar->getIdentifier())) { 1114 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration); 1115 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 1116 continue; 1117 } 1118 // Instance ivar to Implementation's DeclContext. 1119 ImplIvar->setLexicalDeclContext(ImpDecl); 1120 IDecl->makeDeclVisibleInContext(ImplIvar); 1121 ImpDecl->addDecl(ImplIvar); 1122 } 1123 return; 1124 } 1125 // Check interface's Ivar list against those in the implementation. 1126 // names and types must match. 1127 // 1128 unsigned j = 0; 1129 ObjCInterfaceDecl::ivar_iterator 1130 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end(); 1131 for (; numIvars > 0 && IVI != IVE; ++IVI) { 1132 ObjCIvarDecl* ImplIvar = ivars[j++]; 1133 ObjCIvarDecl* ClsIvar = *IVI; 1134 assert (ImplIvar && "missing implementation ivar"); 1135 assert (ClsIvar && "missing class ivar"); 1136 1137 // First, make sure the types match. 1138 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) { 1139 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type) 1140 << ImplIvar->getIdentifier() 1141 << ImplIvar->getType() << ClsIvar->getType(); 1142 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 1143 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() && 1144 ImplIvar->getBitWidthValue(Context) != 1145 ClsIvar->getBitWidthValue(Context)) { 1146 Diag(ImplIvar->getBitWidth()->getLocStart(), 1147 diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier(); 1148 Diag(ClsIvar->getBitWidth()->getLocStart(), 1149 diag::note_previous_definition); 1150 } 1151 // Make sure the names are identical. 1152 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) { 1153 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name) 1154 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier(); 1155 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 1156 } 1157 --numIvars; 1158 } 1159 1160 if (numIvars > 0) 1161 Diag(ivars[j]->getLocation(), diag::err_inconsistant_ivar_count); 1162 else if (IVI != IVE) 1163 Diag(IVI->getLocation(), diag::err_inconsistant_ivar_count); 1164 } 1165 1166 void Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method, 1167 bool &IncompleteImpl, unsigned DiagID) { 1168 // No point warning no definition of method which is 'unavailable'. 1169 switch (method->getAvailability()) { 1170 case AR_Available: 1171 case AR_Deprecated: 1172 break; 1173 1174 // Don't warn about unavailable or not-yet-introduced methods. 1175 case AR_NotYetIntroduced: 1176 case AR_Unavailable: 1177 return; 1178 } 1179 1180 if (!IncompleteImpl) { 1181 Diag(ImpLoc, diag::warn_incomplete_impl); 1182 IncompleteImpl = true; 1183 } 1184 if (DiagID == diag::warn_unimplemented_protocol_method) 1185 Diag(ImpLoc, DiagID) << method->getDeclName(); 1186 else 1187 Diag(method->getLocation(), DiagID) << method->getDeclName(); 1188 } 1189 1190 /// Determines if type B can be substituted for type A. Returns true if we can 1191 /// guarantee that anything that the user will do to an object of type A can 1192 /// also be done to an object of type B. This is trivially true if the two 1193 /// types are the same, or if B is a subclass of A. It becomes more complex 1194 /// in cases where protocols are involved. 1195 /// 1196 /// Object types in Objective-C describe the minimum requirements for an 1197 /// object, rather than providing a complete description of a type. For 1198 /// example, if A is a subclass of B, then B* may refer to an instance of A. 1199 /// The principle of substitutability means that we may use an instance of A 1200 /// anywhere that we may use an instance of B - it will implement all of the 1201 /// ivars of B and all of the methods of B. 1202 /// 1203 /// This substitutability is important when type checking methods, because 1204 /// the implementation may have stricter type definitions than the interface. 1205 /// The interface specifies minimum requirements, but the implementation may 1206 /// have more accurate ones. For example, a method may privately accept 1207 /// instances of B, but only publish that it accepts instances of A. Any 1208 /// object passed to it will be type checked against B, and so will implicitly 1209 /// by a valid A*. Similarly, a method may return a subclass of the class that 1210 /// it is declared as returning. 1211 /// 1212 /// This is most important when considering subclassing. A method in a 1213 /// subclass must accept any object as an argument that its superclass's 1214 /// implementation accepts. It may, however, accept a more general type 1215 /// without breaking substitutability (i.e. you can still use the subclass 1216 /// anywhere that you can use the superclass, but not vice versa). The 1217 /// converse requirement applies to return types: the return type for a 1218 /// subclass method must be a valid object of the kind that the superclass 1219 /// advertises, but it may be specified more accurately. This avoids the need 1220 /// for explicit down-casting by callers. 1221 /// 1222 /// Note: This is a stricter requirement than for assignment. 1223 static bool isObjCTypeSubstitutable(ASTContext &Context, 1224 const ObjCObjectPointerType *A, 1225 const ObjCObjectPointerType *B, 1226 bool rejectId) { 1227 // Reject a protocol-unqualified id. 1228 if (rejectId && B->isObjCIdType()) return false; 1229 1230 // If B is a qualified id, then A must also be a qualified id and it must 1231 // implement all of the protocols in B. It may not be a qualified class. 1232 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a 1233 // stricter definition so it is not substitutable for id<A>. 1234 if (B->isObjCQualifiedIdType()) { 1235 return A->isObjCQualifiedIdType() && 1236 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0), 1237 QualType(B,0), 1238 false); 1239 } 1240 1241 /* 1242 // id is a special type that bypasses type checking completely. We want a 1243 // warning when it is used in one place but not another. 1244 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false; 1245 1246 1247 // If B is a qualified id, then A must also be a qualified id (which it isn't 1248 // if we've got this far) 1249 if (B->isObjCQualifiedIdType()) return false; 1250 */ 1251 1252 // Now we know that A and B are (potentially-qualified) class types. The 1253 // normal rules for assignment apply. 1254 return Context.canAssignObjCInterfaces(A, B); 1255 } 1256 1257 static SourceRange getTypeRange(TypeSourceInfo *TSI) { 1258 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange()); 1259 } 1260 1261 static bool CheckMethodOverrideReturn(Sema &S, 1262 ObjCMethodDecl *MethodImpl, 1263 ObjCMethodDecl *MethodDecl, 1264 bool IsProtocolMethodDecl, 1265 bool IsOverridingMode, 1266 bool Warn) { 1267 if (IsProtocolMethodDecl && 1268 (MethodDecl->getObjCDeclQualifier() != 1269 MethodImpl->getObjCDeclQualifier())) { 1270 if (Warn) { 1271 S.Diag(MethodImpl->getLocation(), 1272 (IsOverridingMode ? 1273 diag::warn_conflicting_overriding_ret_type_modifiers 1274 : diag::warn_conflicting_ret_type_modifiers)) 1275 << MethodImpl->getDeclName() 1276 << getTypeRange(MethodImpl->getResultTypeSourceInfo()); 1277 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration) 1278 << getTypeRange(MethodDecl->getResultTypeSourceInfo()); 1279 } 1280 else 1281 return false; 1282 } 1283 1284 if (S.Context.hasSameUnqualifiedType(MethodImpl->getResultType(), 1285 MethodDecl->getResultType())) 1286 return true; 1287 if (!Warn) 1288 return false; 1289 1290 unsigned DiagID = 1291 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types 1292 : diag::warn_conflicting_ret_types; 1293 1294 // Mismatches between ObjC pointers go into a different warning 1295 // category, and sometimes they're even completely whitelisted. 1296 if (const ObjCObjectPointerType *ImplPtrTy = 1297 MethodImpl->getResultType()->getAs<ObjCObjectPointerType>()) { 1298 if (const ObjCObjectPointerType *IfacePtrTy = 1299 MethodDecl->getResultType()->getAs<ObjCObjectPointerType>()) { 1300 // Allow non-matching return types as long as they don't violate 1301 // the principle of substitutability. Specifically, we permit 1302 // return types that are subclasses of the declared return type, 1303 // or that are more-qualified versions of the declared type. 1304 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false)) 1305 return false; 1306 1307 DiagID = 1308 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types 1309 : diag::warn_non_covariant_ret_types; 1310 } 1311 } 1312 1313 S.Diag(MethodImpl->getLocation(), DiagID) 1314 << MethodImpl->getDeclName() 1315 << MethodDecl->getResultType() 1316 << MethodImpl->getResultType() 1317 << getTypeRange(MethodImpl->getResultTypeSourceInfo()); 1318 S.Diag(MethodDecl->getLocation(), 1319 IsOverridingMode ? diag::note_previous_declaration 1320 : diag::note_previous_definition) 1321 << getTypeRange(MethodDecl->getResultTypeSourceInfo()); 1322 return false; 1323 } 1324 1325 static bool CheckMethodOverrideParam(Sema &S, 1326 ObjCMethodDecl *MethodImpl, 1327 ObjCMethodDecl *MethodDecl, 1328 ParmVarDecl *ImplVar, 1329 ParmVarDecl *IfaceVar, 1330 bool IsProtocolMethodDecl, 1331 bool IsOverridingMode, 1332 bool Warn) { 1333 if (IsProtocolMethodDecl && 1334 (ImplVar->getObjCDeclQualifier() != 1335 IfaceVar->getObjCDeclQualifier())) { 1336 if (Warn) { 1337 if (IsOverridingMode) 1338 S.Diag(ImplVar->getLocation(), 1339 diag::warn_conflicting_overriding_param_modifiers) 1340 << getTypeRange(ImplVar->getTypeSourceInfo()) 1341 << MethodImpl->getDeclName(); 1342 else S.Diag(ImplVar->getLocation(), 1343 diag::warn_conflicting_param_modifiers) 1344 << getTypeRange(ImplVar->getTypeSourceInfo()) 1345 << MethodImpl->getDeclName(); 1346 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration) 1347 << getTypeRange(IfaceVar->getTypeSourceInfo()); 1348 } 1349 else 1350 return false; 1351 } 1352 1353 QualType ImplTy = ImplVar->getType(); 1354 QualType IfaceTy = IfaceVar->getType(); 1355 1356 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy)) 1357 return true; 1358 1359 if (!Warn) 1360 return false; 1361 unsigned DiagID = 1362 IsOverridingMode ? diag::warn_conflicting_overriding_param_types 1363 : diag::warn_conflicting_param_types; 1364 1365 // Mismatches between ObjC pointers go into a different warning 1366 // category, and sometimes they're even completely whitelisted. 1367 if (const ObjCObjectPointerType *ImplPtrTy = 1368 ImplTy->getAs<ObjCObjectPointerType>()) { 1369 if (const ObjCObjectPointerType *IfacePtrTy = 1370 IfaceTy->getAs<ObjCObjectPointerType>()) { 1371 // Allow non-matching argument types as long as they don't 1372 // violate the principle of substitutability. Specifically, the 1373 // implementation must accept any objects that the superclass 1374 // accepts, however it may also accept others. 1375 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true)) 1376 return false; 1377 1378 DiagID = 1379 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types 1380 : diag::warn_non_contravariant_param_types; 1381 } 1382 } 1383 1384 S.Diag(ImplVar->getLocation(), DiagID) 1385 << getTypeRange(ImplVar->getTypeSourceInfo()) 1386 << MethodImpl->getDeclName() << IfaceTy << ImplTy; 1387 S.Diag(IfaceVar->getLocation(), 1388 (IsOverridingMode ? diag::note_previous_declaration 1389 : diag::note_previous_definition)) 1390 << getTypeRange(IfaceVar->getTypeSourceInfo()); 1391 return false; 1392 } 1393 1394 /// In ARC, check whether the conventional meanings of the two methods 1395 /// match. If they don't, it's a hard error. 1396 static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl, 1397 ObjCMethodDecl *decl) { 1398 ObjCMethodFamily implFamily = impl->getMethodFamily(); 1399 ObjCMethodFamily declFamily = decl->getMethodFamily(); 1400 if (implFamily == declFamily) return false; 1401 1402 // Since conventions are sorted by selector, the only possibility is 1403 // that the types differ enough to cause one selector or the other 1404 // to fall out of the family. 1405 assert(implFamily == OMF_None || declFamily == OMF_None); 1406 1407 // No further diagnostics required on invalid declarations. 1408 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true; 1409 1410 const ObjCMethodDecl *unmatched = impl; 1411 ObjCMethodFamily family = declFamily; 1412 unsigned errorID = diag::err_arc_lost_method_convention; 1413 unsigned noteID = diag::note_arc_lost_method_convention; 1414 if (declFamily == OMF_None) { 1415 unmatched = decl; 1416 family = implFamily; 1417 errorID = diag::err_arc_gained_method_convention; 1418 noteID = diag::note_arc_gained_method_convention; 1419 } 1420 1421 // Indexes into a %select clause in the diagnostic. 1422 enum FamilySelector { 1423 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new 1424 }; 1425 FamilySelector familySelector = FamilySelector(); 1426 1427 switch (family) { 1428 case OMF_None: llvm_unreachable("logic error, no method convention"); 1429 case OMF_retain: 1430 case OMF_release: 1431 case OMF_autorelease: 1432 case OMF_dealloc: 1433 case OMF_finalize: 1434 case OMF_retainCount: 1435 case OMF_self: 1436 case OMF_performSelector: 1437 // Mismatches for these methods don't change ownership 1438 // conventions, so we don't care. 1439 return false; 1440 1441 case OMF_init: familySelector = F_init; break; 1442 case OMF_alloc: familySelector = F_alloc; break; 1443 case OMF_copy: familySelector = F_copy; break; 1444 case OMF_mutableCopy: familySelector = F_mutableCopy; break; 1445 case OMF_new: familySelector = F_new; break; 1446 } 1447 1448 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn }; 1449 ReasonSelector reasonSelector; 1450 1451 // The only reason these methods don't fall within their families is 1452 // due to unusual result types. 1453 if (unmatched->getResultType()->isObjCObjectPointerType()) { 1454 reasonSelector = R_UnrelatedReturn; 1455 } else { 1456 reasonSelector = R_NonObjectReturn; 1457 } 1458 1459 S.Diag(impl->getLocation(), errorID) << familySelector << reasonSelector; 1460 S.Diag(decl->getLocation(), noteID) << familySelector << reasonSelector; 1461 1462 return true; 1463 } 1464 1465 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl, 1466 ObjCMethodDecl *MethodDecl, 1467 bool IsProtocolMethodDecl) { 1468 if (getLangOpts().ObjCAutoRefCount && 1469 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl)) 1470 return; 1471 1472 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, 1473 IsProtocolMethodDecl, false, 1474 true); 1475 1476 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(), 1477 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(), 1478 EF = MethodDecl->param_end(); 1479 IM != EM && IF != EF; ++IM, ++IF) { 1480 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF, 1481 IsProtocolMethodDecl, false, true); 1482 } 1483 1484 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) { 1485 Diag(ImpMethodDecl->getLocation(), 1486 diag::warn_conflicting_variadic); 1487 Diag(MethodDecl->getLocation(), diag::note_previous_declaration); 1488 } 1489 } 1490 1491 void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method, 1492 ObjCMethodDecl *Overridden, 1493 bool IsProtocolMethodDecl) { 1494 1495 CheckMethodOverrideReturn(*this, Method, Overridden, 1496 IsProtocolMethodDecl, true, 1497 true); 1498 1499 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(), 1500 IF = Overridden->param_begin(), EM = Method->param_end(), 1501 EF = Overridden->param_end(); 1502 IM != EM && IF != EF; ++IM, ++IF) { 1503 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF, 1504 IsProtocolMethodDecl, true, true); 1505 } 1506 1507 if (Method->isVariadic() != Overridden->isVariadic()) { 1508 Diag(Method->getLocation(), 1509 diag::warn_conflicting_overriding_variadic); 1510 Diag(Overridden->getLocation(), diag::note_previous_declaration); 1511 } 1512 } 1513 1514 /// WarnExactTypedMethods - This routine issues a warning if method 1515 /// implementation declaration matches exactly that of its declaration. 1516 void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl, 1517 ObjCMethodDecl *MethodDecl, 1518 bool IsProtocolMethodDecl) { 1519 // don't issue warning when protocol method is optional because primary 1520 // class is not required to implement it and it is safe for protocol 1521 // to implement it. 1522 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional) 1523 return; 1524 // don't issue warning when primary class's method is 1525 // depecated/unavailable. 1526 if (MethodDecl->hasAttr<UnavailableAttr>() || 1527 MethodDecl->hasAttr<DeprecatedAttr>()) 1528 return; 1529 1530 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, 1531 IsProtocolMethodDecl, false, false); 1532 if (match) 1533 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(), 1534 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(), 1535 EF = MethodDecl->param_end(); 1536 IM != EM && IF != EF; ++IM, ++IF) { 1537 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, 1538 *IM, *IF, 1539 IsProtocolMethodDecl, false, false); 1540 if (!match) 1541 break; 1542 } 1543 if (match) 1544 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic()); 1545 if (match) 1546 match = !(MethodDecl->isClassMethod() && 1547 MethodDecl->getSelector() == GetNullarySelector("load", Context)); 1548 1549 if (match) { 1550 Diag(ImpMethodDecl->getLocation(), 1551 diag::warn_category_method_impl_match); 1552 Diag(MethodDecl->getLocation(), diag::note_method_declared_at) 1553 << MethodDecl->getDeclName(); 1554 } 1555 } 1556 1557 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely 1558 /// improve the efficiency of selector lookups and type checking by associating 1559 /// with each protocol / interface / category the flattened instance tables. If 1560 /// we used an immutable set to keep the table then it wouldn't add significant 1561 /// memory cost and it would be handy for lookups. 1562 1563 /// CheckProtocolMethodDefs - This routine checks unimplemented methods 1564 /// Declared in protocol, and those referenced by it. 1565 void Sema::CheckProtocolMethodDefs(SourceLocation ImpLoc, 1566 ObjCProtocolDecl *PDecl, 1567 bool& IncompleteImpl, 1568 const SelectorSet &InsMap, 1569 const SelectorSet &ClsMap, 1570 ObjCContainerDecl *CDecl) { 1571 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl); 1572 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface() 1573 : dyn_cast<ObjCInterfaceDecl>(CDecl); 1574 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null"); 1575 1576 ObjCInterfaceDecl *Super = IDecl->getSuperClass(); 1577 ObjCInterfaceDecl *NSIDecl = 0; 1578 if (getLangOpts().ObjCRuntime.isNeXTFamily()) { 1579 // check to see if class implements forwardInvocation method and objects 1580 // of this class are derived from 'NSProxy' so that to forward requests 1581 // from one object to another. 1582 // Under such conditions, which means that every method possible is 1583 // implemented in the class, we should not issue "Method definition not 1584 // found" warnings. 1585 // FIXME: Use a general GetUnarySelector method for this. 1586 IdentifierInfo* II = &Context.Idents.get("forwardInvocation"); 1587 Selector fISelector = Context.Selectors.getSelector(1, &II); 1588 if (InsMap.count(fISelector)) 1589 // Is IDecl derived from 'NSProxy'? If so, no instance methods 1590 // need be implemented in the implementation. 1591 NSIDecl = IDecl->lookupInheritedClass(&Context.Idents.get("NSProxy")); 1592 } 1593 1594 // If this is a forward protocol declaration, get its definition. 1595 if (!PDecl->isThisDeclarationADefinition() && 1596 PDecl->getDefinition()) 1597 PDecl = PDecl->getDefinition(); 1598 1599 // If a method lookup fails locally we still need to look and see if 1600 // the method was implemented by a base class or an inherited 1601 // protocol. This lookup is slow, but occurs rarely in correct code 1602 // and otherwise would terminate in a warning. 1603 1604 // check unimplemented instance methods. 1605 if (!NSIDecl) 1606 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(), 1607 E = PDecl->instmeth_end(); I != E; ++I) { 1608 ObjCMethodDecl *method = *I; 1609 if (method->getImplementationControl() != ObjCMethodDecl::Optional && 1610 !method->isPropertyAccessor() && 1611 !InsMap.count(method->getSelector()) && 1612 (!Super || !Super->lookupInstanceMethod(method->getSelector()))) { 1613 // If a method is not implemented in the category implementation but 1614 // has been declared in its primary class, superclass, 1615 // or in one of their protocols, no need to issue the warning. 1616 // This is because method will be implemented in the primary class 1617 // or one of its super class implementation. 1618 1619 // Ugly, but necessary. Method declared in protcol might have 1620 // have been synthesized due to a property declared in the class which 1621 // uses the protocol. 1622 if (ObjCMethodDecl *MethodInClass = 1623 IDecl->lookupInstanceMethod(method->getSelector(), 1624 true /*shallowCategoryLookup*/)) 1625 if (C || MethodInClass->isPropertyAccessor()) 1626 continue; 1627 unsigned DIAG = diag::warn_unimplemented_protocol_method; 1628 if (Diags.getDiagnosticLevel(DIAG, ImpLoc) 1629 != DiagnosticsEngine::Ignored) { 1630 WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG); 1631 Diag(method->getLocation(), diag::note_method_declared_at) 1632 << method->getDeclName(); 1633 Diag(CDecl->getLocation(), diag::note_required_for_protocol_at) 1634 << PDecl->getDeclName(); 1635 } 1636 } 1637 } 1638 // check unimplemented class methods 1639 for (ObjCProtocolDecl::classmeth_iterator 1640 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end(); 1641 I != E; ++I) { 1642 ObjCMethodDecl *method = *I; 1643 if (method->getImplementationControl() != ObjCMethodDecl::Optional && 1644 !ClsMap.count(method->getSelector()) && 1645 (!Super || !Super->lookupClassMethod(method->getSelector()))) { 1646 // See above comment for instance method lookups. 1647 if (C && IDecl->lookupClassMethod(method->getSelector(), 1648 true /*shallowCategoryLookup*/)) 1649 continue; 1650 unsigned DIAG = diag::warn_unimplemented_protocol_method; 1651 if (Diags.getDiagnosticLevel(DIAG, ImpLoc) != 1652 DiagnosticsEngine::Ignored) { 1653 WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG); 1654 Diag(method->getLocation(), diag::note_method_declared_at) 1655 << method->getDeclName(); 1656 Diag(IDecl->getLocation(), diag::note_required_for_protocol_at) << 1657 PDecl->getDeclName(); 1658 } 1659 } 1660 } 1661 // Check on this protocols's referenced protocols, recursively. 1662 for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(), 1663 E = PDecl->protocol_end(); PI != E; ++PI) 1664 CheckProtocolMethodDefs(ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap, CDecl); 1665 } 1666 1667 /// MatchAllMethodDeclarations - Check methods declared in interface 1668 /// or protocol against those declared in their implementations. 1669 /// 1670 void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap, 1671 const SelectorSet &ClsMap, 1672 SelectorSet &InsMapSeen, 1673 SelectorSet &ClsMapSeen, 1674 ObjCImplDecl* IMPDecl, 1675 ObjCContainerDecl* CDecl, 1676 bool &IncompleteImpl, 1677 bool ImmediateClass, 1678 bool WarnCategoryMethodImpl) { 1679 // Check and see if instance methods in class interface have been 1680 // implemented in the implementation class. If so, their types match. 1681 for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(), 1682 E = CDecl->instmeth_end(); I != E; ++I) { 1683 if (InsMapSeen.count((*I)->getSelector())) 1684 continue; 1685 InsMapSeen.insert((*I)->getSelector()); 1686 if (!(*I)->isPropertyAccessor() && 1687 !InsMap.count((*I)->getSelector())) { 1688 if (ImmediateClass) 1689 WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl, 1690 diag::note_undef_method_impl); 1691 continue; 1692 } else { 1693 ObjCMethodDecl *ImpMethodDecl = 1694 IMPDecl->getInstanceMethod((*I)->getSelector()); 1695 assert(CDecl->getInstanceMethod((*I)->getSelector()) && 1696 "Expected to find the method through lookup as well"); 1697 ObjCMethodDecl *MethodDecl = *I; 1698 // ImpMethodDecl may be null as in a @dynamic property. 1699 if (ImpMethodDecl) { 1700 if (!WarnCategoryMethodImpl) 1701 WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl, 1702 isa<ObjCProtocolDecl>(CDecl)); 1703 else if (!MethodDecl->isPropertyAccessor()) 1704 WarnExactTypedMethods(ImpMethodDecl, MethodDecl, 1705 isa<ObjCProtocolDecl>(CDecl)); 1706 } 1707 } 1708 } 1709 1710 // Check and see if class methods in class interface have been 1711 // implemented in the implementation class. If so, their types match. 1712 for (ObjCInterfaceDecl::classmeth_iterator 1713 I = CDecl->classmeth_begin(), E = CDecl->classmeth_end(); I != E; ++I) { 1714 if (ClsMapSeen.count((*I)->getSelector())) 1715 continue; 1716 ClsMapSeen.insert((*I)->getSelector()); 1717 if (!ClsMap.count((*I)->getSelector())) { 1718 if (ImmediateClass) 1719 WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl, 1720 diag::note_undef_method_impl); 1721 } else { 1722 ObjCMethodDecl *ImpMethodDecl = 1723 IMPDecl->getClassMethod((*I)->getSelector()); 1724 assert(CDecl->getClassMethod((*I)->getSelector()) && 1725 "Expected to find the method through lookup as well"); 1726 ObjCMethodDecl *MethodDecl = *I; 1727 if (!WarnCategoryMethodImpl) 1728 WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl, 1729 isa<ObjCProtocolDecl>(CDecl)); 1730 else 1731 WarnExactTypedMethods(ImpMethodDecl, MethodDecl, 1732 isa<ObjCProtocolDecl>(CDecl)); 1733 } 1734 } 1735 1736 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) { 1737 // when checking that methods in implementation match their declaration, 1738 // i.e. when WarnCategoryMethodImpl is false, check declarations in class 1739 // extension; as well as those in categories. 1740 if (!WarnCategoryMethodImpl) { 1741 for (ObjCInterfaceDecl::visible_categories_iterator 1742 Cat = I->visible_categories_begin(), 1743 CatEnd = I->visible_categories_end(); 1744 Cat != CatEnd; ++Cat) { 1745 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1746 IMPDecl, *Cat, IncompleteImpl, false, 1747 WarnCategoryMethodImpl); 1748 } 1749 } else { 1750 // Also methods in class extensions need be looked at next. 1751 for (ObjCInterfaceDecl::visible_extensions_iterator 1752 Ext = I->visible_extensions_begin(), 1753 ExtEnd = I->visible_extensions_end(); 1754 Ext != ExtEnd; ++Ext) { 1755 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1756 IMPDecl, *Ext, IncompleteImpl, false, 1757 WarnCategoryMethodImpl); 1758 } 1759 } 1760 1761 // Check for any implementation of a methods declared in protocol. 1762 for (ObjCInterfaceDecl::all_protocol_iterator 1763 PI = I->all_referenced_protocol_begin(), 1764 E = I->all_referenced_protocol_end(); PI != E; ++PI) 1765 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1766 IMPDecl, 1767 (*PI), IncompleteImpl, false, 1768 WarnCategoryMethodImpl); 1769 1770 // FIXME. For now, we are not checking for extact match of methods 1771 // in category implementation and its primary class's super class. 1772 if (!WarnCategoryMethodImpl && I->getSuperClass()) 1773 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1774 IMPDecl, 1775 I->getSuperClass(), IncompleteImpl, false); 1776 } 1777 } 1778 1779 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in 1780 /// category matches with those implemented in its primary class and 1781 /// warns each time an exact match is found. 1782 void Sema::CheckCategoryVsClassMethodMatches( 1783 ObjCCategoryImplDecl *CatIMPDecl) { 1784 SelectorSet InsMap, ClsMap; 1785 1786 for (ObjCImplementationDecl::instmeth_iterator 1787 I = CatIMPDecl->instmeth_begin(), 1788 E = CatIMPDecl->instmeth_end(); I!=E; ++I) 1789 InsMap.insert((*I)->getSelector()); 1790 1791 for (ObjCImplementationDecl::classmeth_iterator 1792 I = CatIMPDecl->classmeth_begin(), 1793 E = CatIMPDecl->classmeth_end(); I != E; ++I) 1794 ClsMap.insert((*I)->getSelector()); 1795 if (InsMap.empty() && ClsMap.empty()) 1796 return; 1797 1798 // Get category's primary class. 1799 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl(); 1800 if (!CatDecl) 1801 return; 1802 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface(); 1803 if (!IDecl) 1804 return; 1805 SelectorSet InsMapSeen, ClsMapSeen; 1806 bool IncompleteImpl = false; 1807 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1808 CatIMPDecl, IDecl, 1809 IncompleteImpl, false, 1810 true /*WarnCategoryMethodImpl*/); 1811 } 1812 1813 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, 1814 ObjCContainerDecl* CDecl, 1815 bool IncompleteImpl) { 1816 SelectorSet InsMap; 1817 // Check and see if instance methods in class interface have been 1818 // implemented in the implementation class. 1819 for (ObjCImplementationDecl::instmeth_iterator 1820 I = IMPDecl->instmeth_begin(), E = IMPDecl->instmeth_end(); I!=E; ++I) 1821 InsMap.insert((*I)->getSelector()); 1822 1823 // Check and see if properties declared in the interface have either 1) 1824 // an implementation or 2) there is a @synthesize/@dynamic implementation 1825 // of the property in the @implementation. 1826 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) 1827 if (!(LangOpts.ObjCDefaultSynthProperties && 1828 LangOpts.ObjCRuntime.isNonFragile()) || 1829 IDecl->isObjCRequiresPropertyDefs()) 1830 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap); 1831 1832 SelectorSet ClsMap; 1833 for (ObjCImplementationDecl::classmeth_iterator 1834 I = IMPDecl->classmeth_begin(), 1835 E = IMPDecl->classmeth_end(); I != E; ++I) 1836 ClsMap.insert((*I)->getSelector()); 1837 1838 // Check for type conflict of methods declared in a class/protocol and 1839 // its implementation; if any. 1840 SelectorSet InsMapSeen, ClsMapSeen; 1841 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1842 IMPDecl, CDecl, 1843 IncompleteImpl, true); 1844 1845 // check all methods implemented in category against those declared 1846 // in its primary class. 1847 if (ObjCCategoryImplDecl *CatDecl = 1848 dyn_cast<ObjCCategoryImplDecl>(IMPDecl)) 1849 CheckCategoryVsClassMethodMatches(CatDecl); 1850 1851 // Check the protocol list for unimplemented methods in the @implementation 1852 // class. 1853 // Check and see if class methods in class interface have been 1854 // implemented in the implementation class. 1855 1856 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) { 1857 for (ObjCInterfaceDecl::all_protocol_iterator 1858 PI = I->all_referenced_protocol_begin(), 1859 E = I->all_referenced_protocol_end(); PI != E; ++PI) 1860 CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl, 1861 InsMap, ClsMap, I); 1862 // Check class extensions (unnamed categories) 1863 for (ObjCInterfaceDecl::visible_extensions_iterator 1864 Ext = I->visible_extensions_begin(), 1865 ExtEnd = I->visible_extensions_end(); 1866 Ext != ExtEnd; ++Ext) { 1867 ImplMethodsVsClassMethods(S, IMPDecl, *Ext, IncompleteImpl); 1868 } 1869 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) { 1870 // For extended class, unimplemented methods in its protocols will 1871 // be reported in the primary class. 1872 if (!C->IsClassExtension()) { 1873 for (ObjCCategoryDecl::protocol_iterator PI = C->protocol_begin(), 1874 E = C->protocol_end(); PI != E; ++PI) 1875 CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl, 1876 InsMap, ClsMap, CDecl); 1877 // Report unimplemented properties in the category as well. 1878 // When reporting on missing setter/getters, do not report when 1879 // setter/getter is implemented in category's primary class 1880 // implementation. 1881 if (ObjCInterfaceDecl *ID = C->getClassInterface()) 1882 if (ObjCImplDecl *IMP = ID->getImplementation()) { 1883 for (ObjCImplementationDecl::instmeth_iterator 1884 I = IMP->instmeth_begin(), E = IMP->instmeth_end(); I!=E; ++I) 1885 InsMap.insert((*I)->getSelector()); 1886 } 1887 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap); 1888 } 1889 } else 1890 llvm_unreachable("invalid ObjCContainerDecl type."); 1891 } 1892 1893 /// ActOnForwardClassDeclaration - 1894 Sema::DeclGroupPtrTy 1895 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc, 1896 IdentifierInfo **IdentList, 1897 SourceLocation *IdentLocs, 1898 unsigned NumElts) { 1899 SmallVector<Decl *, 8> DeclsInGroup; 1900 for (unsigned i = 0; i != NumElts; ++i) { 1901 // Check for another declaration kind with the same name. 1902 NamedDecl *PrevDecl 1903 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i], 1904 LookupOrdinaryName, ForRedeclaration); 1905 if (PrevDecl && PrevDecl->isTemplateParameter()) { 1906 // Maybe we will complain about the shadowed template parameter. 1907 DiagnoseTemplateParameterShadow(AtClassLoc, PrevDecl); 1908 // Just pretend that we didn't see the previous declaration. 1909 PrevDecl = 0; 1910 } 1911 1912 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 1913 // GCC apparently allows the following idiom: 1914 // 1915 // typedef NSObject < XCElementTogglerP > XCElementToggler; 1916 // @class XCElementToggler; 1917 // 1918 // Here we have chosen to ignore the forward class declaration 1919 // with a warning. Since this is the implied behavior. 1920 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl); 1921 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) { 1922 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i]; 1923 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 1924 } else { 1925 // a forward class declaration matching a typedef name of a class refers 1926 // to the underlying class. Just ignore the forward class with a warning 1927 // as this will force the intended behavior which is to lookup the typedef 1928 // name. 1929 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) { 1930 Diag(AtClassLoc, diag::warn_forward_class_redefinition) << IdentList[i]; 1931 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 1932 continue; 1933 } 1934 } 1935 } 1936 1937 // Create a declaration to describe this forward declaration. 1938 ObjCInterfaceDecl *PrevIDecl 1939 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 1940 ObjCInterfaceDecl *IDecl 1941 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc, 1942 IdentList[i], PrevIDecl, IdentLocs[i]); 1943 IDecl->setAtEndRange(IdentLocs[i]); 1944 1945 PushOnScopeChains(IDecl, TUScope); 1946 CheckObjCDeclScope(IDecl); 1947 DeclsInGroup.push_back(IDecl); 1948 } 1949 1950 return BuildDeclaratorGroup(DeclsInGroup.data(), DeclsInGroup.size(), false); 1951 } 1952 1953 static bool tryMatchRecordTypes(ASTContext &Context, 1954 Sema::MethodMatchStrategy strategy, 1955 const Type *left, const Type *right); 1956 1957 static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy, 1958 QualType leftQT, QualType rightQT) { 1959 const Type *left = 1960 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr(); 1961 const Type *right = 1962 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr(); 1963 1964 if (left == right) return true; 1965 1966 // If we're doing a strict match, the types have to match exactly. 1967 if (strategy == Sema::MMS_strict) return false; 1968 1969 if (left->isIncompleteType() || right->isIncompleteType()) return false; 1970 1971 // Otherwise, use this absurdly complicated algorithm to try to 1972 // validate the basic, low-level compatibility of the two types. 1973 1974 // As a minimum, require the sizes and alignments to match. 1975 if (Context.getTypeInfo(left) != Context.getTypeInfo(right)) 1976 return false; 1977 1978 // Consider all the kinds of non-dependent canonical types: 1979 // - functions and arrays aren't possible as return and parameter types 1980 1981 // - vector types of equal size can be arbitrarily mixed 1982 if (isa<VectorType>(left)) return isa<VectorType>(right); 1983 if (isa<VectorType>(right)) return false; 1984 1985 // - references should only match references of identical type 1986 // - structs, unions, and Objective-C objects must match more-or-less 1987 // exactly 1988 // - everything else should be a scalar 1989 if (!left->isScalarType() || !right->isScalarType()) 1990 return tryMatchRecordTypes(Context, strategy, left, right); 1991 1992 // Make scalars agree in kind, except count bools as chars, and group 1993 // all non-member pointers together. 1994 Type::ScalarTypeKind leftSK = left->getScalarTypeKind(); 1995 Type::ScalarTypeKind rightSK = right->getScalarTypeKind(); 1996 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral; 1997 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral; 1998 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer) 1999 leftSK = Type::STK_ObjCObjectPointer; 2000 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer) 2001 rightSK = Type::STK_ObjCObjectPointer; 2002 2003 // Note that data member pointers and function member pointers don't 2004 // intermix because of the size differences. 2005 2006 return (leftSK == rightSK); 2007 } 2008 2009 static bool tryMatchRecordTypes(ASTContext &Context, 2010 Sema::MethodMatchStrategy strategy, 2011 const Type *lt, const Type *rt) { 2012 assert(lt && rt && lt != rt); 2013 2014 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false; 2015 RecordDecl *left = cast<RecordType>(lt)->getDecl(); 2016 RecordDecl *right = cast<RecordType>(rt)->getDecl(); 2017 2018 // Require union-hood to match. 2019 if (left->isUnion() != right->isUnion()) return false; 2020 2021 // Require an exact match if either is non-POD. 2022 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) || 2023 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD())) 2024 return false; 2025 2026 // Require size and alignment to match. 2027 if (Context.getTypeInfo(lt) != Context.getTypeInfo(rt)) return false; 2028 2029 // Require fields to match. 2030 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end(); 2031 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end(); 2032 for (; li != le && ri != re; ++li, ++ri) { 2033 if (!matchTypes(Context, strategy, li->getType(), ri->getType())) 2034 return false; 2035 } 2036 return (li == le && ri == re); 2037 } 2038 2039 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and 2040 /// returns true, or false, accordingly. 2041 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons 2042 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left, 2043 const ObjCMethodDecl *right, 2044 MethodMatchStrategy strategy) { 2045 if (!matchTypes(Context, strategy, 2046 left->getResultType(), right->getResultType())) 2047 return false; 2048 2049 // If either is hidden, it is not considered to match. 2050 if (left->isHidden() || right->isHidden()) 2051 return false; 2052 2053 if (getLangOpts().ObjCAutoRefCount && 2054 (left->hasAttr<NSReturnsRetainedAttr>() 2055 != right->hasAttr<NSReturnsRetainedAttr>() || 2056 left->hasAttr<NSConsumesSelfAttr>() 2057 != right->hasAttr<NSConsumesSelfAttr>())) 2058 return false; 2059 2060 ObjCMethodDecl::param_const_iterator 2061 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(), 2062 re = right->param_end(); 2063 2064 for (; li != le && ri != re; ++li, ++ri) { 2065 assert(ri != right->param_end() && "Param mismatch"); 2066 const ParmVarDecl *lparm = *li, *rparm = *ri; 2067 2068 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType())) 2069 return false; 2070 2071 if (getLangOpts().ObjCAutoRefCount && 2072 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>()) 2073 return false; 2074 } 2075 return true; 2076 } 2077 2078 void Sema::addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method) { 2079 // If the list is empty, make it a singleton list. 2080 if (List->Method == 0) { 2081 List->Method = Method; 2082 List->Next = 0; 2083 return; 2084 } 2085 2086 // We've seen a method with this name, see if we have already seen this type 2087 // signature. 2088 ObjCMethodList *Previous = List; 2089 for (; List; Previous = List, List = List->Next) { 2090 if (!MatchTwoMethodDeclarations(Method, List->Method)) 2091 continue; 2092 2093 ObjCMethodDecl *PrevObjCMethod = List->Method; 2094 2095 // Propagate the 'defined' bit. 2096 if (Method->isDefined()) 2097 PrevObjCMethod->setDefined(true); 2098 2099 // If a method is deprecated, push it in the global pool. 2100 // This is used for better diagnostics. 2101 if (Method->isDeprecated()) { 2102 if (!PrevObjCMethod->isDeprecated()) 2103 List->Method = Method; 2104 } 2105 // If new method is unavailable, push it into global pool 2106 // unless previous one is deprecated. 2107 if (Method->isUnavailable()) { 2108 if (PrevObjCMethod->getAvailability() < AR_Deprecated) 2109 List->Method = Method; 2110 } 2111 2112 return; 2113 } 2114 2115 // We have a new signature for an existing method - add it. 2116 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded". 2117 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>(); 2118 Previous->Next = new (Mem) ObjCMethodList(Method, 0); 2119 } 2120 2121 /// \brief Read the contents of the method pool for a given selector from 2122 /// external storage. 2123 void Sema::ReadMethodPool(Selector Sel) { 2124 assert(ExternalSource && "We need an external AST source"); 2125 ExternalSource->ReadMethodPool(Sel); 2126 } 2127 2128 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, 2129 bool instance) { 2130 // Ignore methods of invalid containers. 2131 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl()) 2132 return; 2133 2134 if (ExternalSource) 2135 ReadMethodPool(Method->getSelector()); 2136 2137 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector()); 2138 if (Pos == MethodPool.end()) 2139 Pos = MethodPool.insert(std::make_pair(Method->getSelector(), 2140 GlobalMethods())).first; 2141 2142 Method->setDefined(impl); 2143 2144 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second; 2145 addMethodToGlobalList(&Entry, Method); 2146 } 2147 2148 /// Determines if this is an "acceptable" loose mismatch in the global 2149 /// method pool. This exists mostly as a hack to get around certain 2150 /// global mismatches which we can't afford to make warnings / errors. 2151 /// Really, what we want is a way to take a method out of the global 2152 /// method pool. 2153 static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen, 2154 ObjCMethodDecl *other) { 2155 if (!chosen->isInstanceMethod()) 2156 return false; 2157 2158 Selector sel = chosen->getSelector(); 2159 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length") 2160 return false; 2161 2162 // Don't complain about mismatches for -length if the method we 2163 // chose has an integral result type. 2164 return (chosen->getResultType()->isIntegerType()); 2165 } 2166 2167 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R, 2168 bool receiverIdOrClass, 2169 bool warn, bool instance) { 2170 if (ExternalSource) 2171 ReadMethodPool(Sel); 2172 2173 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 2174 if (Pos == MethodPool.end()) 2175 return 0; 2176 2177 // Gather the non-hidden methods. 2178 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second; 2179 llvm::SmallVector<ObjCMethodDecl *, 4> Methods; 2180 for (ObjCMethodList *M = &MethList; M; M = M->Next) { 2181 if (M->Method && !M->Method->isHidden()) { 2182 // If we're not supposed to warn about mismatches, we're done. 2183 if (!warn) 2184 return M->Method; 2185 2186 Methods.push_back(M->Method); 2187 } 2188 } 2189 2190 // If there aren't any visible methods, we're done. 2191 // FIXME: Recover if there are any known-but-hidden methods? 2192 if (Methods.empty()) 2193 return 0; 2194 2195 if (Methods.size() == 1) 2196 return Methods[0]; 2197 2198 // We found multiple methods, so we may have to complain. 2199 bool issueDiagnostic = false, issueError = false; 2200 2201 // We support a warning which complains about *any* difference in 2202 // method signature. 2203 bool strictSelectorMatch = 2204 (receiverIdOrClass && warn && 2205 (Diags.getDiagnosticLevel(diag::warn_strict_multiple_method_decl, 2206 R.getBegin()) 2207 != DiagnosticsEngine::Ignored)); 2208 if (strictSelectorMatch) { 2209 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 2210 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) { 2211 issueDiagnostic = true; 2212 break; 2213 } 2214 } 2215 } 2216 2217 // If we didn't see any strict differences, we won't see any loose 2218 // differences. In ARC, however, we also need to check for loose 2219 // mismatches, because most of them are errors. 2220 if (!strictSelectorMatch || 2221 (issueDiagnostic && getLangOpts().ObjCAutoRefCount)) 2222 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 2223 // This checks if the methods differ in type mismatch. 2224 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) && 2225 !isAcceptableMethodMismatch(Methods[0], Methods[I])) { 2226 issueDiagnostic = true; 2227 if (getLangOpts().ObjCAutoRefCount) 2228 issueError = true; 2229 break; 2230 } 2231 } 2232 2233 if (issueDiagnostic) { 2234 if (issueError) 2235 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R; 2236 else if (strictSelectorMatch) 2237 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R; 2238 else 2239 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R; 2240 2241 Diag(Methods[0]->getLocStart(), 2242 issueError ? diag::note_possibility : diag::note_using) 2243 << Methods[0]->getSourceRange(); 2244 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 2245 Diag(Methods[I]->getLocStart(), diag::note_also_found) 2246 << Methods[I]->getSourceRange(); 2247 } 2248 } 2249 return Methods[0]; 2250 } 2251 2252 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) { 2253 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 2254 if (Pos == MethodPool.end()) 2255 return 0; 2256 2257 GlobalMethods &Methods = Pos->second; 2258 2259 if (Methods.first.Method && Methods.first.Method->isDefined()) 2260 return Methods.first.Method; 2261 if (Methods.second.Method && Methods.second.Method->isDefined()) 2262 return Methods.second.Method; 2263 return 0; 2264 } 2265 2266 /// DiagnoseDuplicateIvars - 2267 /// Check for duplicate ivars in the entire class at the start of 2268 /// \@implementation. This becomes necesssary because class extension can 2269 /// add ivars to a class in random order which will not be known until 2270 /// class's \@implementation is seen. 2271 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, 2272 ObjCInterfaceDecl *SID) { 2273 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(), 2274 IVE = ID->ivar_end(); IVI != IVE; ++IVI) { 2275 ObjCIvarDecl* Ivar = *IVI; 2276 if (Ivar->isInvalidDecl()) 2277 continue; 2278 if (IdentifierInfo *II = Ivar->getIdentifier()) { 2279 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II); 2280 if (prevIvar) { 2281 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II; 2282 Diag(prevIvar->getLocation(), diag::note_previous_declaration); 2283 Ivar->setInvalidDecl(); 2284 } 2285 } 2286 } 2287 } 2288 2289 Sema::ObjCContainerKind Sema::getObjCContainerKind() const { 2290 switch (CurContext->getDeclKind()) { 2291 case Decl::ObjCInterface: 2292 return Sema::OCK_Interface; 2293 case Decl::ObjCProtocol: 2294 return Sema::OCK_Protocol; 2295 case Decl::ObjCCategory: 2296 if (dyn_cast<ObjCCategoryDecl>(CurContext)->IsClassExtension()) 2297 return Sema::OCK_ClassExtension; 2298 else 2299 return Sema::OCK_Category; 2300 case Decl::ObjCImplementation: 2301 return Sema::OCK_Implementation; 2302 case Decl::ObjCCategoryImpl: 2303 return Sema::OCK_CategoryImplementation; 2304 2305 default: 2306 return Sema::OCK_None; 2307 } 2308 } 2309 2310 // Note: For class/category implemenations, allMethods/allProperties is 2311 // always null. 2312 Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, 2313 Decl **allMethods, unsigned allNum, 2314 Decl **allProperties, unsigned pNum, 2315 DeclGroupPtrTy *allTUVars, unsigned tuvNum) { 2316 2317 if (getObjCContainerKind() == Sema::OCK_None) 2318 return 0; 2319 2320 assert(AtEnd.isValid() && "Invalid location for '@end'"); 2321 2322 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext); 2323 Decl *ClassDecl = cast<Decl>(OCD); 2324 2325 bool isInterfaceDeclKind = 2326 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl) 2327 || isa<ObjCProtocolDecl>(ClassDecl); 2328 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl); 2329 2330 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext. 2331 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap; 2332 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap; 2333 2334 for (unsigned i = 0; i < allNum; i++ ) { 2335 ObjCMethodDecl *Method = 2336 cast_or_null<ObjCMethodDecl>(allMethods[i]); 2337 2338 if (!Method) continue; // Already issued a diagnostic. 2339 if (Method->isInstanceMethod()) { 2340 /// Check for instance method of the same name with incompatible types 2341 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()]; 2342 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod) 2343 : false; 2344 if ((isInterfaceDeclKind && PrevMethod && !match) 2345 || (checkIdenticalMethods && match)) { 2346 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 2347 << Method->getDeclName(); 2348 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 2349 Method->setInvalidDecl(); 2350 } else { 2351 if (PrevMethod) { 2352 Method->setAsRedeclaration(PrevMethod); 2353 if (!Context.getSourceManager().isInSystemHeader( 2354 Method->getLocation())) 2355 Diag(Method->getLocation(), diag::warn_duplicate_method_decl) 2356 << Method->getDeclName(); 2357 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 2358 } 2359 InsMap[Method->getSelector()] = Method; 2360 /// The following allows us to typecheck messages to "id". 2361 AddInstanceMethodToGlobalPool(Method); 2362 } 2363 } else { 2364 /// Check for class method of the same name with incompatible types 2365 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()]; 2366 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod) 2367 : false; 2368 if ((isInterfaceDeclKind && PrevMethod && !match) 2369 || (checkIdenticalMethods && match)) { 2370 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 2371 << Method->getDeclName(); 2372 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 2373 Method->setInvalidDecl(); 2374 } else { 2375 if (PrevMethod) { 2376 Method->setAsRedeclaration(PrevMethod); 2377 if (!Context.getSourceManager().isInSystemHeader( 2378 Method->getLocation())) 2379 Diag(Method->getLocation(), diag::warn_duplicate_method_decl) 2380 << Method->getDeclName(); 2381 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 2382 } 2383 ClsMap[Method->getSelector()] = Method; 2384 AddFactoryMethodToGlobalPool(Method); 2385 } 2386 } 2387 } 2388 if (isa<ObjCInterfaceDecl>(ClassDecl)) { 2389 // Nothing to do here. 2390 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) { 2391 // Categories are used to extend the class by declaring new methods. 2392 // By the same token, they are also used to add new properties. No 2393 // need to compare the added property to those in the class. 2394 2395 if (C->IsClassExtension()) { 2396 ObjCInterfaceDecl *CCPrimary = C->getClassInterface(); 2397 DiagnoseClassExtensionDupMethods(C, CCPrimary); 2398 } 2399 } 2400 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) { 2401 if (CDecl->getIdentifier()) 2402 // ProcessPropertyDecl is responsible for diagnosing conflicts with any 2403 // user-defined setter/getter. It also synthesizes setter/getter methods 2404 // and adds them to the DeclContext and global method pools. 2405 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(), 2406 E = CDecl->prop_end(); 2407 I != E; ++I) 2408 ProcessPropertyDecl(*I, CDecl); 2409 CDecl->setAtEndRange(AtEnd); 2410 } 2411 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) { 2412 IC->setAtEndRange(AtEnd); 2413 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) { 2414 // Any property declared in a class extension might have user 2415 // declared setter or getter in current class extension or one 2416 // of the other class extensions. Mark them as synthesized as 2417 // property will be synthesized when property with same name is 2418 // seen in the @implementation. 2419 for (ObjCInterfaceDecl::visible_extensions_iterator 2420 Ext = IDecl->visible_extensions_begin(), 2421 ExtEnd = IDecl->visible_extensions_end(); 2422 Ext != ExtEnd; ++Ext) { 2423 for (ObjCContainerDecl::prop_iterator I = Ext->prop_begin(), 2424 E = Ext->prop_end(); I != E; ++I) { 2425 ObjCPropertyDecl *Property = *I; 2426 // Skip over properties declared @dynamic 2427 if (const ObjCPropertyImplDecl *PIDecl 2428 = IC->FindPropertyImplDecl(Property->getIdentifier())) 2429 if (PIDecl->getPropertyImplementation() 2430 == ObjCPropertyImplDecl::Dynamic) 2431 continue; 2432 2433 for (ObjCInterfaceDecl::visible_extensions_iterator 2434 Ext = IDecl->visible_extensions_begin(), 2435 ExtEnd = IDecl->visible_extensions_end(); 2436 Ext != ExtEnd; ++Ext) { 2437 if (ObjCMethodDecl *GetterMethod 2438 = Ext->getInstanceMethod(Property->getGetterName())) 2439 GetterMethod->setPropertyAccessor(true); 2440 if (!Property->isReadOnly()) 2441 if (ObjCMethodDecl *SetterMethod 2442 = Ext->getInstanceMethod(Property->getSetterName())) 2443 SetterMethod->setPropertyAccessor(true); 2444 } 2445 } 2446 } 2447 ImplMethodsVsClassMethods(S, IC, IDecl); 2448 AtomicPropertySetterGetterRules(IC, IDecl); 2449 DiagnoseOwningPropertyGetterSynthesis(IC); 2450 2451 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>(); 2452 if (IDecl->getSuperClass() == NULL) { 2453 // This class has no superclass, so check that it has been marked with 2454 // __attribute((objc_root_class)). 2455 if (!HasRootClassAttr) { 2456 SourceLocation DeclLoc(IDecl->getLocation()); 2457 SourceLocation SuperClassLoc(PP.getLocForEndOfToken(DeclLoc)); 2458 Diag(DeclLoc, diag::warn_objc_root_class_missing) 2459 << IDecl->getIdentifier(); 2460 // See if NSObject is in the current scope, and if it is, suggest 2461 // adding " : NSObject " to the class declaration. 2462 NamedDecl *IF = LookupSingleName(TUScope, 2463 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject), 2464 DeclLoc, LookupOrdinaryName); 2465 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); 2466 if (NSObjectDecl && NSObjectDecl->getDefinition()) { 2467 Diag(SuperClassLoc, diag::note_objc_needs_superclass) 2468 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject "); 2469 } else { 2470 Diag(SuperClassLoc, diag::note_objc_needs_superclass); 2471 } 2472 } 2473 } else if (HasRootClassAttr) { 2474 // Complain that only root classes may have this attribute. 2475 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass); 2476 } 2477 2478 if (LangOpts.ObjCRuntime.isNonFragile()) { 2479 while (IDecl->getSuperClass()) { 2480 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass()); 2481 IDecl = IDecl->getSuperClass(); 2482 } 2483 } 2484 } 2485 SetIvarInitializers(IC); 2486 } else if (ObjCCategoryImplDecl* CatImplClass = 2487 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) { 2488 CatImplClass->setAtEndRange(AtEnd); 2489 2490 // Find category interface decl and then check that all methods declared 2491 // in this interface are implemented in the category @implementation. 2492 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) { 2493 if (ObjCCategoryDecl *Cat 2494 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) { 2495 ImplMethodsVsClassMethods(S, CatImplClass, Cat); 2496 } 2497 } 2498 } 2499 if (isInterfaceDeclKind) { 2500 // Reject invalid vardecls. 2501 for (unsigned i = 0; i != tuvNum; i++) { 2502 DeclGroupRef DG = allTUVars[i].getAsVal<DeclGroupRef>(); 2503 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) 2504 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) { 2505 if (!VDecl->hasExternalStorage()) 2506 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass); 2507 } 2508 } 2509 } 2510 ActOnObjCContainerFinishDefinition(); 2511 2512 for (unsigned i = 0; i != tuvNum; i++) { 2513 DeclGroupRef DG = allTUVars[i].getAsVal<DeclGroupRef>(); 2514 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) 2515 (*I)->setTopLevelDeclInObjCContainer(); 2516 Consumer.HandleTopLevelDeclInObjCContainer(DG); 2517 } 2518 2519 ActOnDocumentableDecl(ClassDecl); 2520 return ClassDecl; 2521 } 2522 2523 2524 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for 2525 /// objective-c's type qualifier from the parser version of the same info. 2526 static Decl::ObjCDeclQualifier 2527 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) { 2528 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal; 2529 } 2530 2531 static inline 2532 unsigned countAlignAttr(const AttrVec &A) { 2533 unsigned count=0; 2534 for (AttrVec::const_iterator i = A.begin(), e = A.end(); i != e; ++i) 2535 if ((*i)->getKind() == attr::Aligned) 2536 ++count; 2537 return count; 2538 } 2539 2540 static inline 2541 bool containsInvalidMethodImplAttribute(ObjCMethodDecl *IMD, 2542 const AttrVec &A) { 2543 // If method is only declared in implementation (private method), 2544 // No need to issue any diagnostics on method definition with attributes. 2545 if (!IMD) 2546 return false; 2547 2548 // method declared in interface has no attribute. 2549 // But implementation has attributes. This is invalid. 2550 // Except when implementation has 'Align' attribute which is 2551 // immaterial to method declared in interface. 2552 if (!IMD->hasAttrs()) 2553 return (A.size() > countAlignAttr(A)); 2554 2555 const AttrVec &D = IMD->getAttrs(); 2556 2557 unsigned countAlignOnImpl = countAlignAttr(A); 2558 if (!countAlignOnImpl && (A.size() != D.size())) 2559 return true; 2560 else if (countAlignOnImpl) { 2561 unsigned countAlignOnDecl = countAlignAttr(D); 2562 if (countAlignOnDecl && (A.size() != D.size())) 2563 return true; 2564 else if (!countAlignOnDecl && 2565 ((A.size()-countAlignOnImpl) != D.size())) 2566 return true; 2567 } 2568 2569 // attributes on method declaration and definition must match exactly. 2570 // Note that we have at most a couple of attributes on methods, so this 2571 // n*n search is good enough. 2572 for (AttrVec::const_iterator i = A.begin(), e = A.end(); i != e; ++i) { 2573 if ((*i)->getKind() == attr::Aligned) 2574 continue; 2575 bool match = false; 2576 for (AttrVec::const_iterator i1 = D.begin(), e1 = D.end(); i1 != e1; ++i1) { 2577 if ((*i)->getKind() == (*i1)->getKind()) { 2578 match = true; 2579 break; 2580 } 2581 } 2582 if (!match) 2583 return true; 2584 } 2585 2586 return false; 2587 } 2588 2589 /// \brief Check whether the declared result type of the given Objective-C 2590 /// method declaration is compatible with the method's class. 2591 /// 2592 static Sema::ResultTypeCompatibilityKind 2593 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method, 2594 ObjCInterfaceDecl *CurrentClass) { 2595 QualType ResultType = Method->getResultType(); 2596 2597 // If an Objective-C method inherits its related result type, then its 2598 // declared result type must be compatible with its own class type. The 2599 // declared result type is compatible if: 2600 if (const ObjCObjectPointerType *ResultObjectType 2601 = ResultType->getAs<ObjCObjectPointerType>()) { 2602 // - it is id or qualified id, or 2603 if (ResultObjectType->isObjCIdType() || 2604 ResultObjectType->isObjCQualifiedIdType()) 2605 return Sema::RTC_Compatible; 2606 2607 if (CurrentClass) { 2608 if (ObjCInterfaceDecl *ResultClass 2609 = ResultObjectType->getInterfaceDecl()) { 2610 // - it is the same as the method's class type, or 2611 if (declaresSameEntity(CurrentClass, ResultClass)) 2612 return Sema::RTC_Compatible; 2613 2614 // - it is a superclass of the method's class type 2615 if (ResultClass->isSuperClassOf(CurrentClass)) 2616 return Sema::RTC_Compatible; 2617 } 2618 } else { 2619 // Any Objective-C pointer type might be acceptable for a protocol 2620 // method; we just don't know. 2621 return Sema::RTC_Unknown; 2622 } 2623 } 2624 2625 return Sema::RTC_Incompatible; 2626 } 2627 2628 namespace { 2629 /// A helper class for searching for methods which a particular method 2630 /// overrides. 2631 class OverrideSearch { 2632 public: 2633 Sema &S; 2634 ObjCMethodDecl *Method; 2635 llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden; 2636 bool Recursive; 2637 2638 public: 2639 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) { 2640 Selector selector = method->getSelector(); 2641 2642 // Bypass this search if we've never seen an instance/class method 2643 // with this selector before. 2644 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector); 2645 if (it == S.MethodPool.end()) { 2646 if (!S.getExternalSource()) return; 2647 S.ReadMethodPool(selector); 2648 2649 it = S.MethodPool.find(selector); 2650 if (it == S.MethodPool.end()) 2651 return; 2652 } 2653 ObjCMethodList &list = 2654 method->isInstanceMethod() ? it->second.first : it->second.second; 2655 if (!list.Method) return; 2656 2657 ObjCContainerDecl *container 2658 = cast<ObjCContainerDecl>(method->getDeclContext()); 2659 2660 // Prevent the search from reaching this container again. This is 2661 // important with categories, which override methods from the 2662 // interface and each other. 2663 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) { 2664 searchFromContainer(container); 2665 if (ObjCInterfaceDecl *Interface = Category->getClassInterface()) 2666 searchFromContainer(Interface); 2667 } else { 2668 searchFromContainer(container); 2669 } 2670 } 2671 2672 typedef llvm::SmallPtrSet<ObjCMethodDecl*, 128>::iterator iterator; 2673 iterator begin() const { return Overridden.begin(); } 2674 iterator end() const { return Overridden.end(); } 2675 2676 private: 2677 void searchFromContainer(ObjCContainerDecl *container) { 2678 if (container->isInvalidDecl()) return; 2679 2680 switch (container->getDeclKind()) { 2681 #define OBJCCONTAINER(type, base) \ 2682 case Decl::type: \ 2683 searchFrom(cast<type##Decl>(container)); \ 2684 break; 2685 #define ABSTRACT_DECL(expansion) 2686 #define DECL(type, base) \ 2687 case Decl::type: 2688 #include "clang/AST/DeclNodes.inc" 2689 llvm_unreachable("not an ObjC container!"); 2690 } 2691 } 2692 2693 void searchFrom(ObjCProtocolDecl *protocol) { 2694 if (!protocol->hasDefinition()) 2695 return; 2696 2697 // A method in a protocol declaration overrides declarations from 2698 // referenced ("parent") protocols. 2699 search(protocol->getReferencedProtocols()); 2700 } 2701 2702 void searchFrom(ObjCCategoryDecl *category) { 2703 // A method in a category declaration overrides declarations from 2704 // the main class and from protocols the category references. 2705 // The main class is handled in the constructor. 2706 search(category->getReferencedProtocols()); 2707 } 2708 2709 void searchFrom(ObjCCategoryImplDecl *impl) { 2710 // A method in a category definition that has a category 2711 // declaration overrides declarations from the category 2712 // declaration. 2713 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) { 2714 search(category); 2715 if (ObjCInterfaceDecl *Interface = category->getClassInterface()) 2716 search(Interface); 2717 2718 // Otherwise it overrides declarations from the class. 2719 } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) { 2720 search(Interface); 2721 } 2722 } 2723 2724 void searchFrom(ObjCInterfaceDecl *iface) { 2725 // A method in a class declaration overrides declarations from 2726 if (!iface->hasDefinition()) 2727 return; 2728 2729 // - categories, 2730 for (ObjCInterfaceDecl::visible_categories_iterator 2731 cat = iface->visible_categories_begin(), 2732 catEnd = iface->visible_categories_end(); 2733 cat != catEnd; ++cat) { 2734 search(*cat); 2735 } 2736 2737 // - the super class, and 2738 if (ObjCInterfaceDecl *super = iface->getSuperClass()) 2739 search(super); 2740 2741 // - any referenced protocols. 2742 search(iface->getReferencedProtocols()); 2743 } 2744 2745 void searchFrom(ObjCImplementationDecl *impl) { 2746 // A method in a class implementation overrides declarations from 2747 // the class interface. 2748 if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) 2749 search(Interface); 2750 } 2751 2752 2753 void search(const ObjCProtocolList &protocols) { 2754 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end(); 2755 i != e; ++i) 2756 search(*i); 2757 } 2758 2759 void search(ObjCContainerDecl *container) { 2760 // Check for a method in this container which matches this selector. 2761 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(), 2762 Method->isInstanceMethod()); 2763 2764 // If we find one, record it and bail out. 2765 if (meth) { 2766 Overridden.insert(meth); 2767 return; 2768 } 2769 2770 // Otherwise, search for methods that a hypothetical method here 2771 // would have overridden. 2772 2773 // Note that we're now in a recursive case. 2774 Recursive = true; 2775 2776 searchFromContainer(container); 2777 } 2778 }; 2779 } 2780 2781 void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, 2782 ObjCInterfaceDecl *CurrentClass, 2783 ResultTypeCompatibilityKind RTC) { 2784 // Search for overridden methods and merge information down from them. 2785 OverrideSearch overrides(*this, ObjCMethod); 2786 // Keep track if the method overrides any method in the class's base classes, 2787 // its protocols, or its categories' protocols; we will keep that info 2788 // in the ObjCMethodDecl. 2789 // For this info, a method in an implementation is not considered as 2790 // overriding the same method in the interface or its categories. 2791 bool hasOverriddenMethodsInBaseOrProtocol = false; 2792 for (OverrideSearch::iterator 2793 i = overrides.begin(), e = overrides.end(); i != e; ++i) { 2794 ObjCMethodDecl *overridden = *i; 2795 2796 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) || 2797 CurrentClass != overridden->getClassInterface() || 2798 overridden->isOverriding()) 2799 hasOverriddenMethodsInBaseOrProtocol = true; 2800 2801 // Propagate down the 'related result type' bit from overridden methods. 2802 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType()) 2803 ObjCMethod->SetRelatedResultType(); 2804 2805 // Then merge the declarations. 2806 mergeObjCMethodDecls(ObjCMethod, overridden); 2807 2808 if (ObjCMethod->isImplicit() && overridden->isImplicit()) 2809 continue; // Conflicting properties are detected elsewhere. 2810 2811 // Check for overriding methods 2812 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) || 2813 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext())) 2814 CheckConflictingOverridingMethod(ObjCMethod, overridden, 2815 isa<ObjCProtocolDecl>(overridden->getDeclContext())); 2816 2817 if (CurrentClass && overridden->getDeclContext() != CurrentClass && 2818 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) && 2819 !overridden->isImplicit() /* not meant for properties */) { 2820 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(), 2821 E = ObjCMethod->param_end(); 2822 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(), 2823 PrevE = overridden->param_end(); 2824 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) { 2825 assert(PrevI != overridden->param_end() && "Param mismatch"); 2826 QualType T1 = Context.getCanonicalType((*ParamI)->getType()); 2827 QualType T2 = Context.getCanonicalType((*PrevI)->getType()); 2828 // If type of argument of method in this class does not match its 2829 // respective argument type in the super class method, issue warning; 2830 if (!Context.typesAreCompatible(T1, T2)) { 2831 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super) 2832 << T1 << T2; 2833 Diag(overridden->getLocation(), diag::note_previous_declaration); 2834 break; 2835 } 2836 } 2837 } 2838 } 2839 2840 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol); 2841 } 2842 2843 Decl *Sema::ActOnMethodDeclaration( 2844 Scope *S, 2845 SourceLocation MethodLoc, SourceLocation EndLoc, 2846 tok::TokenKind MethodType, 2847 ObjCDeclSpec &ReturnQT, ParsedType ReturnType, 2848 ArrayRef<SourceLocation> SelectorLocs, 2849 Selector Sel, 2850 // optional arguments. The number of types/arguments is obtained 2851 // from the Sel.getNumArgs(). 2852 ObjCArgInfo *ArgInfo, 2853 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args 2854 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind, 2855 bool isVariadic, bool MethodDefinition) { 2856 // Make sure we can establish a context for the method. 2857 if (!CurContext->isObjCContainer()) { 2858 Diag(MethodLoc, diag::error_missing_method_context); 2859 return 0; 2860 } 2861 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext); 2862 Decl *ClassDecl = cast<Decl>(OCD); 2863 QualType resultDeclType; 2864 2865 bool HasRelatedResultType = false; 2866 TypeSourceInfo *ResultTInfo = 0; 2867 if (ReturnType) { 2868 resultDeclType = GetTypeFromParser(ReturnType, &ResultTInfo); 2869 2870 // Methods cannot return interface types. All ObjC objects are 2871 // passed by reference. 2872 if (resultDeclType->isObjCObjectType()) { 2873 Diag(MethodLoc, diag::err_object_cannot_be_passed_returned_by_value) 2874 << 0 << resultDeclType; 2875 return 0; 2876 } 2877 2878 HasRelatedResultType = (resultDeclType == Context.getObjCInstanceType()); 2879 } else { // get the type for "id". 2880 resultDeclType = Context.getObjCIdType(); 2881 Diag(MethodLoc, diag::warn_missing_method_return_type) 2882 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)"); 2883 } 2884 2885 ObjCMethodDecl* ObjCMethod = 2886 ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel, 2887 resultDeclType, 2888 ResultTInfo, 2889 CurContext, 2890 MethodType == tok::minus, isVariadic, 2891 /*isPropertyAccessor=*/false, 2892 /*isImplicitlyDeclared=*/false, /*isDefined=*/false, 2893 MethodDeclKind == tok::objc_optional 2894 ? ObjCMethodDecl::Optional 2895 : ObjCMethodDecl::Required, 2896 HasRelatedResultType); 2897 2898 SmallVector<ParmVarDecl*, 16> Params; 2899 2900 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) { 2901 QualType ArgType; 2902 TypeSourceInfo *DI; 2903 2904 if (ArgInfo[i].Type == 0) { 2905 ArgType = Context.getObjCIdType(); 2906 DI = 0; 2907 } else { 2908 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI); 2909 } 2910 2911 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc, 2912 LookupOrdinaryName, ForRedeclaration); 2913 LookupName(R, S); 2914 if (R.isSingleResult()) { 2915 NamedDecl *PrevDecl = R.getFoundDecl(); 2916 if (S->isDeclScope(PrevDecl)) { 2917 Diag(ArgInfo[i].NameLoc, 2918 (MethodDefinition ? diag::warn_method_param_redefinition 2919 : diag::warn_method_param_declaration)) 2920 << ArgInfo[i].Name; 2921 Diag(PrevDecl->getLocation(), 2922 diag::note_previous_declaration); 2923 } 2924 } 2925 2926 SourceLocation StartLoc = DI 2927 ? DI->getTypeLoc().getBeginLoc() 2928 : ArgInfo[i].NameLoc; 2929 2930 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc, 2931 ArgInfo[i].NameLoc, ArgInfo[i].Name, 2932 ArgType, DI, SC_None, SC_None); 2933 2934 Param->setObjCMethodScopeInfo(i); 2935 2936 Param->setObjCDeclQualifier( 2937 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier())); 2938 2939 // Apply the attributes to the parameter. 2940 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs); 2941 2942 if (Param->hasAttr<BlocksAttr>()) { 2943 Diag(Param->getLocation(), diag::err_block_on_nonlocal); 2944 Param->setInvalidDecl(); 2945 } 2946 S->AddDecl(Param); 2947 IdResolver.AddDecl(Param); 2948 2949 Params.push_back(Param); 2950 } 2951 2952 for (unsigned i = 0, e = CNumArgs; i != e; ++i) { 2953 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param); 2954 QualType ArgType = Param->getType(); 2955 if (ArgType.isNull()) 2956 ArgType = Context.getObjCIdType(); 2957 else 2958 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]). 2959 ArgType = Context.getAdjustedParameterType(ArgType); 2960 if (ArgType->isObjCObjectType()) { 2961 Diag(Param->getLocation(), 2962 diag::err_object_cannot_be_passed_returned_by_value) 2963 << 1 << ArgType; 2964 Param->setInvalidDecl(); 2965 } 2966 Param->setDeclContext(ObjCMethod); 2967 2968 Params.push_back(Param); 2969 } 2970 2971 ObjCMethod->setMethodParams(Context, Params, SelectorLocs); 2972 ObjCMethod->setObjCDeclQualifier( 2973 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier())); 2974 2975 if (AttrList) 2976 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList); 2977 2978 // Add the method now. 2979 const ObjCMethodDecl *PrevMethod = 0; 2980 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) { 2981 if (MethodType == tok::minus) { 2982 PrevMethod = ImpDecl->getInstanceMethod(Sel); 2983 ImpDecl->addInstanceMethod(ObjCMethod); 2984 } else { 2985 PrevMethod = ImpDecl->getClassMethod(Sel); 2986 ImpDecl->addClassMethod(ObjCMethod); 2987 } 2988 2989 ObjCMethodDecl *IMD = 0; 2990 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) 2991 IMD = IDecl->lookupMethod(ObjCMethod->getSelector(), 2992 ObjCMethod->isInstanceMethod()); 2993 if (ObjCMethod->hasAttrs() && 2994 containsInvalidMethodImplAttribute(IMD, ObjCMethod->getAttrs())) { 2995 SourceLocation MethodLoc = IMD->getLocation(); 2996 if (!getSourceManager().isInSystemHeader(MethodLoc)) { 2997 Diag(EndLoc, diag::warn_attribute_method_def); 2998 Diag(MethodLoc, diag::note_method_declared_at) 2999 << ObjCMethod->getDeclName(); 3000 } 3001 } 3002 } else { 3003 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod); 3004 } 3005 3006 if (PrevMethod) { 3007 // You can never have two method definitions with the same name. 3008 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl) 3009 << ObjCMethod->getDeclName(); 3010 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 3011 } 3012 3013 // If this Objective-C method does not have a related result type, but we 3014 // are allowed to infer related result types, try to do so based on the 3015 // method family. 3016 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl); 3017 if (!CurrentClass) { 3018 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl)) 3019 CurrentClass = Cat->getClassInterface(); 3020 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl)) 3021 CurrentClass = Impl->getClassInterface(); 3022 else if (ObjCCategoryImplDecl *CatImpl 3023 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) 3024 CurrentClass = CatImpl->getClassInterface(); 3025 } 3026 3027 ResultTypeCompatibilityKind RTC 3028 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass); 3029 3030 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC); 3031 3032 bool ARCError = false; 3033 if (getLangOpts().ObjCAutoRefCount) 3034 ARCError = CheckARCMethodDecl(*this, ObjCMethod); 3035 3036 // Infer the related result type when possible. 3037 if (!ARCError && RTC == Sema::RTC_Compatible && 3038 !ObjCMethod->hasRelatedResultType() && 3039 LangOpts.ObjCInferRelatedResultType) { 3040 bool InferRelatedResultType = false; 3041 switch (ObjCMethod->getMethodFamily()) { 3042 case OMF_None: 3043 case OMF_copy: 3044 case OMF_dealloc: 3045 case OMF_finalize: 3046 case OMF_mutableCopy: 3047 case OMF_release: 3048 case OMF_retainCount: 3049 case OMF_performSelector: 3050 break; 3051 3052 case OMF_alloc: 3053 case OMF_new: 3054 InferRelatedResultType = ObjCMethod->isClassMethod(); 3055 break; 3056 3057 case OMF_init: 3058 case OMF_autorelease: 3059 case OMF_retain: 3060 case OMF_self: 3061 InferRelatedResultType = ObjCMethod->isInstanceMethod(); 3062 break; 3063 } 3064 3065 if (InferRelatedResultType) 3066 ObjCMethod->SetRelatedResultType(); 3067 } 3068 3069 ActOnDocumentableDecl(ObjCMethod); 3070 3071 return ObjCMethod; 3072 } 3073 3074 bool Sema::CheckObjCDeclScope(Decl *D) { 3075 // Following is also an error. But it is caused by a missing @end 3076 // and diagnostic is issued elsewhere. 3077 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext())) 3078 return false; 3079 3080 // If we switched context to translation unit while we are still lexically in 3081 // an objc container, it means the parser missed emitting an error. 3082 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext())) 3083 return false; 3084 3085 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope); 3086 D->setInvalidDecl(); 3087 3088 return true; 3089 } 3090 3091 /// Called whenever \@defs(ClassName) is encountered in the source. Inserts the 3092 /// instance variables of ClassName into Decls. 3093 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, 3094 IdentifierInfo *ClassName, 3095 SmallVectorImpl<Decl*> &Decls) { 3096 // Check that ClassName is a valid class 3097 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart); 3098 if (!Class) { 3099 Diag(DeclStart, diag::err_undef_interface) << ClassName; 3100 return; 3101 } 3102 if (LangOpts.ObjCRuntime.isNonFragile()) { 3103 Diag(DeclStart, diag::err_atdef_nonfragile_interface); 3104 return; 3105 } 3106 3107 // Collect the instance variables 3108 SmallVector<const ObjCIvarDecl*, 32> Ivars; 3109 Context.DeepCollectObjCIvars(Class, true, Ivars); 3110 // For each ivar, create a fresh ObjCAtDefsFieldDecl. 3111 for (unsigned i = 0; i < Ivars.size(); i++) { 3112 const FieldDecl* ID = cast<FieldDecl>(Ivars[i]); 3113 RecordDecl *Record = dyn_cast<RecordDecl>(TagD); 3114 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record, 3115 /*FIXME: StartL=*/ID->getLocation(), 3116 ID->getLocation(), 3117 ID->getIdentifier(), ID->getType(), 3118 ID->getBitWidth()); 3119 Decls.push_back(FD); 3120 } 3121 3122 // Introduce all of these fields into the appropriate scope. 3123 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin(); 3124 D != Decls.end(); ++D) { 3125 FieldDecl *FD = cast<FieldDecl>(*D); 3126 if (getLangOpts().CPlusPlus) 3127 PushOnScopeChains(cast<FieldDecl>(FD), S); 3128 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD)) 3129 Record->addDecl(FD); 3130 } 3131 } 3132 3133 /// \brief Build a type-check a new Objective-C exception variable declaration. 3134 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T, 3135 SourceLocation StartLoc, 3136 SourceLocation IdLoc, 3137 IdentifierInfo *Id, 3138 bool Invalid) { 3139 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 3140 // duration shall not be qualified by an address-space qualifier." 3141 // Since all parameters have automatic store duration, they can not have 3142 // an address space. 3143 if (T.getAddressSpace() != 0) { 3144 Diag(IdLoc, diag::err_arg_with_address_space); 3145 Invalid = true; 3146 } 3147 3148 // An @catch parameter must be an unqualified object pointer type; 3149 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"? 3150 if (Invalid) { 3151 // Don't do any further checking. 3152 } else if (T->isDependentType()) { 3153 // Okay: we don't know what this type will instantiate to. 3154 } else if (!T->isObjCObjectPointerType()) { 3155 Invalid = true; 3156 Diag(IdLoc ,diag::err_catch_param_not_objc_type); 3157 } else if (T->isObjCQualifiedIdType()) { 3158 Invalid = true; 3159 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm); 3160 } 3161 3162 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id, 3163 T, TInfo, SC_None, SC_None); 3164 New->setExceptionVariable(true); 3165 3166 // In ARC, infer 'retaining' for variables of retainable type. 3167 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New)) 3168 Invalid = true; 3169 3170 if (Invalid) 3171 New->setInvalidDecl(); 3172 return New; 3173 } 3174 3175 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) { 3176 const DeclSpec &DS = D.getDeclSpec(); 3177 3178 // We allow the "register" storage class on exception variables because 3179 // GCC did, but we drop it completely. Any other storage class is an error. 3180 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 3181 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm) 3182 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc())); 3183 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 3184 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm) 3185 << DS.getStorageClassSpec(); 3186 } 3187 if (D.getDeclSpec().isThreadSpecified()) 3188 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 3189 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3190 3191 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 3192 3193 // Check that there are no default arguments inside the type of this 3194 // exception object (C++ only). 3195 if (getLangOpts().CPlusPlus) 3196 CheckExtraCXXDefaultArguments(D); 3197 3198 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 3199 QualType ExceptionType = TInfo->getType(); 3200 3201 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType, 3202 D.getSourceRange().getBegin(), 3203 D.getIdentifierLoc(), 3204 D.getIdentifier(), 3205 D.isInvalidType()); 3206 3207 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 3208 if (D.getCXXScopeSpec().isSet()) { 3209 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm) 3210 << D.getCXXScopeSpec().getRange(); 3211 New->setInvalidDecl(); 3212 } 3213 3214 // Add the parameter declaration into this scope. 3215 S->AddDecl(New); 3216 if (D.getIdentifier()) 3217 IdResolver.AddDecl(New); 3218 3219 ProcessDeclAttributes(S, New, D); 3220 3221 if (New->hasAttr<BlocksAttr>()) 3222 Diag(New->getLocation(), diag::err_block_on_nonlocal); 3223 return New; 3224 } 3225 3226 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require 3227 /// initialization. 3228 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, 3229 SmallVectorImpl<ObjCIvarDecl*> &Ivars) { 3230 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv; 3231 Iv= Iv->getNextIvar()) { 3232 QualType QT = Context.getBaseElementType(Iv->getType()); 3233 if (QT->isRecordType()) 3234 Ivars.push_back(Iv); 3235 } 3236 } 3237 3238 void Sema::DiagnoseUseOfUnimplementedSelectors() { 3239 // Load referenced selectors from the external source. 3240 if (ExternalSource) { 3241 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels; 3242 ExternalSource->ReadReferencedSelectors(Sels); 3243 for (unsigned I = 0, N = Sels.size(); I != N; ++I) 3244 ReferencedSelectors[Sels[I].first] = Sels[I].second; 3245 } 3246 3247 // Warning will be issued only when selector table is 3248 // generated (which means there is at lease one implementation 3249 // in the TU). This is to match gcc's behavior. 3250 if (ReferencedSelectors.empty() || 3251 !Context.AnyObjCImplementation()) 3252 return; 3253 for (llvm::DenseMap<Selector, SourceLocation>::iterator S = 3254 ReferencedSelectors.begin(), 3255 E = ReferencedSelectors.end(); S != E; ++S) { 3256 Selector Sel = (*S).first; 3257 if (!LookupImplementedMethodInGlobalPool(Sel)) 3258 Diag((*S).second, diag::warn_unimplemented_selector) << Sel; 3259 } 3260 return; 3261 } 3262