1 //===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for Objective C declarations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TypeLocBuilder.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/DeclObjC.h" 18 #include "clang/AST/Expr.h" 19 #include "clang/AST/ExprObjC.h" 20 #include "clang/AST/RecursiveASTVisitor.h" 21 #include "clang/Basic/SourceManager.h" 22 #include "clang/Basic/TargetInfo.h" 23 #include "clang/Sema/DeclSpec.h" 24 #include "clang/Sema/Lookup.h" 25 #include "clang/Sema/Scope.h" 26 #include "clang/Sema/ScopeInfo.h" 27 #include "clang/Sema/SemaInternal.h" 28 #include "llvm/ADT/DenseMap.h" 29 #include "llvm/ADT/DenseSet.h" 30 31 using namespace clang; 32 33 /// Check whether the given method, which must be in the 'init' 34 /// family, is a valid member of that family. 35 /// 36 /// \param receiverTypeIfCall - if null, check this as if declaring it; 37 /// if non-null, check this as if making a call to it with the given 38 /// receiver type 39 /// 40 /// \return true to indicate that there was an error and appropriate 41 /// actions were taken 42 bool Sema::checkInitMethod(ObjCMethodDecl *method, 43 QualType receiverTypeIfCall) { 44 if (method->isInvalidDecl()) return true; 45 46 // This castAs is safe: methods that don't return an object 47 // pointer won't be inferred as inits and will reject an explicit 48 // objc_method_family(init). 49 50 // We ignore protocols here. Should we? What about Class? 51 52 const ObjCObjectType *result = 53 method->getReturnType()->castAs<ObjCObjectPointerType>()->getObjectType(); 54 55 if (result->isObjCId()) { 56 return false; 57 } else if (result->isObjCClass()) { 58 // fall through: always an error 59 } else { 60 ObjCInterfaceDecl *resultClass = result->getInterface(); 61 assert(resultClass && "unexpected object type!"); 62 63 // It's okay for the result type to still be a forward declaration 64 // if we're checking an interface declaration. 65 if (!resultClass->hasDefinition()) { 66 if (receiverTypeIfCall.isNull() && 67 !isa<ObjCImplementationDecl>(method->getDeclContext())) 68 return false; 69 70 // Otherwise, we try to compare class types. 71 } else { 72 // If this method was declared in a protocol, we can't check 73 // anything unless we have a receiver type that's an interface. 74 const ObjCInterfaceDecl *receiverClass = nullptr; 75 if (isa<ObjCProtocolDecl>(method->getDeclContext())) { 76 if (receiverTypeIfCall.isNull()) 77 return false; 78 79 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>() 80 ->getInterfaceDecl(); 81 82 // This can be null for calls to e.g. id<Foo>. 83 if (!receiverClass) return false; 84 } else { 85 receiverClass = method->getClassInterface(); 86 assert(receiverClass && "method not associated with a class!"); 87 } 88 89 // If either class is a subclass of the other, it's fine. 90 if (receiverClass->isSuperClassOf(resultClass) || 91 resultClass->isSuperClassOf(receiverClass)) 92 return false; 93 } 94 } 95 96 SourceLocation loc = method->getLocation(); 97 98 // If we're in a system header, and this is not a call, just make 99 // the method unusable. 100 if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) { 101 method->addAttr(UnavailableAttr::CreateImplicit(Context, "", 102 UnavailableAttr::IR_ARCInitReturnsUnrelated, loc)); 103 return true; 104 } 105 106 // Otherwise, it's an error. 107 Diag(loc, diag::err_arc_init_method_unrelated_result_type); 108 method->setInvalidDecl(); 109 return true; 110 } 111 112 /// Issue a warning if the parameter of the overridden method is non-escaping 113 /// but the parameter of the overriding method is not. 114 static bool diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD, 115 Sema &S) { 116 if (OldD->hasAttr<NoEscapeAttr>() && !NewD->hasAttr<NoEscapeAttr>()) { 117 S.Diag(NewD->getLocation(), diag::warn_overriding_method_missing_noescape); 118 S.Diag(OldD->getLocation(), diag::note_overridden_marked_noescape); 119 return false; 120 } 121 122 return true; 123 } 124 125 /// Produce additional diagnostics if a category conforms to a protocol that 126 /// defines a method taking a non-escaping parameter. 127 static void diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD, 128 const ObjCCategoryDecl *CD, 129 const ObjCProtocolDecl *PD, Sema &S) { 130 if (!diagnoseNoescape(NewD, OldD, S)) 131 S.Diag(CD->getLocation(), diag::note_cat_conform_to_noescape_prot) 132 << CD->IsClassExtension() << PD 133 << cast<ObjCMethodDecl>(NewD->getDeclContext()); 134 } 135 136 void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, 137 const ObjCMethodDecl *Overridden) { 138 if (Overridden->hasRelatedResultType() && 139 !NewMethod->hasRelatedResultType()) { 140 // This can only happen when the method follows a naming convention that 141 // implies a related result type, and the original (overridden) method has 142 // a suitable return type, but the new (overriding) method does not have 143 // a suitable return type. 144 QualType ResultType = NewMethod->getReturnType(); 145 SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange(); 146 147 // Figure out which class this method is part of, if any. 148 ObjCInterfaceDecl *CurrentClass 149 = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext()); 150 if (!CurrentClass) { 151 DeclContext *DC = NewMethod->getDeclContext(); 152 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC)) 153 CurrentClass = Cat->getClassInterface(); 154 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC)) 155 CurrentClass = Impl->getClassInterface(); 156 else if (ObjCCategoryImplDecl *CatImpl 157 = dyn_cast<ObjCCategoryImplDecl>(DC)) 158 CurrentClass = CatImpl->getClassInterface(); 159 } 160 161 if (CurrentClass) { 162 Diag(NewMethod->getLocation(), 163 diag::warn_related_result_type_compatibility_class) 164 << Context.getObjCInterfaceType(CurrentClass) 165 << ResultType 166 << ResultTypeRange; 167 } else { 168 Diag(NewMethod->getLocation(), 169 diag::warn_related_result_type_compatibility_protocol) 170 << ResultType 171 << ResultTypeRange; 172 } 173 174 if (ObjCMethodFamily Family = Overridden->getMethodFamily()) 175 Diag(Overridden->getLocation(), 176 diag::note_related_result_type_family) 177 << /*overridden method*/ 0 178 << Family; 179 else 180 Diag(Overridden->getLocation(), 181 diag::note_related_result_type_overridden); 182 } 183 184 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() != 185 Overridden->hasAttr<NSReturnsRetainedAttr>())) { 186 Diag(NewMethod->getLocation(), 187 getLangOpts().ObjCAutoRefCount 188 ? diag::err_nsreturns_retained_attribute_mismatch 189 : diag::warn_nsreturns_retained_attribute_mismatch) 190 << 1; 191 Diag(Overridden->getLocation(), diag::note_previous_decl) << "method"; 192 } 193 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() != 194 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) { 195 Diag(NewMethod->getLocation(), 196 getLangOpts().ObjCAutoRefCount 197 ? diag::err_nsreturns_retained_attribute_mismatch 198 : diag::warn_nsreturns_retained_attribute_mismatch) 199 << 0; 200 Diag(Overridden->getLocation(), diag::note_previous_decl) << "method"; 201 } 202 203 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(), 204 oe = Overridden->param_end(); 205 for (ObjCMethodDecl::param_iterator ni = NewMethod->param_begin(), 206 ne = NewMethod->param_end(); 207 ni != ne && oi != oe; ++ni, ++oi) { 208 const ParmVarDecl *oldDecl = (*oi); 209 ParmVarDecl *newDecl = (*ni); 210 if (newDecl->hasAttr<NSConsumedAttr>() != 211 oldDecl->hasAttr<NSConsumedAttr>()) { 212 Diag(newDecl->getLocation(), 213 getLangOpts().ObjCAutoRefCount 214 ? diag::err_nsconsumed_attribute_mismatch 215 : diag::warn_nsconsumed_attribute_mismatch); 216 Diag(oldDecl->getLocation(), diag::note_previous_decl) << "parameter"; 217 } 218 219 diagnoseNoescape(newDecl, oldDecl, *this); 220 } 221 } 222 223 /// Check a method declaration for compatibility with the Objective-C 224 /// ARC conventions. 225 bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) { 226 ObjCMethodFamily family = method->getMethodFamily(); 227 switch (family) { 228 case OMF_None: 229 case OMF_finalize: 230 case OMF_retain: 231 case OMF_release: 232 case OMF_autorelease: 233 case OMF_retainCount: 234 case OMF_self: 235 case OMF_initialize: 236 case OMF_performSelector: 237 return false; 238 239 case OMF_dealloc: 240 if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) { 241 SourceRange ResultTypeRange = method->getReturnTypeSourceRange(); 242 if (ResultTypeRange.isInvalid()) 243 Diag(method->getLocation(), diag::err_dealloc_bad_result_type) 244 << method->getReturnType() 245 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)"); 246 else 247 Diag(method->getLocation(), diag::err_dealloc_bad_result_type) 248 << method->getReturnType() 249 << FixItHint::CreateReplacement(ResultTypeRange, "void"); 250 return true; 251 } 252 return false; 253 254 case OMF_init: 255 // If the method doesn't obey the init rules, don't bother annotating it. 256 if (checkInitMethod(method, QualType())) 257 return true; 258 259 method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context)); 260 261 // Don't add a second copy of this attribute, but otherwise don't 262 // let it be suppressed. 263 if (method->hasAttr<NSReturnsRetainedAttr>()) 264 return false; 265 break; 266 267 case OMF_alloc: 268 case OMF_copy: 269 case OMF_mutableCopy: 270 case OMF_new: 271 if (method->hasAttr<NSReturnsRetainedAttr>() || 272 method->hasAttr<NSReturnsNotRetainedAttr>() || 273 method->hasAttr<NSReturnsAutoreleasedAttr>()) 274 return false; 275 break; 276 } 277 278 method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context)); 279 return false; 280 } 281 282 static void DiagnoseObjCImplementedDeprecations(Sema &S, const NamedDecl *ND, 283 SourceLocation ImplLoc) { 284 if (!ND) 285 return; 286 bool IsCategory = false; 287 StringRef RealizedPlatform; 288 AvailabilityResult Availability = ND->getAvailability( 289 /*Message=*/nullptr, /*EnclosingVersion=*/VersionTuple(), 290 &RealizedPlatform); 291 if (Availability != AR_Deprecated) { 292 if (isa<ObjCMethodDecl>(ND)) { 293 if (Availability != AR_Unavailable) 294 return; 295 if (RealizedPlatform.empty()) 296 RealizedPlatform = S.Context.getTargetInfo().getPlatformName(); 297 // Warn about implementing unavailable methods, unless the unavailable 298 // is for an app extension. 299 if (RealizedPlatform.endswith("_app_extension")) 300 return; 301 S.Diag(ImplLoc, diag::warn_unavailable_def); 302 S.Diag(ND->getLocation(), diag::note_method_declared_at) 303 << ND->getDeclName(); 304 return; 305 } 306 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND)) { 307 if (!CD->getClassInterface()->isDeprecated()) 308 return; 309 ND = CD->getClassInterface(); 310 IsCategory = true; 311 } else 312 return; 313 } 314 S.Diag(ImplLoc, diag::warn_deprecated_def) 315 << (isa<ObjCMethodDecl>(ND) 316 ? /*Method*/ 0 317 : isa<ObjCCategoryDecl>(ND) || IsCategory ? /*Category*/ 2 318 : /*Class*/ 1); 319 if (isa<ObjCMethodDecl>(ND)) 320 S.Diag(ND->getLocation(), diag::note_method_declared_at) 321 << ND->getDeclName(); 322 else 323 S.Diag(ND->getLocation(), diag::note_previous_decl) 324 << (isa<ObjCCategoryDecl>(ND) ? "category" : "class"); 325 } 326 327 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global 328 /// pool. 329 void Sema::AddAnyMethodToGlobalPool(Decl *D) { 330 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D); 331 332 // If we don't have a valid method decl, simply return. 333 if (!MDecl) 334 return; 335 if (MDecl->isInstanceMethod()) 336 AddInstanceMethodToGlobalPool(MDecl, true); 337 else 338 AddFactoryMethodToGlobalPool(MDecl, true); 339 } 340 341 /// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer 342 /// has explicit ownership attribute; false otherwise. 343 static bool 344 HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) { 345 QualType T = Param->getType(); 346 347 if (const PointerType *PT = T->getAs<PointerType>()) { 348 T = PT->getPointeeType(); 349 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) { 350 T = RT->getPointeeType(); 351 } else { 352 return true; 353 } 354 355 // If we have a lifetime qualifier, but it's local, we must have 356 // inferred it. So, it is implicit. 357 return !T.getLocalQualifiers().hasObjCLifetime(); 358 } 359 360 /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible 361 /// and user declared, in the method definition's AST. 362 void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) { 363 ImplicitlyRetainedSelfLocs.clear(); 364 assert((getCurMethodDecl() == nullptr) && "Methodparsing confused"); 365 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D); 366 367 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 368 369 // If we don't have a valid method decl, simply return. 370 if (!MDecl) 371 return; 372 373 QualType ResultType = MDecl->getReturnType(); 374 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 375 !MDecl->isInvalidDecl() && 376 RequireCompleteType(MDecl->getLocation(), ResultType, 377 diag::err_func_def_incomplete_result)) 378 MDecl->setInvalidDecl(); 379 380 // Allow all of Sema to see that we are entering a method definition. 381 PushDeclContext(FnBodyScope, MDecl); 382 PushFunctionScope(); 383 384 // Create Decl objects for each parameter, entrring them in the scope for 385 // binding to their use. 386 387 // Insert the invisible arguments, self and _cmd! 388 MDecl->createImplicitParams(Context, MDecl->getClassInterface()); 389 390 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope); 391 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope); 392 393 // The ObjC parser requires parameter names so there's no need to check. 394 CheckParmsForFunctionDef(MDecl->parameters(), 395 /*CheckParameterNames=*/false); 396 397 // Introduce all of the other parameters into this scope. 398 for (auto *Param : MDecl->parameters()) { 399 if (!Param->isInvalidDecl() && 400 getLangOpts().ObjCAutoRefCount && 401 !HasExplicitOwnershipAttr(*this, Param)) 402 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) << 403 Param->getType(); 404 405 if (Param->getIdentifier()) 406 PushOnScopeChains(Param, FnBodyScope); 407 } 408 409 // In ARC, disallow definition of retain/release/autorelease/retainCount 410 if (getLangOpts().ObjCAutoRefCount) { 411 switch (MDecl->getMethodFamily()) { 412 case OMF_retain: 413 case OMF_retainCount: 414 case OMF_release: 415 case OMF_autorelease: 416 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def) 417 << 0 << MDecl->getSelector(); 418 break; 419 420 case OMF_None: 421 case OMF_dealloc: 422 case OMF_finalize: 423 case OMF_alloc: 424 case OMF_init: 425 case OMF_mutableCopy: 426 case OMF_copy: 427 case OMF_new: 428 case OMF_self: 429 case OMF_initialize: 430 case OMF_performSelector: 431 break; 432 } 433 } 434 435 // Warn on deprecated methods under -Wdeprecated-implementations, 436 // and prepare for warning on missing super calls. 437 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) { 438 ObjCMethodDecl *IMD = 439 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod()); 440 441 if (IMD) { 442 ObjCImplDecl *ImplDeclOfMethodDef = 443 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext()); 444 ObjCContainerDecl *ContDeclOfMethodDecl = 445 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext()); 446 ObjCImplDecl *ImplDeclOfMethodDecl = nullptr; 447 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl)) 448 ImplDeclOfMethodDecl = OID->getImplementation(); 449 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) { 450 if (CD->IsClassExtension()) { 451 if (ObjCInterfaceDecl *OID = CD->getClassInterface()) 452 ImplDeclOfMethodDecl = OID->getImplementation(); 453 } else 454 ImplDeclOfMethodDecl = CD->getImplementation(); 455 } 456 // No need to issue deprecated warning if deprecated mehod in class/category 457 // is being implemented in its own implementation (no overriding is involved). 458 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef) 459 DiagnoseObjCImplementedDeprecations(*this, IMD, MDecl->getLocation()); 460 } 461 462 if (MDecl->getMethodFamily() == OMF_init) { 463 if (MDecl->isDesignatedInitializerForTheInterface()) { 464 getCurFunction()->ObjCIsDesignatedInit = true; 465 getCurFunction()->ObjCWarnForNoDesignatedInitChain = 466 IC->getSuperClass() != nullptr; 467 } else if (IC->hasDesignatedInitializers()) { 468 getCurFunction()->ObjCIsSecondaryInit = true; 469 getCurFunction()->ObjCWarnForNoInitDelegation = true; 470 } 471 } 472 473 // If this is "dealloc" or "finalize", set some bit here. 474 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false. 475 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set. 476 // Only do this if the current class actually has a superclass. 477 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) { 478 ObjCMethodFamily Family = MDecl->getMethodFamily(); 479 if (Family == OMF_dealloc) { 480 if (!(getLangOpts().ObjCAutoRefCount || 481 getLangOpts().getGC() == LangOptions::GCOnly)) 482 getCurFunction()->ObjCShouldCallSuper = true; 483 484 } else if (Family == OMF_finalize) { 485 if (Context.getLangOpts().getGC() != LangOptions::NonGC) 486 getCurFunction()->ObjCShouldCallSuper = true; 487 488 } else { 489 const ObjCMethodDecl *SuperMethod = 490 SuperClass->lookupMethod(MDecl->getSelector(), 491 MDecl->isInstanceMethod()); 492 getCurFunction()->ObjCShouldCallSuper = 493 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>()); 494 } 495 } 496 } 497 } 498 499 namespace { 500 501 // Callback to only accept typo corrections that are Objective-C classes. 502 // If an ObjCInterfaceDecl* is given to the constructor, then the validation 503 // function will reject corrections to that class. 504 class ObjCInterfaceValidatorCCC final : public CorrectionCandidateCallback { 505 public: 506 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {} 507 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl) 508 : CurrentIDecl(IDecl) {} 509 510 bool ValidateCandidate(const TypoCorrection &candidate) override { 511 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>(); 512 return ID && !declaresSameEntity(ID, CurrentIDecl); 513 } 514 515 std::unique_ptr<CorrectionCandidateCallback> clone() override { 516 return std::make_unique<ObjCInterfaceValidatorCCC>(*this); 517 } 518 519 private: 520 ObjCInterfaceDecl *CurrentIDecl; 521 }; 522 523 } // end anonymous namespace 524 525 static void diagnoseUseOfProtocols(Sema &TheSema, 526 ObjCContainerDecl *CD, 527 ObjCProtocolDecl *const *ProtoRefs, 528 unsigned NumProtoRefs, 529 const SourceLocation *ProtoLocs) { 530 assert(ProtoRefs); 531 // Diagnose availability in the context of the ObjC container. 532 Sema::ContextRAII SavedContext(TheSema, CD); 533 for (unsigned i = 0; i < NumProtoRefs; ++i) { 534 (void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i], 535 /*UnknownObjCClass=*/nullptr, 536 /*ObjCPropertyAccess=*/false, 537 /*AvoidPartialAvailabilityChecks=*/true); 538 } 539 } 540 541 void Sema:: 542 ActOnSuperClassOfClassInterface(Scope *S, 543 SourceLocation AtInterfaceLoc, 544 ObjCInterfaceDecl *IDecl, 545 IdentifierInfo *ClassName, 546 SourceLocation ClassLoc, 547 IdentifierInfo *SuperName, 548 SourceLocation SuperLoc, 549 ArrayRef<ParsedType> SuperTypeArgs, 550 SourceRange SuperTypeArgsRange) { 551 // Check if a different kind of symbol declared in this scope. 552 NamedDecl *PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc, 553 LookupOrdinaryName); 554 555 if (!PrevDecl) { 556 // Try to correct for a typo in the superclass name without correcting 557 // to the class we're defining. 558 ObjCInterfaceValidatorCCC CCC(IDecl); 559 if (TypoCorrection Corrected = CorrectTypo( 560 DeclarationNameInfo(SuperName, SuperLoc), LookupOrdinaryName, 561 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 562 diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest) 563 << SuperName << ClassName); 564 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>(); 565 } 566 } 567 568 if (declaresSameEntity(PrevDecl, IDecl)) { 569 Diag(SuperLoc, diag::err_recursive_superclass) 570 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc); 571 IDecl->setEndOfDefinitionLoc(ClassLoc); 572 } else { 573 ObjCInterfaceDecl *SuperClassDecl = 574 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 575 QualType SuperClassType; 576 577 // Diagnose classes that inherit from deprecated classes. 578 if (SuperClassDecl) { 579 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc); 580 SuperClassType = Context.getObjCInterfaceType(SuperClassDecl); 581 } 582 583 if (PrevDecl && !SuperClassDecl) { 584 // The previous declaration was not a class decl. Check if we have a 585 // typedef. If we do, get the underlying class type. 586 if (const TypedefNameDecl *TDecl = 587 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) { 588 QualType T = TDecl->getUnderlyingType(); 589 if (T->isObjCObjectType()) { 590 if (NamedDecl *IDecl = T->castAs<ObjCObjectType>()->getInterface()) { 591 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl); 592 SuperClassType = Context.getTypeDeclType(TDecl); 593 594 // This handles the following case: 595 // @interface NewI @end 596 // typedef NewI DeprI __attribute__((deprecated("blah"))) 597 // @interface SI : DeprI /* warn here */ @end 598 (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc); 599 } 600 } 601 } 602 603 // This handles the following case: 604 // 605 // typedef int SuperClass; 606 // @interface MyClass : SuperClass {} @end 607 // 608 if (!SuperClassDecl) { 609 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName; 610 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 611 } 612 } 613 614 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) { 615 if (!SuperClassDecl) 616 Diag(SuperLoc, diag::err_undef_superclass) 617 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc); 618 else if (RequireCompleteType(SuperLoc, 619 SuperClassType, 620 diag::err_forward_superclass, 621 SuperClassDecl->getDeclName(), 622 ClassName, 623 SourceRange(AtInterfaceLoc, ClassLoc))) { 624 SuperClassDecl = nullptr; 625 SuperClassType = QualType(); 626 } 627 } 628 629 if (SuperClassType.isNull()) { 630 assert(!SuperClassDecl && "Failed to set SuperClassType?"); 631 return; 632 } 633 634 // Handle type arguments on the superclass. 635 TypeSourceInfo *SuperClassTInfo = nullptr; 636 if (!SuperTypeArgs.empty()) { 637 TypeResult fullSuperClassType = actOnObjCTypeArgsAndProtocolQualifiers( 638 S, 639 SuperLoc, 640 CreateParsedType(SuperClassType, 641 nullptr), 642 SuperTypeArgsRange.getBegin(), 643 SuperTypeArgs, 644 SuperTypeArgsRange.getEnd(), 645 SourceLocation(), 646 { }, 647 { }, 648 SourceLocation()); 649 if (!fullSuperClassType.isUsable()) 650 return; 651 652 SuperClassType = GetTypeFromParser(fullSuperClassType.get(), 653 &SuperClassTInfo); 654 } 655 656 if (!SuperClassTInfo) { 657 SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType, 658 SuperLoc); 659 } 660 661 IDecl->setSuperClass(SuperClassTInfo); 662 IDecl->setEndOfDefinitionLoc(SuperClassTInfo->getTypeLoc().getEndLoc()); 663 } 664 } 665 666 DeclResult Sema::actOnObjCTypeParam(Scope *S, 667 ObjCTypeParamVariance variance, 668 SourceLocation varianceLoc, 669 unsigned index, 670 IdentifierInfo *paramName, 671 SourceLocation paramLoc, 672 SourceLocation colonLoc, 673 ParsedType parsedTypeBound) { 674 // If there was an explicitly-provided type bound, check it. 675 TypeSourceInfo *typeBoundInfo = nullptr; 676 if (parsedTypeBound) { 677 // The type bound can be any Objective-C pointer type. 678 QualType typeBound = GetTypeFromParser(parsedTypeBound, &typeBoundInfo); 679 if (typeBound->isObjCObjectPointerType()) { 680 // okay 681 } else if (typeBound->isObjCObjectType()) { 682 // The user forgot the * on an Objective-C pointer type, e.g., 683 // "T : NSView". 684 SourceLocation starLoc = getLocForEndOfToken( 685 typeBoundInfo->getTypeLoc().getEndLoc()); 686 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(), 687 diag::err_objc_type_param_bound_missing_pointer) 688 << typeBound << paramName 689 << FixItHint::CreateInsertion(starLoc, " *"); 690 691 // Create a new type location builder so we can update the type 692 // location information we have. 693 TypeLocBuilder builder; 694 builder.pushFullCopy(typeBoundInfo->getTypeLoc()); 695 696 // Create the Objective-C pointer type. 697 typeBound = Context.getObjCObjectPointerType(typeBound); 698 ObjCObjectPointerTypeLoc newT 699 = builder.push<ObjCObjectPointerTypeLoc>(typeBound); 700 newT.setStarLoc(starLoc); 701 702 // Form the new type source information. 703 typeBoundInfo = builder.getTypeSourceInfo(Context, typeBound); 704 } else { 705 // Not a valid type bound. 706 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(), 707 diag::err_objc_type_param_bound_nonobject) 708 << typeBound << paramName; 709 710 // Forget the bound; we'll default to id later. 711 typeBoundInfo = nullptr; 712 } 713 714 // Type bounds cannot have qualifiers (even indirectly) or explicit 715 // nullability. 716 if (typeBoundInfo) { 717 QualType typeBound = typeBoundInfo->getType(); 718 TypeLoc qual = typeBoundInfo->getTypeLoc().findExplicitQualifierLoc(); 719 if (qual || typeBound.hasQualifiers()) { 720 bool diagnosed = false; 721 SourceRange rangeToRemove; 722 if (qual) { 723 if (auto attr = qual.getAs<AttributedTypeLoc>()) { 724 rangeToRemove = attr.getLocalSourceRange(); 725 if (attr.getTypePtr()->getImmediateNullability()) { 726 Diag(attr.getBeginLoc(), 727 diag::err_objc_type_param_bound_explicit_nullability) 728 << paramName << typeBound 729 << FixItHint::CreateRemoval(rangeToRemove); 730 diagnosed = true; 731 } 732 } 733 } 734 735 if (!diagnosed) { 736 Diag(qual ? qual.getBeginLoc() 737 : typeBoundInfo->getTypeLoc().getBeginLoc(), 738 diag::err_objc_type_param_bound_qualified) 739 << paramName << typeBound 740 << typeBound.getQualifiers().getAsString() 741 << FixItHint::CreateRemoval(rangeToRemove); 742 } 743 744 // If the type bound has qualifiers other than CVR, we need to strip 745 // them or we'll probably assert later when trying to apply new 746 // qualifiers. 747 Qualifiers quals = typeBound.getQualifiers(); 748 quals.removeCVRQualifiers(); 749 if (!quals.empty()) { 750 typeBoundInfo = 751 Context.getTrivialTypeSourceInfo(typeBound.getUnqualifiedType()); 752 } 753 } 754 } 755 } 756 757 // If there was no explicit type bound (or we removed it due to an error), 758 // use 'id' instead. 759 if (!typeBoundInfo) { 760 colonLoc = SourceLocation(); 761 typeBoundInfo = Context.getTrivialTypeSourceInfo(Context.getObjCIdType()); 762 } 763 764 // Create the type parameter. 765 return ObjCTypeParamDecl::Create(Context, CurContext, variance, varianceLoc, 766 index, paramLoc, paramName, colonLoc, 767 typeBoundInfo); 768 } 769 770 ObjCTypeParamList *Sema::actOnObjCTypeParamList(Scope *S, 771 SourceLocation lAngleLoc, 772 ArrayRef<Decl *> typeParamsIn, 773 SourceLocation rAngleLoc) { 774 // We know that the array only contains Objective-C type parameters. 775 ArrayRef<ObjCTypeParamDecl *> 776 typeParams( 777 reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()), 778 typeParamsIn.size()); 779 780 // Diagnose redeclarations of type parameters. 781 // We do this now because Objective-C type parameters aren't pushed into 782 // scope until later (after the instance variable block), but we want the 783 // diagnostics to occur right after we parse the type parameter list. 784 llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams; 785 for (auto typeParam : typeParams) { 786 auto known = knownParams.find(typeParam->getIdentifier()); 787 if (known != knownParams.end()) { 788 Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl) 789 << typeParam->getIdentifier() 790 << SourceRange(known->second->getLocation()); 791 792 typeParam->setInvalidDecl(); 793 } else { 794 knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam)); 795 796 // Push the type parameter into scope. 797 PushOnScopeChains(typeParam, S, /*AddToContext=*/false); 798 } 799 } 800 801 // Create the parameter list. 802 return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc); 803 } 804 805 void Sema::popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList) { 806 for (auto typeParam : *typeParamList) { 807 if (!typeParam->isInvalidDecl()) { 808 S->RemoveDecl(typeParam); 809 IdResolver.RemoveDecl(typeParam); 810 } 811 } 812 } 813 814 namespace { 815 /// The context in which an Objective-C type parameter list occurs, for use 816 /// in diagnostics. 817 enum class TypeParamListContext { 818 ForwardDeclaration, 819 Definition, 820 Category, 821 Extension 822 }; 823 } // end anonymous namespace 824 825 /// Check consistency between two Objective-C type parameter lists, e.g., 826 /// between a category/extension and an \@interface or between an \@class and an 827 /// \@interface. 828 static bool checkTypeParamListConsistency(Sema &S, 829 ObjCTypeParamList *prevTypeParams, 830 ObjCTypeParamList *newTypeParams, 831 TypeParamListContext newContext) { 832 // If the sizes don't match, complain about that. 833 if (prevTypeParams->size() != newTypeParams->size()) { 834 SourceLocation diagLoc; 835 if (newTypeParams->size() > prevTypeParams->size()) { 836 diagLoc = newTypeParams->begin()[prevTypeParams->size()]->getLocation(); 837 } else { 838 diagLoc = S.getLocForEndOfToken(newTypeParams->back()->getEndLoc()); 839 } 840 841 S.Diag(diagLoc, diag::err_objc_type_param_arity_mismatch) 842 << static_cast<unsigned>(newContext) 843 << (newTypeParams->size() > prevTypeParams->size()) 844 << prevTypeParams->size() 845 << newTypeParams->size(); 846 847 return true; 848 } 849 850 // Match up the type parameters. 851 for (unsigned i = 0, n = prevTypeParams->size(); i != n; ++i) { 852 ObjCTypeParamDecl *prevTypeParam = prevTypeParams->begin()[i]; 853 ObjCTypeParamDecl *newTypeParam = newTypeParams->begin()[i]; 854 855 // Check for consistency of the variance. 856 if (newTypeParam->getVariance() != prevTypeParam->getVariance()) { 857 if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant && 858 newContext != TypeParamListContext::Definition) { 859 // When the new type parameter is invariant and is not part 860 // of the definition, just propagate the variance. 861 newTypeParam->setVariance(prevTypeParam->getVariance()); 862 } else if (prevTypeParam->getVariance() 863 == ObjCTypeParamVariance::Invariant && 864 !(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) && 865 cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) 866 ->getDefinition() == prevTypeParam->getDeclContext())) { 867 // When the old parameter is invariant and was not part of the 868 // definition, just ignore the difference because it doesn't 869 // matter. 870 } else { 871 { 872 // Diagnose the conflict and update the second declaration. 873 SourceLocation diagLoc = newTypeParam->getVarianceLoc(); 874 if (diagLoc.isInvalid()) 875 diagLoc = newTypeParam->getBeginLoc(); 876 877 auto diag = S.Diag(diagLoc, 878 diag::err_objc_type_param_variance_conflict) 879 << static_cast<unsigned>(newTypeParam->getVariance()) 880 << newTypeParam->getDeclName() 881 << static_cast<unsigned>(prevTypeParam->getVariance()) 882 << prevTypeParam->getDeclName(); 883 switch (prevTypeParam->getVariance()) { 884 case ObjCTypeParamVariance::Invariant: 885 diag << FixItHint::CreateRemoval(newTypeParam->getVarianceLoc()); 886 break; 887 888 case ObjCTypeParamVariance::Covariant: 889 case ObjCTypeParamVariance::Contravariant: { 890 StringRef newVarianceStr 891 = prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant 892 ? "__covariant" 893 : "__contravariant"; 894 if (newTypeParam->getVariance() 895 == ObjCTypeParamVariance::Invariant) { 896 diag << FixItHint::CreateInsertion(newTypeParam->getBeginLoc(), 897 (newVarianceStr + " ").str()); 898 } else { 899 diag << FixItHint::CreateReplacement(newTypeParam->getVarianceLoc(), 900 newVarianceStr); 901 } 902 } 903 } 904 } 905 906 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here) 907 << prevTypeParam->getDeclName(); 908 909 // Override the variance. 910 newTypeParam->setVariance(prevTypeParam->getVariance()); 911 } 912 } 913 914 // If the bound types match, there's nothing to do. 915 if (S.Context.hasSameType(prevTypeParam->getUnderlyingType(), 916 newTypeParam->getUnderlyingType())) 917 continue; 918 919 // If the new type parameter's bound was explicit, complain about it being 920 // different from the original. 921 if (newTypeParam->hasExplicitBound()) { 922 SourceRange newBoundRange = newTypeParam->getTypeSourceInfo() 923 ->getTypeLoc().getSourceRange(); 924 S.Diag(newBoundRange.getBegin(), diag::err_objc_type_param_bound_conflict) 925 << newTypeParam->getUnderlyingType() 926 << newTypeParam->getDeclName() 927 << prevTypeParam->hasExplicitBound() 928 << prevTypeParam->getUnderlyingType() 929 << (newTypeParam->getDeclName() == prevTypeParam->getDeclName()) 930 << prevTypeParam->getDeclName() 931 << FixItHint::CreateReplacement( 932 newBoundRange, 933 prevTypeParam->getUnderlyingType().getAsString( 934 S.Context.getPrintingPolicy())); 935 936 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here) 937 << prevTypeParam->getDeclName(); 938 939 // Override the new type parameter's bound type with the previous type, 940 // so that it's consistent. 941 S.Context.adjustObjCTypeParamBoundType(prevTypeParam, newTypeParam); 942 continue; 943 } 944 945 // The new type parameter got the implicit bound of 'id'. That's okay for 946 // categories and extensions (overwrite it later), but not for forward 947 // declarations and @interfaces, because those must be standalone. 948 if (newContext == TypeParamListContext::ForwardDeclaration || 949 newContext == TypeParamListContext::Definition) { 950 // Diagnose this problem for forward declarations and definitions. 951 SourceLocation insertionLoc 952 = S.getLocForEndOfToken(newTypeParam->getLocation()); 953 std::string newCode 954 = " : " + prevTypeParam->getUnderlyingType().getAsString( 955 S.Context.getPrintingPolicy()); 956 S.Diag(newTypeParam->getLocation(), 957 diag::err_objc_type_param_bound_missing) 958 << prevTypeParam->getUnderlyingType() 959 << newTypeParam->getDeclName() 960 << (newContext == TypeParamListContext::ForwardDeclaration) 961 << FixItHint::CreateInsertion(insertionLoc, newCode); 962 963 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here) 964 << prevTypeParam->getDeclName(); 965 } 966 967 // Update the new type parameter's bound to match the previous one. 968 S.Context.adjustObjCTypeParamBoundType(prevTypeParam, newTypeParam); 969 } 970 971 return false; 972 } 973 974 Decl *Sema::ActOnStartClassInterface( 975 Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, 976 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, 977 IdentifierInfo *SuperName, SourceLocation SuperLoc, 978 ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange, 979 Decl *const *ProtoRefs, unsigned NumProtoRefs, 980 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, 981 const ParsedAttributesView &AttrList) { 982 assert(ClassName && "Missing class identifier"); 983 984 // Check for another declaration kind with the same name. 985 NamedDecl *PrevDecl = 986 LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName, 987 forRedeclarationInCurContext()); 988 989 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 990 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName; 991 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 992 } 993 994 // Create a declaration to describe this @interface. 995 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 996 997 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) { 998 // A previous decl with a different name is because of 999 // @compatibility_alias, for example: 1000 // \code 1001 // @class NewImage; 1002 // @compatibility_alias OldImage NewImage; 1003 // \endcode 1004 // A lookup for 'OldImage' will return the 'NewImage' decl. 1005 // 1006 // In such a case use the real declaration name, instead of the alias one, 1007 // otherwise we will break IdentifierResolver and redecls-chain invariants. 1008 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl 1009 // has been aliased. 1010 ClassName = PrevIDecl->getIdentifier(); 1011 } 1012 1013 // If there was a forward declaration with type parameters, check 1014 // for consistency. 1015 if (PrevIDecl) { 1016 if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) { 1017 if (typeParamList) { 1018 // Both have type parameter lists; check for consistency. 1019 if (checkTypeParamListConsistency(*this, prevTypeParamList, 1020 typeParamList, 1021 TypeParamListContext::Definition)) { 1022 typeParamList = nullptr; 1023 } 1024 } else { 1025 Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first) 1026 << ClassName; 1027 Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl) 1028 << ClassName; 1029 1030 // Clone the type parameter list. 1031 SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams; 1032 for (auto typeParam : *prevTypeParamList) { 1033 clonedTypeParams.push_back( 1034 ObjCTypeParamDecl::Create( 1035 Context, 1036 CurContext, 1037 typeParam->getVariance(), 1038 SourceLocation(), 1039 typeParam->getIndex(), 1040 SourceLocation(), 1041 typeParam->getIdentifier(), 1042 SourceLocation(), 1043 Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType()))); 1044 } 1045 1046 typeParamList = ObjCTypeParamList::create(Context, 1047 SourceLocation(), 1048 clonedTypeParams, 1049 SourceLocation()); 1050 } 1051 } 1052 } 1053 1054 ObjCInterfaceDecl *IDecl 1055 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName, 1056 typeParamList, PrevIDecl, ClassLoc); 1057 if (PrevIDecl) { 1058 // Class already seen. Was it a definition? 1059 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) { 1060 Diag(AtInterfaceLoc, diag::err_duplicate_class_def) 1061 << PrevIDecl->getDeclName(); 1062 Diag(Def->getLocation(), diag::note_previous_definition); 1063 IDecl->setInvalidDecl(); 1064 } 1065 } 1066 1067 ProcessDeclAttributeList(TUScope, IDecl, AttrList); 1068 AddPragmaAttributes(TUScope, IDecl); 1069 PushOnScopeChains(IDecl, TUScope); 1070 1071 // Start the definition of this class. If we're in a redefinition case, there 1072 // may already be a definition, so we'll end up adding to it. 1073 if (!IDecl->hasDefinition()) 1074 IDecl->startDefinition(); 1075 1076 if (SuperName) { 1077 // Diagnose availability in the context of the @interface. 1078 ContextRAII SavedContext(*this, IDecl); 1079 1080 ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl, 1081 ClassName, ClassLoc, 1082 SuperName, SuperLoc, SuperTypeArgs, 1083 SuperTypeArgsRange); 1084 } else { // we have a root class. 1085 IDecl->setEndOfDefinitionLoc(ClassLoc); 1086 } 1087 1088 // Check then save referenced protocols. 1089 if (NumProtoRefs) { 1090 diagnoseUseOfProtocols(*this, IDecl, (ObjCProtocolDecl*const*)ProtoRefs, 1091 NumProtoRefs, ProtoLocs); 1092 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs, 1093 ProtoLocs, Context); 1094 IDecl->setEndOfDefinitionLoc(EndProtoLoc); 1095 } 1096 1097 CheckObjCDeclScope(IDecl); 1098 return ActOnObjCContainerStartDefinition(IDecl); 1099 } 1100 1101 /// ActOnTypedefedProtocols - this action finds protocol list as part of the 1102 /// typedef'ed use for a qualified super class and adds them to the list 1103 /// of the protocols. 1104 void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, 1105 SmallVectorImpl<SourceLocation> &ProtocolLocs, 1106 IdentifierInfo *SuperName, 1107 SourceLocation SuperLoc) { 1108 if (!SuperName) 1109 return; 1110 NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc, 1111 LookupOrdinaryName); 1112 if (!IDecl) 1113 return; 1114 1115 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) { 1116 QualType T = TDecl->getUnderlyingType(); 1117 if (T->isObjCObjectType()) 1118 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>()) { 1119 ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end()); 1120 // FIXME: Consider whether this should be an invalid loc since the loc 1121 // is not actually pointing to a protocol name reference but to the 1122 // typedef reference. Note that the base class name loc is also pointing 1123 // at the typedef. 1124 ProtocolLocs.append(OPT->getNumProtocols(), SuperLoc); 1125 } 1126 } 1127 } 1128 1129 /// ActOnCompatibilityAlias - this action is called after complete parsing of 1130 /// a \@compatibility_alias declaration. It sets up the alias relationships. 1131 Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc, 1132 IdentifierInfo *AliasName, 1133 SourceLocation AliasLocation, 1134 IdentifierInfo *ClassName, 1135 SourceLocation ClassLocation) { 1136 // Look for previous declaration of alias name 1137 NamedDecl *ADecl = 1138 LookupSingleName(TUScope, AliasName, AliasLocation, LookupOrdinaryName, 1139 forRedeclarationInCurContext()); 1140 if (ADecl) { 1141 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName; 1142 Diag(ADecl->getLocation(), diag::note_previous_declaration); 1143 return nullptr; 1144 } 1145 // Check for class declaration 1146 NamedDecl *CDeclU = 1147 LookupSingleName(TUScope, ClassName, ClassLocation, LookupOrdinaryName, 1148 forRedeclarationInCurContext()); 1149 if (const TypedefNameDecl *TDecl = 1150 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) { 1151 QualType T = TDecl->getUnderlyingType(); 1152 if (T->isObjCObjectType()) { 1153 if (NamedDecl *IDecl = T->castAs<ObjCObjectType>()->getInterface()) { 1154 ClassName = IDecl->getIdentifier(); 1155 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation, 1156 LookupOrdinaryName, 1157 forRedeclarationInCurContext()); 1158 } 1159 } 1160 } 1161 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU); 1162 if (!CDecl) { 1163 Diag(ClassLocation, diag::warn_undef_interface) << ClassName; 1164 if (CDeclU) 1165 Diag(CDeclU->getLocation(), diag::note_previous_declaration); 1166 return nullptr; 1167 } 1168 1169 // Everything checked out, instantiate a new alias declaration AST. 1170 ObjCCompatibleAliasDecl *AliasDecl = 1171 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl); 1172 1173 if (!CheckObjCDeclScope(AliasDecl)) 1174 PushOnScopeChains(AliasDecl, TUScope); 1175 1176 return AliasDecl; 1177 } 1178 1179 bool Sema::CheckForwardProtocolDeclarationForCircularDependency( 1180 IdentifierInfo *PName, 1181 SourceLocation &Ploc, SourceLocation PrevLoc, 1182 const ObjCList<ObjCProtocolDecl> &PList) { 1183 1184 bool res = false; 1185 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(), 1186 E = PList.end(); I != E; ++I) { 1187 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(), 1188 Ploc)) { 1189 if (PDecl->getIdentifier() == PName) { 1190 Diag(Ploc, diag::err_protocol_has_circular_dependency); 1191 Diag(PrevLoc, diag::note_previous_definition); 1192 res = true; 1193 } 1194 1195 if (!PDecl->hasDefinition()) 1196 continue; 1197 1198 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc, 1199 PDecl->getLocation(), PDecl->getReferencedProtocols())) 1200 res = true; 1201 } 1202 } 1203 return res; 1204 } 1205 1206 Decl *Sema::ActOnStartProtocolInterface( 1207 SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName, 1208 SourceLocation ProtocolLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs, 1209 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, 1210 const ParsedAttributesView &AttrList) { 1211 bool err = false; 1212 // FIXME: Deal with AttrList. 1213 assert(ProtocolName && "Missing protocol identifier"); 1214 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc, 1215 forRedeclarationInCurContext()); 1216 ObjCProtocolDecl *PDecl = nullptr; 1217 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) { 1218 // If we already have a definition, complain. 1219 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName; 1220 Diag(Def->getLocation(), diag::note_previous_definition); 1221 1222 // Create a new protocol that is completely distinct from previous 1223 // declarations, and do not make this protocol available for name lookup. 1224 // That way, we'll end up completely ignoring the duplicate. 1225 // FIXME: Can we turn this into an error? 1226 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName, 1227 ProtocolLoc, AtProtoInterfaceLoc, 1228 /*PrevDecl=*/nullptr); 1229 1230 // If we are using modules, add the decl to the context in order to 1231 // serialize something meaningful. 1232 if (getLangOpts().Modules) 1233 PushOnScopeChains(PDecl, TUScope); 1234 PDecl->startDefinition(); 1235 } else { 1236 if (PrevDecl) { 1237 // Check for circular dependencies among protocol declarations. This can 1238 // only happen if this protocol was forward-declared. 1239 ObjCList<ObjCProtocolDecl> PList; 1240 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context); 1241 err = CheckForwardProtocolDeclarationForCircularDependency( 1242 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList); 1243 } 1244 1245 // Create the new declaration. 1246 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName, 1247 ProtocolLoc, AtProtoInterfaceLoc, 1248 /*PrevDecl=*/PrevDecl); 1249 1250 PushOnScopeChains(PDecl, TUScope); 1251 PDecl->startDefinition(); 1252 } 1253 1254 ProcessDeclAttributeList(TUScope, PDecl, AttrList); 1255 AddPragmaAttributes(TUScope, PDecl); 1256 1257 // Merge attributes from previous declarations. 1258 if (PrevDecl) 1259 mergeDeclAttributes(PDecl, PrevDecl); 1260 1261 if (!err && NumProtoRefs ) { 1262 /// Check then save referenced protocols. 1263 diagnoseUseOfProtocols(*this, PDecl, (ObjCProtocolDecl*const*)ProtoRefs, 1264 NumProtoRefs, ProtoLocs); 1265 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs, 1266 ProtoLocs, Context); 1267 } 1268 1269 CheckObjCDeclScope(PDecl); 1270 return ActOnObjCContainerStartDefinition(PDecl); 1271 } 1272 1273 static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl, 1274 ObjCProtocolDecl *&UndefinedProtocol) { 1275 if (!PDecl->hasDefinition() || 1276 !PDecl->getDefinition()->isUnconditionallyVisible()) { 1277 UndefinedProtocol = PDecl; 1278 return true; 1279 } 1280 1281 for (auto *PI : PDecl->protocols()) 1282 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) { 1283 UndefinedProtocol = PI; 1284 return true; 1285 } 1286 return false; 1287 } 1288 1289 /// FindProtocolDeclaration - This routine looks up protocols and 1290 /// issues an error if they are not declared. It returns list of 1291 /// protocol declarations in its 'Protocols' argument. 1292 void 1293 Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer, 1294 ArrayRef<IdentifierLocPair> ProtocolId, 1295 SmallVectorImpl<Decl *> &Protocols) { 1296 for (const IdentifierLocPair &Pair : ProtocolId) { 1297 ObjCProtocolDecl *PDecl = LookupProtocol(Pair.first, Pair.second); 1298 if (!PDecl) { 1299 DeclFilterCCC<ObjCProtocolDecl> CCC{}; 1300 TypoCorrection Corrected = CorrectTypo( 1301 DeclarationNameInfo(Pair.first, Pair.second), LookupObjCProtocolName, 1302 TUScope, nullptr, CCC, CTK_ErrorRecovery); 1303 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>())) 1304 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest) 1305 << Pair.first); 1306 } 1307 1308 if (!PDecl) { 1309 Diag(Pair.second, diag::err_undeclared_protocol) << Pair.first; 1310 continue; 1311 } 1312 // If this is a forward protocol declaration, get its definition. 1313 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition()) 1314 PDecl = PDecl->getDefinition(); 1315 1316 // For an objc container, delay protocol reference checking until after we 1317 // can set the objc decl as the availability context, otherwise check now. 1318 if (!ForObjCContainer) { 1319 (void)DiagnoseUseOfDecl(PDecl, Pair.second); 1320 } 1321 1322 // If this is a forward declaration and we are supposed to warn in this 1323 // case, do it. 1324 // FIXME: Recover nicely in the hidden case. 1325 ObjCProtocolDecl *UndefinedProtocol; 1326 1327 if (WarnOnDeclarations && 1328 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) { 1329 Diag(Pair.second, diag::warn_undef_protocolref) << Pair.first; 1330 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined) 1331 << UndefinedProtocol; 1332 } 1333 Protocols.push_back(PDecl); 1334 } 1335 } 1336 1337 namespace { 1338 // Callback to only accept typo corrections that are either 1339 // Objective-C protocols or valid Objective-C type arguments. 1340 class ObjCTypeArgOrProtocolValidatorCCC final 1341 : public CorrectionCandidateCallback { 1342 ASTContext &Context; 1343 Sema::LookupNameKind LookupKind; 1344 public: 1345 ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context, 1346 Sema::LookupNameKind lookupKind) 1347 : Context(context), LookupKind(lookupKind) { } 1348 1349 bool ValidateCandidate(const TypoCorrection &candidate) override { 1350 // If we're allowed to find protocols and we have a protocol, accept it. 1351 if (LookupKind != Sema::LookupOrdinaryName) { 1352 if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>()) 1353 return true; 1354 } 1355 1356 // If we're allowed to find type names and we have one, accept it. 1357 if (LookupKind != Sema::LookupObjCProtocolName) { 1358 // If we have a type declaration, we might accept this result. 1359 if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) { 1360 // If we found a tag declaration outside of C++, skip it. This 1361 // can happy because we look for any name when there is no 1362 // bias to protocol or type names. 1363 if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus) 1364 return false; 1365 1366 // Make sure the type is something we would accept as a type 1367 // argument. 1368 auto type = Context.getTypeDeclType(typeDecl); 1369 if (type->isObjCObjectPointerType() || 1370 type->isBlockPointerType() || 1371 type->isDependentType() || 1372 type->isObjCObjectType()) 1373 return true; 1374 1375 return false; 1376 } 1377 1378 // If we have an Objective-C class type, accept it; there will 1379 // be another fix to add the '*'. 1380 if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>()) 1381 return true; 1382 1383 return false; 1384 } 1385 1386 return false; 1387 } 1388 1389 std::unique_ptr<CorrectionCandidateCallback> clone() override { 1390 return std::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(*this); 1391 } 1392 }; 1393 } // end anonymous namespace 1394 1395 void Sema::DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId, 1396 SourceLocation ProtocolLoc, 1397 IdentifierInfo *TypeArgId, 1398 SourceLocation TypeArgLoc, 1399 bool SelectProtocolFirst) { 1400 Diag(TypeArgLoc, diag::err_objc_type_args_and_protocols) 1401 << SelectProtocolFirst << TypeArgId << ProtocolId 1402 << SourceRange(ProtocolLoc); 1403 } 1404 1405 void Sema::actOnObjCTypeArgsOrProtocolQualifiers( 1406 Scope *S, 1407 ParsedType baseType, 1408 SourceLocation lAngleLoc, 1409 ArrayRef<IdentifierInfo *> identifiers, 1410 ArrayRef<SourceLocation> identifierLocs, 1411 SourceLocation rAngleLoc, 1412 SourceLocation &typeArgsLAngleLoc, 1413 SmallVectorImpl<ParsedType> &typeArgs, 1414 SourceLocation &typeArgsRAngleLoc, 1415 SourceLocation &protocolLAngleLoc, 1416 SmallVectorImpl<Decl *> &protocols, 1417 SourceLocation &protocolRAngleLoc, 1418 bool warnOnIncompleteProtocols) { 1419 // Local function that updates the declaration specifiers with 1420 // protocol information. 1421 unsigned numProtocolsResolved = 0; 1422 auto resolvedAsProtocols = [&] { 1423 assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols"); 1424 1425 // Determine whether the base type is a parameterized class, in 1426 // which case we want to warn about typos such as 1427 // "NSArray<NSObject>" (that should be NSArray<NSObject *>). 1428 ObjCInterfaceDecl *baseClass = nullptr; 1429 QualType base = GetTypeFromParser(baseType, nullptr); 1430 bool allAreTypeNames = false; 1431 SourceLocation firstClassNameLoc; 1432 if (!base.isNull()) { 1433 if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) { 1434 baseClass = objcObjectType->getInterface(); 1435 if (baseClass) { 1436 if (auto typeParams = baseClass->getTypeParamList()) { 1437 if (typeParams->size() == numProtocolsResolved) { 1438 // Note that we should be looking for type names, too. 1439 allAreTypeNames = true; 1440 } 1441 } 1442 } 1443 } 1444 } 1445 1446 for (unsigned i = 0, n = protocols.size(); i != n; ++i) { 1447 ObjCProtocolDecl *&proto 1448 = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]); 1449 // For an objc container, delay protocol reference checking until after we 1450 // can set the objc decl as the availability context, otherwise check now. 1451 if (!warnOnIncompleteProtocols) { 1452 (void)DiagnoseUseOfDecl(proto, identifierLocs[i]); 1453 } 1454 1455 // If this is a forward protocol declaration, get its definition. 1456 if (!proto->isThisDeclarationADefinition() && proto->getDefinition()) 1457 proto = proto->getDefinition(); 1458 1459 // If this is a forward declaration and we are supposed to warn in this 1460 // case, do it. 1461 // FIXME: Recover nicely in the hidden case. 1462 ObjCProtocolDecl *forwardDecl = nullptr; 1463 if (warnOnIncompleteProtocols && 1464 NestedProtocolHasNoDefinition(proto, forwardDecl)) { 1465 Diag(identifierLocs[i], diag::warn_undef_protocolref) 1466 << proto->getDeclName(); 1467 Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined) 1468 << forwardDecl; 1469 } 1470 1471 // If everything this far has been a type name (and we care 1472 // about such things), check whether this name refers to a type 1473 // as well. 1474 if (allAreTypeNames) { 1475 if (auto *decl = LookupSingleName(S, identifiers[i], identifierLocs[i], 1476 LookupOrdinaryName)) { 1477 if (isa<ObjCInterfaceDecl>(decl)) { 1478 if (firstClassNameLoc.isInvalid()) 1479 firstClassNameLoc = identifierLocs[i]; 1480 } else if (!isa<TypeDecl>(decl)) { 1481 // Not a type. 1482 allAreTypeNames = false; 1483 } 1484 } else { 1485 allAreTypeNames = false; 1486 } 1487 } 1488 } 1489 1490 // All of the protocols listed also have type names, and at least 1491 // one is an Objective-C class name. Check whether all of the 1492 // protocol conformances are declared by the base class itself, in 1493 // which case we warn. 1494 if (allAreTypeNames && firstClassNameLoc.isValid()) { 1495 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> knownProtocols; 1496 Context.CollectInheritedProtocols(baseClass, knownProtocols); 1497 bool allProtocolsDeclared = true; 1498 for (auto proto : protocols) { 1499 if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) { 1500 allProtocolsDeclared = false; 1501 break; 1502 } 1503 } 1504 1505 if (allProtocolsDeclared) { 1506 Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type) 1507 << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc) 1508 << FixItHint::CreateInsertion(getLocForEndOfToken(firstClassNameLoc), 1509 " *"); 1510 } 1511 } 1512 1513 protocolLAngleLoc = lAngleLoc; 1514 protocolRAngleLoc = rAngleLoc; 1515 assert(protocols.size() == identifierLocs.size()); 1516 }; 1517 1518 // Attempt to resolve all of the identifiers as protocols. 1519 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) { 1520 ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]); 1521 protocols.push_back(proto); 1522 if (proto) 1523 ++numProtocolsResolved; 1524 } 1525 1526 // If all of the names were protocols, these were protocol qualifiers. 1527 if (numProtocolsResolved == identifiers.size()) 1528 return resolvedAsProtocols(); 1529 1530 // Attempt to resolve all of the identifiers as type names or 1531 // Objective-C class names. The latter is technically ill-formed, 1532 // but is probably something like \c NSArray<NSView *> missing the 1533 // \c*. 1534 typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl; 1535 SmallVector<TypeOrClassDecl, 4> typeDecls; 1536 unsigned numTypeDeclsResolved = 0; 1537 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) { 1538 NamedDecl *decl = LookupSingleName(S, identifiers[i], identifierLocs[i], 1539 LookupOrdinaryName); 1540 if (!decl) { 1541 typeDecls.push_back(TypeOrClassDecl()); 1542 continue; 1543 } 1544 1545 if (auto typeDecl = dyn_cast<TypeDecl>(decl)) { 1546 typeDecls.push_back(typeDecl); 1547 ++numTypeDeclsResolved; 1548 continue; 1549 } 1550 1551 if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) { 1552 typeDecls.push_back(objcClass); 1553 ++numTypeDeclsResolved; 1554 continue; 1555 } 1556 1557 typeDecls.push_back(TypeOrClassDecl()); 1558 } 1559 1560 AttributeFactory attrFactory; 1561 1562 // Local function that forms a reference to the given type or 1563 // Objective-C class declaration. 1564 auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc) 1565 -> TypeResult { 1566 // Form declaration specifiers. They simply refer to the type. 1567 DeclSpec DS(attrFactory); 1568 const char* prevSpec; // unused 1569 unsigned diagID; // unused 1570 QualType type; 1571 if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>()) 1572 type = Context.getTypeDeclType(actualTypeDecl); 1573 else 1574 type = Context.getObjCInterfaceType(typeDecl.get<ObjCInterfaceDecl *>()); 1575 TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc); 1576 ParsedType parsedType = CreateParsedType(type, parsedTSInfo); 1577 DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID, 1578 parsedType, Context.getPrintingPolicy()); 1579 // Use the identifier location for the type source range. 1580 DS.SetRangeStart(loc); 1581 DS.SetRangeEnd(loc); 1582 1583 // Form the declarator. 1584 Declarator D(DS, DeclaratorContext::TypeNameContext); 1585 1586 // If we have a typedef of an Objective-C class type that is missing a '*', 1587 // add the '*'. 1588 if (type->getAs<ObjCInterfaceType>()) { 1589 SourceLocation starLoc = getLocForEndOfToken(loc); 1590 D.AddTypeInfo(DeclaratorChunk::getPointer(/*TypeQuals=*/0, starLoc, 1591 SourceLocation(), 1592 SourceLocation(), 1593 SourceLocation(), 1594 SourceLocation(), 1595 SourceLocation()), 1596 starLoc); 1597 1598 // Diagnose the missing '*'. 1599 Diag(loc, diag::err_objc_type_arg_missing_star) 1600 << type 1601 << FixItHint::CreateInsertion(starLoc, " *"); 1602 } 1603 1604 // Convert this to a type. 1605 return ActOnTypeName(S, D); 1606 }; 1607 1608 // Local function that updates the declaration specifiers with 1609 // type argument information. 1610 auto resolvedAsTypeDecls = [&] { 1611 // We did not resolve these as protocols. 1612 protocols.clear(); 1613 1614 assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl"); 1615 // Map type declarations to type arguments. 1616 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) { 1617 // Map type reference to a type. 1618 TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]); 1619 if (!type.isUsable()) { 1620 typeArgs.clear(); 1621 return; 1622 } 1623 1624 typeArgs.push_back(type.get()); 1625 } 1626 1627 typeArgsLAngleLoc = lAngleLoc; 1628 typeArgsRAngleLoc = rAngleLoc; 1629 }; 1630 1631 // If all of the identifiers can be resolved as type names or 1632 // Objective-C class names, we have type arguments. 1633 if (numTypeDeclsResolved == identifiers.size()) 1634 return resolvedAsTypeDecls(); 1635 1636 // Error recovery: some names weren't found, or we have a mix of 1637 // type and protocol names. Go resolve all of the unresolved names 1638 // and complain if we can't find a consistent answer. 1639 LookupNameKind lookupKind = LookupAnyName; 1640 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) { 1641 // If we already have a protocol or type. Check whether it is the 1642 // right thing. 1643 if (protocols[i] || typeDecls[i]) { 1644 // If we haven't figured out whether we want types or protocols 1645 // yet, try to figure it out from this name. 1646 if (lookupKind == LookupAnyName) { 1647 // If this name refers to both a protocol and a type (e.g., \c 1648 // NSObject), don't conclude anything yet. 1649 if (protocols[i] && typeDecls[i]) 1650 continue; 1651 1652 // Otherwise, let this name decide whether we'll be correcting 1653 // toward types or protocols. 1654 lookupKind = protocols[i] ? LookupObjCProtocolName 1655 : LookupOrdinaryName; 1656 continue; 1657 } 1658 1659 // If we want protocols and we have a protocol, there's nothing 1660 // more to do. 1661 if (lookupKind == LookupObjCProtocolName && protocols[i]) 1662 continue; 1663 1664 // If we want types and we have a type declaration, there's 1665 // nothing more to do. 1666 if (lookupKind == LookupOrdinaryName && typeDecls[i]) 1667 continue; 1668 1669 // We have a conflict: some names refer to protocols and others 1670 // refer to types. 1671 DiagnoseTypeArgsAndProtocols(identifiers[0], identifierLocs[0], 1672 identifiers[i], identifierLocs[i], 1673 protocols[i] != nullptr); 1674 1675 protocols.clear(); 1676 typeArgs.clear(); 1677 return; 1678 } 1679 1680 // Perform typo correction on the name. 1681 ObjCTypeArgOrProtocolValidatorCCC CCC(Context, lookupKind); 1682 TypoCorrection corrected = 1683 CorrectTypo(DeclarationNameInfo(identifiers[i], identifierLocs[i]), 1684 lookupKind, S, nullptr, CCC, CTK_ErrorRecovery); 1685 if (corrected) { 1686 // Did we find a protocol? 1687 if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) { 1688 diagnoseTypo(corrected, 1689 PDiag(diag::err_undeclared_protocol_suggest) 1690 << identifiers[i]); 1691 lookupKind = LookupObjCProtocolName; 1692 protocols[i] = proto; 1693 ++numProtocolsResolved; 1694 continue; 1695 } 1696 1697 // Did we find a type? 1698 if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) { 1699 diagnoseTypo(corrected, 1700 PDiag(diag::err_unknown_typename_suggest) 1701 << identifiers[i]); 1702 lookupKind = LookupOrdinaryName; 1703 typeDecls[i] = typeDecl; 1704 ++numTypeDeclsResolved; 1705 continue; 1706 } 1707 1708 // Did we find an Objective-C class? 1709 if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) { 1710 diagnoseTypo(corrected, 1711 PDiag(diag::err_unknown_type_or_class_name_suggest) 1712 << identifiers[i] << true); 1713 lookupKind = LookupOrdinaryName; 1714 typeDecls[i] = objcClass; 1715 ++numTypeDeclsResolved; 1716 continue; 1717 } 1718 } 1719 1720 // We couldn't find anything. 1721 Diag(identifierLocs[i], 1722 (lookupKind == LookupAnyName ? diag::err_objc_type_arg_missing 1723 : lookupKind == LookupObjCProtocolName ? diag::err_undeclared_protocol 1724 : diag::err_unknown_typename)) 1725 << identifiers[i]; 1726 protocols.clear(); 1727 typeArgs.clear(); 1728 return; 1729 } 1730 1731 // If all of the names were (corrected to) protocols, these were 1732 // protocol qualifiers. 1733 if (numProtocolsResolved == identifiers.size()) 1734 return resolvedAsProtocols(); 1735 1736 // Otherwise, all of the names were (corrected to) types. 1737 assert(numTypeDeclsResolved == identifiers.size() && "Not all types?"); 1738 return resolvedAsTypeDecls(); 1739 } 1740 1741 /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of 1742 /// a class method in its extension. 1743 /// 1744 void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, 1745 ObjCInterfaceDecl *ID) { 1746 if (!ID) 1747 return; // Possibly due to previous error 1748 1749 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap; 1750 for (auto *MD : ID->methods()) 1751 MethodMap[MD->getSelector()] = MD; 1752 1753 if (MethodMap.empty()) 1754 return; 1755 for (const auto *Method : CAT->methods()) { 1756 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()]; 1757 if (PrevMethod && 1758 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) && 1759 !MatchTwoMethodDeclarations(Method, PrevMethod)) { 1760 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 1761 << Method->getDeclName(); 1762 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 1763 } 1764 } 1765 } 1766 1767 /// ActOnForwardProtocolDeclaration - Handle \@protocol foo; 1768 Sema::DeclGroupPtrTy 1769 Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc, 1770 ArrayRef<IdentifierLocPair> IdentList, 1771 const ParsedAttributesView &attrList) { 1772 SmallVector<Decl *, 8> DeclsInGroup; 1773 for (const IdentifierLocPair &IdentPair : IdentList) { 1774 IdentifierInfo *Ident = IdentPair.first; 1775 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentPair.second, 1776 forRedeclarationInCurContext()); 1777 ObjCProtocolDecl *PDecl 1778 = ObjCProtocolDecl::Create(Context, CurContext, Ident, 1779 IdentPair.second, AtProtocolLoc, 1780 PrevDecl); 1781 1782 PushOnScopeChains(PDecl, TUScope); 1783 CheckObjCDeclScope(PDecl); 1784 1785 ProcessDeclAttributeList(TUScope, PDecl, attrList); 1786 AddPragmaAttributes(TUScope, PDecl); 1787 1788 if (PrevDecl) 1789 mergeDeclAttributes(PDecl, PrevDecl); 1790 1791 DeclsInGroup.push_back(PDecl); 1792 } 1793 1794 return BuildDeclaratorGroup(DeclsInGroup); 1795 } 1796 1797 Decl *Sema::ActOnStartCategoryInterface( 1798 SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, 1799 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, 1800 IdentifierInfo *CategoryName, SourceLocation CategoryLoc, 1801 Decl *const *ProtoRefs, unsigned NumProtoRefs, 1802 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, 1803 const ParsedAttributesView &AttrList) { 1804 ObjCCategoryDecl *CDecl; 1805 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true); 1806 1807 /// Check that class of this category is already completely declared. 1808 1809 if (!IDecl 1810 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl), 1811 diag::err_category_forward_interface, 1812 CategoryName == nullptr)) { 1813 // Create an invalid ObjCCategoryDecl to serve as context for 1814 // the enclosing method declarations. We mark the decl invalid 1815 // to make it clear that this isn't a valid AST. 1816 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc, 1817 ClassLoc, CategoryLoc, CategoryName, 1818 IDecl, typeParamList); 1819 CDecl->setInvalidDecl(); 1820 CurContext->addDecl(CDecl); 1821 1822 if (!IDecl) 1823 Diag(ClassLoc, diag::err_undef_interface) << ClassName; 1824 return ActOnObjCContainerStartDefinition(CDecl); 1825 } 1826 1827 if (!CategoryName && IDecl->getImplementation()) { 1828 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName; 1829 Diag(IDecl->getImplementation()->getLocation(), 1830 diag::note_implementation_declared); 1831 } 1832 1833 if (CategoryName) { 1834 /// Check for duplicate interface declaration for this category 1835 if (ObjCCategoryDecl *Previous 1836 = IDecl->FindCategoryDeclaration(CategoryName)) { 1837 // Class extensions can be declared multiple times, categories cannot. 1838 Diag(CategoryLoc, diag::warn_dup_category_def) 1839 << ClassName << CategoryName; 1840 Diag(Previous->getLocation(), diag::note_previous_definition); 1841 } 1842 } 1843 1844 // If we have a type parameter list, check it. 1845 if (typeParamList) { 1846 if (auto prevTypeParamList = IDecl->getTypeParamList()) { 1847 if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList, 1848 CategoryName 1849 ? TypeParamListContext::Category 1850 : TypeParamListContext::Extension)) 1851 typeParamList = nullptr; 1852 } else { 1853 Diag(typeParamList->getLAngleLoc(), 1854 diag::err_objc_parameterized_category_nonclass) 1855 << (CategoryName != nullptr) 1856 << ClassName 1857 << typeParamList->getSourceRange(); 1858 1859 typeParamList = nullptr; 1860 } 1861 } 1862 1863 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc, 1864 ClassLoc, CategoryLoc, CategoryName, IDecl, 1865 typeParamList); 1866 // FIXME: PushOnScopeChains? 1867 CurContext->addDecl(CDecl); 1868 1869 // Process the attributes before looking at protocols to ensure that the 1870 // availability attribute is attached to the category to provide availability 1871 // checking for protocol uses. 1872 ProcessDeclAttributeList(TUScope, CDecl, AttrList); 1873 AddPragmaAttributes(TUScope, CDecl); 1874 1875 if (NumProtoRefs) { 1876 diagnoseUseOfProtocols(*this, CDecl, (ObjCProtocolDecl*const*)ProtoRefs, 1877 NumProtoRefs, ProtoLocs); 1878 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs, 1879 ProtoLocs, Context); 1880 // Protocols in the class extension belong to the class. 1881 if (CDecl->IsClassExtension()) 1882 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs, 1883 NumProtoRefs, Context); 1884 } 1885 1886 CheckObjCDeclScope(CDecl); 1887 return ActOnObjCContainerStartDefinition(CDecl); 1888 } 1889 1890 /// ActOnStartCategoryImplementation - Perform semantic checks on the 1891 /// category implementation declaration and build an ObjCCategoryImplDecl 1892 /// object. 1893 Decl *Sema::ActOnStartCategoryImplementation( 1894 SourceLocation AtCatImplLoc, 1895 IdentifierInfo *ClassName, SourceLocation ClassLoc, 1896 IdentifierInfo *CatName, SourceLocation CatLoc, 1897 const ParsedAttributesView &Attrs) { 1898 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true); 1899 ObjCCategoryDecl *CatIDecl = nullptr; 1900 if (IDecl && IDecl->hasDefinition()) { 1901 CatIDecl = IDecl->FindCategoryDeclaration(CatName); 1902 if (!CatIDecl) { 1903 // Category @implementation with no corresponding @interface. 1904 // Create and install one. 1905 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc, 1906 ClassLoc, CatLoc, 1907 CatName, IDecl, 1908 /*typeParamList=*/nullptr); 1909 CatIDecl->setImplicit(); 1910 } 1911 } 1912 1913 ObjCCategoryImplDecl *CDecl = 1914 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl, 1915 ClassLoc, AtCatImplLoc, CatLoc); 1916 /// Check that class of this category is already completely declared. 1917 if (!IDecl) { 1918 Diag(ClassLoc, diag::err_undef_interface) << ClassName; 1919 CDecl->setInvalidDecl(); 1920 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl), 1921 diag::err_undef_interface)) { 1922 CDecl->setInvalidDecl(); 1923 } 1924 1925 ProcessDeclAttributeList(TUScope, CDecl, Attrs); 1926 AddPragmaAttributes(TUScope, CDecl); 1927 1928 // FIXME: PushOnScopeChains? 1929 CurContext->addDecl(CDecl); 1930 1931 // If the interface has the objc_runtime_visible attribute, we 1932 // cannot implement a category for it. 1933 if (IDecl && IDecl->hasAttr<ObjCRuntimeVisibleAttr>()) { 1934 Diag(ClassLoc, diag::err_objc_runtime_visible_category) 1935 << IDecl->getDeclName(); 1936 } 1937 1938 /// Check that CatName, category name, is not used in another implementation. 1939 if (CatIDecl) { 1940 if (CatIDecl->getImplementation()) { 1941 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName 1942 << CatName; 1943 Diag(CatIDecl->getImplementation()->getLocation(), 1944 diag::note_previous_definition); 1945 CDecl->setInvalidDecl(); 1946 } else { 1947 CatIDecl->setImplementation(CDecl); 1948 // Warn on implementating category of deprecated class under 1949 // -Wdeprecated-implementations flag. 1950 DiagnoseObjCImplementedDeprecations(*this, CatIDecl, 1951 CDecl->getLocation()); 1952 } 1953 } 1954 1955 CheckObjCDeclScope(CDecl); 1956 return ActOnObjCContainerStartDefinition(CDecl); 1957 } 1958 1959 Decl *Sema::ActOnStartClassImplementation( 1960 SourceLocation AtClassImplLoc, 1961 IdentifierInfo *ClassName, SourceLocation ClassLoc, 1962 IdentifierInfo *SuperClassname, 1963 SourceLocation SuperClassLoc, 1964 const ParsedAttributesView &Attrs) { 1965 ObjCInterfaceDecl *IDecl = nullptr; 1966 // Check for another declaration kind with the same name. 1967 NamedDecl *PrevDecl 1968 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName, 1969 forRedeclarationInCurContext()); 1970 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 1971 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName; 1972 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 1973 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) { 1974 // FIXME: This will produce an error if the definition of the interface has 1975 // been imported from a module but is not visible. 1976 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl), 1977 diag::warn_undef_interface); 1978 } else { 1979 // We did not find anything with the name ClassName; try to correct for 1980 // typos in the class name. 1981 ObjCInterfaceValidatorCCC CCC{}; 1982 TypoCorrection Corrected = 1983 CorrectTypo(DeclarationNameInfo(ClassName, ClassLoc), 1984 LookupOrdinaryName, TUScope, nullptr, CCC, CTK_NonError); 1985 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) { 1986 // Suggest the (potentially) correct interface name. Don't provide a 1987 // code-modification hint or use the typo name for recovery, because 1988 // this is just a warning. The program may actually be correct. 1989 diagnoseTypo(Corrected, 1990 PDiag(diag::warn_undef_interface_suggest) << ClassName, 1991 /*ErrorRecovery*/false); 1992 } else { 1993 Diag(ClassLoc, diag::warn_undef_interface) << ClassName; 1994 } 1995 } 1996 1997 // Check that super class name is valid class name 1998 ObjCInterfaceDecl *SDecl = nullptr; 1999 if (SuperClassname) { 2000 // Check if a different kind of symbol declared in this scope. 2001 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc, 2002 LookupOrdinaryName); 2003 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 2004 Diag(SuperClassLoc, diag::err_redefinition_different_kind) 2005 << SuperClassname; 2006 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2007 } else { 2008 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 2009 if (SDecl && !SDecl->hasDefinition()) 2010 SDecl = nullptr; 2011 if (!SDecl) 2012 Diag(SuperClassLoc, diag::err_undef_superclass) 2013 << SuperClassname << ClassName; 2014 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) { 2015 // This implementation and its interface do not have the same 2016 // super class. 2017 Diag(SuperClassLoc, diag::err_conflicting_super_class) 2018 << SDecl->getDeclName(); 2019 Diag(SDecl->getLocation(), diag::note_previous_definition); 2020 } 2021 } 2022 } 2023 2024 if (!IDecl) { 2025 // Legacy case of @implementation with no corresponding @interface. 2026 // Build, chain & install the interface decl into the identifier. 2027 2028 // FIXME: Do we support attributes on the @implementation? If so we should 2029 // copy them over. 2030 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc, 2031 ClassName, /*typeParamList=*/nullptr, 2032 /*PrevDecl=*/nullptr, ClassLoc, 2033 true); 2034 AddPragmaAttributes(TUScope, IDecl); 2035 IDecl->startDefinition(); 2036 if (SDecl) { 2037 IDecl->setSuperClass(Context.getTrivialTypeSourceInfo( 2038 Context.getObjCInterfaceType(SDecl), 2039 SuperClassLoc)); 2040 IDecl->setEndOfDefinitionLoc(SuperClassLoc); 2041 } else { 2042 IDecl->setEndOfDefinitionLoc(ClassLoc); 2043 } 2044 2045 PushOnScopeChains(IDecl, TUScope); 2046 } else { 2047 // Mark the interface as being completed, even if it was just as 2048 // @class ....; 2049 // declaration; the user cannot reopen it. 2050 if (!IDecl->hasDefinition()) 2051 IDecl->startDefinition(); 2052 } 2053 2054 ObjCImplementationDecl* IMPDecl = 2055 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl, 2056 ClassLoc, AtClassImplLoc, SuperClassLoc); 2057 2058 ProcessDeclAttributeList(TUScope, IMPDecl, Attrs); 2059 AddPragmaAttributes(TUScope, IMPDecl); 2060 2061 if (CheckObjCDeclScope(IMPDecl)) 2062 return ActOnObjCContainerStartDefinition(IMPDecl); 2063 2064 // Check that there is no duplicate implementation of this class. 2065 if (IDecl->getImplementation()) { 2066 // FIXME: Don't leak everything! 2067 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName; 2068 Diag(IDecl->getImplementation()->getLocation(), 2069 diag::note_previous_definition); 2070 IMPDecl->setInvalidDecl(); 2071 } else { // add it to the list. 2072 IDecl->setImplementation(IMPDecl); 2073 PushOnScopeChains(IMPDecl, TUScope); 2074 // Warn on implementating deprecated class under 2075 // -Wdeprecated-implementations flag. 2076 DiagnoseObjCImplementedDeprecations(*this, IDecl, IMPDecl->getLocation()); 2077 } 2078 2079 // If the superclass has the objc_runtime_visible attribute, we 2080 // cannot implement a subclass of it. 2081 if (IDecl->getSuperClass() && 2082 IDecl->getSuperClass()->hasAttr<ObjCRuntimeVisibleAttr>()) { 2083 Diag(ClassLoc, diag::err_objc_runtime_visible_subclass) 2084 << IDecl->getDeclName() 2085 << IDecl->getSuperClass()->getDeclName(); 2086 } 2087 2088 return ActOnObjCContainerStartDefinition(IMPDecl); 2089 } 2090 2091 Sema::DeclGroupPtrTy 2092 Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) { 2093 SmallVector<Decl *, 64> DeclsInGroup; 2094 DeclsInGroup.reserve(Decls.size() + 1); 2095 2096 for (unsigned i = 0, e = Decls.size(); i != e; ++i) { 2097 Decl *Dcl = Decls[i]; 2098 if (!Dcl) 2099 continue; 2100 if (Dcl->getDeclContext()->isFileContext()) 2101 Dcl->setTopLevelDeclInObjCContainer(); 2102 DeclsInGroup.push_back(Dcl); 2103 } 2104 2105 DeclsInGroup.push_back(ObjCImpDecl); 2106 2107 return BuildDeclaratorGroup(DeclsInGroup); 2108 } 2109 2110 void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, 2111 ObjCIvarDecl **ivars, unsigned numIvars, 2112 SourceLocation RBrace) { 2113 assert(ImpDecl && "missing implementation decl"); 2114 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface(); 2115 if (!IDecl) 2116 return; 2117 /// Check case of non-existing \@interface decl. 2118 /// (legacy objective-c \@implementation decl without an \@interface decl). 2119 /// Add implementations's ivar to the synthesize class's ivar list. 2120 if (IDecl->isImplicitInterfaceDecl()) { 2121 IDecl->setEndOfDefinitionLoc(RBrace); 2122 // Add ivar's to class's DeclContext. 2123 for (unsigned i = 0, e = numIvars; i != e; ++i) { 2124 ivars[i]->setLexicalDeclContext(ImpDecl); 2125 // In a 'fragile' runtime the ivar was added to the implicit 2126 // ObjCInterfaceDecl while in a 'non-fragile' runtime the ivar is 2127 // only in the ObjCImplementationDecl. In the non-fragile case the ivar 2128 // therefore also needs to be propagated to the ObjCInterfaceDecl. 2129 if (!LangOpts.ObjCRuntime.isFragile()) 2130 IDecl->makeDeclVisibleInContext(ivars[i]); 2131 ImpDecl->addDecl(ivars[i]); 2132 } 2133 2134 return; 2135 } 2136 // If implementation has empty ivar list, just return. 2137 if (numIvars == 0) 2138 return; 2139 2140 assert(ivars && "missing @implementation ivars"); 2141 if (LangOpts.ObjCRuntime.isNonFragile()) { 2142 if (ImpDecl->getSuperClass()) 2143 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use); 2144 for (unsigned i = 0; i < numIvars; i++) { 2145 ObjCIvarDecl* ImplIvar = ivars[i]; 2146 if (const ObjCIvarDecl *ClsIvar = 2147 IDecl->getIvarDecl(ImplIvar->getIdentifier())) { 2148 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration); 2149 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 2150 continue; 2151 } 2152 // Check class extensions (unnamed categories) for duplicate ivars. 2153 for (const auto *CDecl : IDecl->visible_extensions()) { 2154 if (const ObjCIvarDecl *ClsExtIvar = 2155 CDecl->getIvarDecl(ImplIvar->getIdentifier())) { 2156 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration); 2157 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 2158 continue; 2159 } 2160 } 2161 // Instance ivar to Implementation's DeclContext. 2162 ImplIvar->setLexicalDeclContext(ImpDecl); 2163 IDecl->makeDeclVisibleInContext(ImplIvar); 2164 ImpDecl->addDecl(ImplIvar); 2165 } 2166 return; 2167 } 2168 // Check interface's Ivar list against those in the implementation. 2169 // names and types must match. 2170 // 2171 unsigned j = 0; 2172 ObjCInterfaceDecl::ivar_iterator 2173 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end(); 2174 for (; numIvars > 0 && IVI != IVE; ++IVI) { 2175 ObjCIvarDecl* ImplIvar = ivars[j++]; 2176 ObjCIvarDecl* ClsIvar = *IVI; 2177 assert (ImplIvar && "missing implementation ivar"); 2178 assert (ClsIvar && "missing class ivar"); 2179 2180 // First, make sure the types match. 2181 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) { 2182 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type) 2183 << ImplIvar->getIdentifier() 2184 << ImplIvar->getType() << ClsIvar->getType(); 2185 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 2186 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() && 2187 ImplIvar->getBitWidthValue(Context) != 2188 ClsIvar->getBitWidthValue(Context)) { 2189 Diag(ImplIvar->getBitWidth()->getBeginLoc(), 2190 diag::err_conflicting_ivar_bitwidth) 2191 << ImplIvar->getIdentifier(); 2192 Diag(ClsIvar->getBitWidth()->getBeginLoc(), 2193 diag::note_previous_definition); 2194 } 2195 // Make sure the names are identical. 2196 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) { 2197 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name) 2198 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier(); 2199 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 2200 } 2201 --numIvars; 2202 } 2203 2204 if (numIvars > 0) 2205 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count); 2206 else if (IVI != IVE) 2207 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count); 2208 } 2209 2210 static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc, 2211 ObjCMethodDecl *method, 2212 bool &IncompleteImpl, 2213 unsigned DiagID, 2214 NamedDecl *NeededFor = nullptr) { 2215 // No point warning no definition of method which is 'unavailable'. 2216 if (method->getAvailability() == AR_Unavailable) 2217 return; 2218 2219 // FIXME: For now ignore 'IncompleteImpl'. 2220 // Previously we grouped all unimplemented methods under a single 2221 // warning, but some users strongly voiced that they would prefer 2222 // separate warnings. We will give that approach a try, as that 2223 // matches what we do with protocols. 2224 { 2225 const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID); 2226 B << method; 2227 if (NeededFor) 2228 B << NeededFor; 2229 } 2230 2231 // Issue a note to the original declaration. 2232 SourceLocation MethodLoc = method->getBeginLoc(); 2233 if (MethodLoc.isValid()) 2234 S.Diag(MethodLoc, diag::note_method_declared_at) << method; 2235 } 2236 2237 /// Determines if type B can be substituted for type A. Returns true if we can 2238 /// guarantee that anything that the user will do to an object of type A can 2239 /// also be done to an object of type B. This is trivially true if the two 2240 /// types are the same, or if B is a subclass of A. It becomes more complex 2241 /// in cases where protocols are involved. 2242 /// 2243 /// Object types in Objective-C describe the minimum requirements for an 2244 /// object, rather than providing a complete description of a type. For 2245 /// example, if A is a subclass of B, then B* may refer to an instance of A. 2246 /// The principle of substitutability means that we may use an instance of A 2247 /// anywhere that we may use an instance of B - it will implement all of the 2248 /// ivars of B and all of the methods of B. 2249 /// 2250 /// This substitutability is important when type checking methods, because 2251 /// the implementation may have stricter type definitions than the interface. 2252 /// The interface specifies minimum requirements, but the implementation may 2253 /// have more accurate ones. For example, a method may privately accept 2254 /// instances of B, but only publish that it accepts instances of A. Any 2255 /// object passed to it will be type checked against B, and so will implicitly 2256 /// by a valid A*. Similarly, a method may return a subclass of the class that 2257 /// it is declared as returning. 2258 /// 2259 /// This is most important when considering subclassing. A method in a 2260 /// subclass must accept any object as an argument that its superclass's 2261 /// implementation accepts. It may, however, accept a more general type 2262 /// without breaking substitutability (i.e. you can still use the subclass 2263 /// anywhere that you can use the superclass, but not vice versa). The 2264 /// converse requirement applies to return types: the return type for a 2265 /// subclass method must be a valid object of the kind that the superclass 2266 /// advertises, but it may be specified more accurately. This avoids the need 2267 /// for explicit down-casting by callers. 2268 /// 2269 /// Note: This is a stricter requirement than for assignment. 2270 static bool isObjCTypeSubstitutable(ASTContext &Context, 2271 const ObjCObjectPointerType *A, 2272 const ObjCObjectPointerType *B, 2273 bool rejectId) { 2274 // Reject a protocol-unqualified id. 2275 if (rejectId && B->isObjCIdType()) return false; 2276 2277 // If B is a qualified id, then A must also be a qualified id and it must 2278 // implement all of the protocols in B. It may not be a qualified class. 2279 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a 2280 // stricter definition so it is not substitutable for id<A>. 2281 if (B->isObjCQualifiedIdType()) { 2282 return A->isObjCQualifiedIdType() && 2283 Context.ObjCQualifiedIdTypesAreCompatible(A, B, false); 2284 } 2285 2286 /* 2287 // id is a special type that bypasses type checking completely. We want a 2288 // warning when it is used in one place but not another. 2289 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false; 2290 2291 2292 // If B is a qualified id, then A must also be a qualified id (which it isn't 2293 // if we've got this far) 2294 if (B->isObjCQualifiedIdType()) return false; 2295 */ 2296 2297 // Now we know that A and B are (potentially-qualified) class types. The 2298 // normal rules for assignment apply. 2299 return Context.canAssignObjCInterfaces(A, B); 2300 } 2301 2302 static SourceRange getTypeRange(TypeSourceInfo *TSI) { 2303 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange()); 2304 } 2305 2306 /// Determine whether two set of Objective-C declaration qualifiers conflict. 2307 static bool objcModifiersConflict(Decl::ObjCDeclQualifier x, 2308 Decl::ObjCDeclQualifier y) { 2309 return (x & ~Decl::OBJC_TQ_CSNullability) != 2310 (y & ~Decl::OBJC_TQ_CSNullability); 2311 } 2312 2313 static bool CheckMethodOverrideReturn(Sema &S, 2314 ObjCMethodDecl *MethodImpl, 2315 ObjCMethodDecl *MethodDecl, 2316 bool IsProtocolMethodDecl, 2317 bool IsOverridingMode, 2318 bool Warn) { 2319 if (IsProtocolMethodDecl && 2320 objcModifiersConflict(MethodDecl->getObjCDeclQualifier(), 2321 MethodImpl->getObjCDeclQualifier())) { 2322 if (Warn) { 2323 S.Diag(MethodImpl->getLocation(), 2324 (IsOverridingMode 2325 ? diag::warn_conflicting_overriding_ret_type_modifiers 2326 : diag::warn_conflicting_ret_type_modifiers)) 2327 << MethodImpl->getDeclName() 2328 << MethodImpl->getReturnTypeSourceRange(); 2329 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration) 2330 << MethodDecl->getReturnTypeSourceRange(); 2331 } 2332 else 2333 return false; 2334 } 2335 if (Warn && IsOverridingMode && 2336 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) && 2337 !S.Context.hasSameNullabilityTypeQualifier(MethodImpl->getReturnType(), 2338 MethodDecl->getReturnType(), 2339 false)) { 2340 auto nullabilityMethodImpl = 2341 *MethodImpl->getReturnType()->getNullability(S.Context); 2342 auto nullabilityMethodDecl = 2343 *MethodDecl->getReturnType()->getNullability(S.Context); 2344 S.Diag(MethodImpl->getLocation(), 2345 diag::warn_conflicting_nullability_attr_overriding_ret_types) 2346 << DiagNullabilityKind( 2347 nullabilityMethodImpl, 2348 ((MethodImpl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2349 != 0)) 2350 << DiagNullabilityKind( 2351 nullabilityMethodDecl, 2352 ((MethodDecl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2353 != 0)); 2354 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration); 2355 } 2356 2357 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(), 2358 MethodDecl->getReturnType())) 2359 return true; 2360 if (!Warn) 2361 return false; 2362 2363 unsigned DiagID = 2364 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types 2365 : diag::warn_conflicting_ret_types; 2366 2367 // Mismatches between ObjC pointers go into a different warning 2368 // category, and sometimes they're even completely explicitly allowed. 2369 if (const ObjCObjectPointerType *ImplPtrTy = 2370 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) { 2371 if (const ObjCObjectPointerType *IfacePtrTy = 2372 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) { 2373 // Allow non-matching return types as long as they don't violate 2374 // the principle of substitutability. Specifically, we permit 2375 // return types that are subclasses of the declared return type, 2376 // or that are more-qualified versions of the declared type. 2377 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false)) 2378 return false; 2379 2380 DiagID = 2381 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types 2382 : diag::warn_non_covariant_ret_types; 2383 } 2384 } 2385 2386 S.Diag(MethodImpl->getLocation(), DiagID) 2387 << MethodImpl->getDeclName() << MethodDecl->getReturnType() 2388 << MethodImpl->getReturnType() 2389 << MethodImpl->getReturnTypeSourceRange(); 2390 S.Diag(MethodDecl->getLocation(), IsOverridingMode 2391 ? diag::note_previous_declaration 2392 : diag::note_previous_definition) 2393 << MethodDecl->getReturnTypeSourceRange(); 2394 return false; 2395 } 2396 2397 static bool CheckMethodOverrideParam(Sema &S, 2398 ObjCMethodDecl *MethodImpl, 2399 ObjCMethodDecl *MethodDecl, 2400 ParmVarDecl *ImplVar, 2401 ParmVarDecl *IfaceVar, 2402 bool IsProtocolMethodDecl, 2403 bool IsOverridingMode, 2404 bool Warn) { 2405 if (IsProtocolMethodDecl && 2406 objcModifiersConflict(ImplVar->getObjCDeclQualifier(), 2407 IfaceVar->getObjCDeclQualifier())) { 2408 if (Warn) { 2409 if (IsOverridingMode) 2410 S.Diag(ImplVar->getLocation(), 2411 diag::warn_conflicting_overriding_param_modifiers) 2412 << getTypeRange(ImplVar->getTypeSourceInfo()) 2413 << MethodImpl->getDeclName(); 2414 else S.Diag(ImplVar->getLocation(), 2415 diag::warn_conflicting_param_modifiers) 2416 << getTypeRange(ImplVar->getTypeSourceInfo()) 2417 << MethodImpl->getDeclName(); 2418 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration) 2419 << getTypeRange(IfaceVar->getTypeSourceInfo()); 2420 } 2421 else 2422 return false; 2423 } 2424 2425 QualType ImplTy = ImplVar->getType(); 2426 QualType IfaceTy = IfaceVar->getType(); 2427 if (Warn && IsOverridingMode && 2428 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) && 2429 !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) { 2430 S.Diag(ImplVar->getLocation(), 2431 diag::warn_conflicting_nullability_attr_overriding_param_types) 2432 << DiagNullabilityKind( 2433 *ImplTy->getNullability(S.Context), 2434 ((ImplVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2435 != 0)) 2436 << DiagNullabilityKind( 2437 *IfaceTy->getNullability(S.Context), 2438 ((IfaceVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2439 != 0)); 2440 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration); 2441 } 2442 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy)) 2443 return true; 2444 2445 if (!Warn) 2446 return false; 2447 unsigned DiagID = 2448 IsOverridingMode ? diag::warn_conflicting_overriding_param_types 2449 : diag::warn_conflicting_param_types; 2450 2451 // Mismatches between ObjC pointers go into a different warning 2452 // category, and sometimes they're even completely explicitly allowed.. 2453 if (const ObjCObjectPointerType *ImplPtrTy = 2454 ImplTy->getAs<ObjCObjectPointerType>()) { 2455 if (const ObjCObjectPointerType *IfacePtrTy = 2456 IfaceTy->getAs<ObjCObjectPointerType>()) { 2457 // Allow non-matching argument types as long as they don't 2458 // violate the principle of substitutability. Specifically, the 2459 // implementation must accept any objects that the superclass 2460 // accepts, however it may also accept others. 2461 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true)) 2462 return false; 2463 2464 DiagID = 2465 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types 2466 : diag::warn_non_contravariant_param_types; 2467 } 2468 } 2469 2470 S.Diag(ImplVar->getLocation(), DiagID) 2471 << getTypeRange(ImplVar->getTypeSourceInfo()) 2472 << MethodImpl->getDeclName() << IfaceTy << ImplTy; 2473 S.Diag(IfaceVar->getLocation(), 2474 (IsOverridingMode ? diag::note_previous_declaration 2475 : diag::note_previous_definition)) 2476 << getTypeRange(IfaceVar->getTypeSourceInfo()); 2477 return false; 2478 } 2479 2480 /// In ARC, check whether the conventional meanings of the two methods 2481 /// match. If they don't, it's a hard error. 2482 static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl, 2483 ObjCMethodDecl *decl) { 2484 ObjCMethodFamily implFamily = impl->getMethodFamily(); 2485 ObjCMethodFamily declFamily = decl->getMethodFamily(); 2486 if (implFamily == declFamily) return false; 2487 2488 // Since conventions are sorted by selector, the only possibility is 2489 // that the types differ enough to cause one selector or the other 2490 // to fall out of the family. 2491 assert(implFamily == OMF_None || declFamily == OMF_None); 2492 2493 // No further diagnostics required on invalid declarations. 2494 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true; 2495 2496 const ObjCMethodDecl *unmatched = impl; 2497 ObjCMethodFamily family = declFamily; 2498 unsigned errorID = diag::err_arc_lost_method_convention; 2499 unsigned noteID = diag::note_arc_lost_method_convention; 2500 if (declFamily == OMF_None) { 2501 unmatched = decl; 2502 family = implFamily; 2503 errorID = diag::err_arc_gained_method_convention; 2504 noteID = diag::note_arc_gained_method_convention; 2505 } 2506 2507 // Indexes into a %select clause in the diagnostic. 2508 enum FamilySelector { 2509 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new 2510 }; 2511 FamilySelector familySelector = FamilySelector(); 2512 2513 switch (family) { 2514 case OMF_None: llvm_unreachable("logic error, no method convention"); 2515 case OMF_retain: 2516 case OMF_release: 2517 case OMF_autorelease: 2518 case OMF_dealloc: 2519 case OMF_finalize: 2520 case OMF_retainCount: 2521 case OMF_self: 2522 case OMF_initialize: 2523 case OMF_performSelector: 2524 // Mismatches for these methods don't change ownership 2525 // conventions, so we don't care. 2526 return false; 2527 2528 case OMF_init: familySelector = F_init; break; 2529 case OMF_alloc: familySelector = F_alloc; break; 2530 case OMF_copy: familySelector = F_copy; break; 2531 case OMF_mutableCopy: familySelector = F_mutableCopy; break; 2532 case OMF_new: familySelector = F_new; break; 2533 } 2534 2535 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn }; 2536 ReasonSelector reasonSelector; 2537 2538 // The only reason these methods don't fall within their families is 2539 // due to unusual result types. 2540 if (unmatched->getReturnType()->isObjCObjectPointerType()) { 2541 reasonSelector = R_UnrelatedReturn; 2542 } else { 2543 reasonSelector = R_NonObjectReturn; 2544 } 2545 2546 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector); 2547 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector); 2548 2549 return true; 2550 } 2551 2552 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl, 2553 ObjCMethodDecl *MethodDecl, 2554 bool IsProtocolMethodDecl) { 2555 if (getLangOpts().ObjCAutoRefCount && 2556 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl)) 2557 return; 2558 2559 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, 2560 IsProtocolMethodDecl, false, 2561 true); 2562 2563 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(), 2564 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(), 2565 EF = MethodDecl->param_end(); 2566 IM != EM && IF != EF; ++IM, ++IF) { 2567 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF, 2568 IsProtocolMethodDecl, false, true); 2569 } 2570 2571 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) { 2572 Diag(ImpMethodDecl->getLocation(), 2573 diag::warn_conflicting_variadic); 2574 Diag(MethodDecl->getLocation(), diag::note_previous_declaration); 2575 } 2576 } 2577 2578 void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method, 2579 ObjCMethodDecl *Overridden, 2580 bool IsProtocolMethodDecl) { 2581 2582 CheckMethodOverrideReturn(*this, Method, Overridden, 2583 IsProtocolMethodDecl, true, 2584 true); 2585 2586 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(), 2587 IF = Overridden->param_begin(), EM = Method->param_end(), 2588 EF = Overridden->param_end(); 2589 IM != EM && IF != EF; ++IM, ++IF) { 2590 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF, 2591 IsProtocolMethodDecl, true, true); 2592 } 2593 2594 if (Method->isVariadic() != Overridden->isVariadic()) { 2595 Diag(Method->getLocation(), 2596 diag::warn_conflicting_overriding_variadic); 2597 Diag(Overridden->getLocation(), diag::note_previous_declaration); 2598 } 2599 } 2600 2601 /// WarnExactTypedMethods - This routine issues a warning if method 2602 /// implementation declaration matches exactly that of its declaration. 2603 void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl, 2604 ObjCMethodDecl *MethodDecl, 2605 bool IsProtocolMethodDecl) { 2606 // don't issue warning when protocol method is optional because primary 2607 // class is not required to implement it and it is safe for protocol 2608 // to implement it. 2609 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional) 2610 return; 2611 // don't issue warning when primary class's method is 2612 // depecated/unavailable. 2613 if (MethodDecl->hasAttr<UnavailableAttr>() || 2614 MethodDecl->hasAttr<DeprecatedAttr>()) 2615 return; 2616 2617 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, 2618 IsProtocolMethodDecl, false, false); 2619 if (match) 2620 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(), 2621 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(), 2622 EF = MethodDecl->param_end(); 2623 IM != EM && IF != EF; ++IM, ++IF) { 2624 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, 2625 *IM, *IF, 2626 IsProtocolMethodDecl, false, false); 2627 if (!match) 2628 break; 2629 } 2630 if (match) 2631 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic()); 2632 if (match) 2633 match = !(MethodDecl->isClassMethod() && 2634 MethodDecl->getSelector() == GetNullarySelector("load", Context)); 2635 2636 if (match) { 2637 Diag(ImpMethodDecl->getLocation(), 2638 diag::warn_category_method_impl_match); 2639 Diag(MethodDecl->getLocation(), diag::note_method_declared_at) 2640 << MethodDecl->getDeclName(); 2641 } 2642 } 2643 2644 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely 2645 /// improve the efficiency of selector lookups and type checking by associating 2646 /// with each protocol / interface / category the flattened instance tables. If 2647 /// we used an immutable set to keep the table then it wouldn't add significant 2648 /// memory cost and it would be handy for lookups. 2649 2650 typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet; 2651 typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet; 2652 2653 static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl, 2654 ProtocolNameSet &PNS) { 2655 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) 2656 PNS.insert(PDecl->getIdentifier()); 2657 for (const auto *PI : PDecl->protocols()) 2658 findProtocolsWithExplicitImpls(PI, PNS); 2659 } 2660 2661 /// Recursively populates a set with all conformed protocols in a class 2662 /// hierarchy that have the 'objc_protocol_requires_explicit_implementation' 2663 /// attribute. 2664 static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super, 2665 ProtocolNameSet &PNS) { 2666 if (!Super) 2667 return; 2668 2669 for (const auto *I : Super->all_referenced_protocols()) 2670 findProtocolsWithExplicitImpls(I, PNS); 2671 2672 findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS); 2673 } 2674 2675 /// CheckProtocolMethodDefs - This routine checks unimplemented methods 2676 /// Declared in protocol, and those referenced by it. 2677 static void CheckProtocolMethodDefs(Sema &S, 2678 SourceLocation ImpLoc, 2679 ObjCProtocolDecl *PDecl, 2680 bool& IncompleteImpl, 2681 const Sema::SelectorSet &InsMap, 2682 const Sema::SelectorSet &ClsMap, 2683 ObjCContainerDecl *CDecl, 2684 LazyProtocolNameSet &ProtocolsExplictImpl) { 2685 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl); 2686 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface() 2687 : dyn_cast<ObjCInterfaceDecl>(CDecl); 2688 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null"); 2689 2690 ObjCInterfaceDecl *Super = IDecl->getSuperClass(); 2691 ObjCInterfaceDecl *NSIDecl = nullptr; 2692 2693 // If this protocol is marked 'objc_protocol_requires_explicit_implementation' 2694 // then we should check if any class in the super class hierarchy also 2695 // conforms to this protocol, either directly or via protocol inheritance. 2696 // If so, we can skip checking this protocol completely because we 2697 // know that a parent class already satisfies this protocol. 2698 // 2699 // Note: we could generalize this logic for all protocols, and merely 2700 // add the limit on looking at the super class chain for just 2701 // specially marked protocols. This may be a good optimization. This 2702 // change is restricted to 'objc_protocol_requires_explicit_implementation' 2703 // protocols for now for controlled evaluation. 2704 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) { 2705 if (!ProtocolsExplictImpl) { 2706 ProtocolsExplictImpl.reset(new ProtocolNameSet); 2707 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl); 2708 } 2709 if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) != 2710 ProtocolsExplictImpl->end()) 2711 return; 2712 2713 // If no super class conforms to the protocol, we should not search 2714 // for methods in the super class to implicitly satisfy the protocol. 2715 Super = nullptr; 2716 } 2717 2718 if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) { 2719 // check to see if class implements forwardInvocation method and objects 2720 // of this class are derived from 'NSProxy' so that to forward requests 2721 // from one object to another. 2722 // Under such conditions, which means that every method possible is 2723 // implemented in the class, we should not issue "Method definition not 2724 // found" warnings. 2725 // FIXME: Use a general GetUnarySelector method for this. 2726 IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation"); 2727 Selector fISelector = S.Context.Selectors.getSelector(1, &II); 2728 if (InsMap.count(fISelector)) 2729 // Is IDecl derived from 'NSProxy'? If so, no instance methods 2730 // need be implemented in the implementation. 2731 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy")); 2732 } 2733 2734 // If this is a forward protocol declaration, get its definition. 2735 if (!PDecl->isThisDeclarationADefinition() && 2736 PDecl->getDefinition()) 2737 PDecl = PDecl->getDefinition(); 2738 2739 // If a method lookup fails locally we still need to look and see if 2740 // the method was implemented by a base class or an inherited 2741 // protocol. This lookup is slow, but occurs rarely in correct code 2742 // and otherwise would terminate in a warning. 2743 2744 // check unimplemented instance methods. 2745 if (!NSIDecl) 2746 for (auto *method : PDecl->instance_methods()) { 2747 if (method->getImplementationControl() != ObjCMethodDecl::Optional && 2748 !method->isPropertyAccessor() && 2749 !InsMap.count(method->getSelector()) && 2750 (!Super || !Super->lookupMethod(method->getSelector(), 2751 true /* instance */, 2752 false /* shallowCategory */, 2753 true /* followsSuper */, 2754 nullptr /* category */))) { 2755 // If a method is not implemented in the category implementation but 2756 // has been declared in its primary class, superclass, 2757 // or in one of their protocols, no need to issue the warning. 2758 // This is because method will be implemented in the primary class 2759 // or one of its super class implementation. 2760 2761 // Ugly, but necessary. Method declared in protocol might have 2762 // have been synthesized due to a property declared in the class which 2763 // uses the protocol. 2764 if (ObjCMethodDecl *MethodInClass = 2765 IDecl->lookupMethod(method->getSelector(), 2766 true /* instance */, 2767 true /* shallowCategoryLookup */, 2768 false /* followSuper */)) 2769 if (C || MethodInClass->isPropertyAccessor()) 2770 continue; 2771 unsigned DIAG = diag::warn_unimplemented_protocol_method; 2772 if (!S.Diags.isIgnored(DIAG, ImpLoc)) { 2773 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, 2774 PDecl); 2775 } 2776 } 2777 } 2778 // check unimplemented class methods 2779 for (auto *method : PDecl->class_methods()) { 2780 if (method->getImplementationControl() != ObjCMethodDecl::Optional && 2781 !ClsMap.count(method->getSelector()) && 2782 (!Super || !Super->lookupMethod(method->getSelector(), 2783 false /* class method */, 2784 false /* shallowCategoryLookup */, 2785 true /* followSuper */, 2786 nullptr /* category */))) { 2787 // See above comment for instance method lookups. 2788 if (C && IDecl->lookupMethod(method->getSelector(), 2789 false /* class */, 2790 true /* shallowCategoryLookup */, 2791 false /* followSuper */)) 2792 continue; 2793 2794 unsigned DIAG = diag::warn_unimplemented_protocol_method; 2795 if (!S.Diags.isIgnored(DIAG, ImpLoc)) { 2796 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl); 2797 } 2798 } 2799 } 2800 // Check on this protocols's referenced protocols, recursively. 2801 for (auto *PI : PDecl->protocols()) 2802 CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap, 2803 CDecl, ProtocolsExplictImpl); 2804 } 2805 2806 /// MatchAllMethodDeclarations - Check methods declared in interface 2807 /// or protocol against those declared in their implementations. 2808 /// 2809 void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap, 2810 const SelectorSet &ClsMap, 2811 SelectorSet &InsMapSeen, 2812 SelectorSet &ClsMapSeen, 2813 ObjCImplDecl* IMPDecl, 2814 ObjCContainerDecl* CDecl, 2815 bool &IncompleteImpl, 2816 bool ImmediateClass, 2817 bool WarnCategoryMethodImpl) { 2818 // Check and see if instance methods in class interface have been 2819 // implemented in the implementation class. If so, their types match. 2820 for (auto *I : CDecl->instance_methods()) { 2821 if (!InsMapSeen.insert(I->getSelector()).second) 2822 continue; 2823 if (!I->isPropertyAccessor() && 2824 !InsMap.count(I->getSelector())) { 2825 if (ImmediateClass) 2826 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl, 2827 diag::warn_undef_method_impl); 2828 continue; 2829 } else { 2830 ObjCMethodDecl *ImpMethodDecl = 2831 IMPDecl->getInstanceMethod(I->getSelector()); 2832 assert(CDecl->getInstanceMethod(I->getSelector(), true/*AllowHidden*/) && 2833 "Expected to find the method through lookup as well"); 2834 // ImpMethodDecl may be null as in a @dynamic property. 2835 if (ImpMethodDecl) { 2836 // Skip property accessor function stubs. 2837 if (ImpMethodDecl->isSynthesizedAccessorStub()) 2838 continue; 2839 if (!WarnCategoryMethodImpl) 2840 WarnConflictingTypedMethods(ImpMethodDecl, I, 2841 isa<ObjCProtocolDecl>(CDecl)); 2842 else if (!I->isPropertyAccessor()) 2843 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl)); 2844 } 2845 } 2846 } 2847 2848 // Check and see if class methods in class interface have been 2849 // implemented in the implementation class. If so, their types match. 2850 for (auto *I : CDecl->class_methods()) { 2851 if (!ClsMapSeen.insert(I->getSelector()).second) 2852 continue; 2853 if (!I->isPropertyAccessor() && 2854 !ClsMap.count(I->getSelector())) { 2855 if (ImmediateClass) 2856 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl, 2857 diag::warn_undef_method_impl); 2858 } else { 2859 ObjCMethodDecl *ImpMethodDecl = 2860 IMPDecl->getClassMethod(I->getSelector()); 2861 assert(CDecl->getClassMethod(I->getSelector(), true/*AllowHidden*/) && 2862 "Expected to find the method through lookup as well"); 2863 // ImpMethodDecl may be null as in a @dynamic property. 2864 if (ImpMethodDecl) { 2865 // Skip property accessor function stubs. 2866 if (ImpMethodDecl->isSynthesizedAccessorStub()) 2867 continue; 2868 if (!WarnCategoryMethodImpl) 2869 WarnConflictingTypedMethods(ImpMethodDecl, I, 2870 isa<ObjCProtocolDecl>(CDecl)); 2871 else if (!I->isPropertyAccessor()) 2872 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl)); 2873 } 2874 } 2875 } 2876 2877 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) { 2878 // Also, check for methods declared in protocols inherited by 2879 // this protocol. 2880 for (auto *PI : PD->protocols()) 2881 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2882 IMPDecl, PI, IncompleteImpl, false, 2883 WarnCategoryMethodImpl); 2884 } 2885 2886 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) { 2887 // when checking that methods in implementation match their declaration, 2888 // i.e. when WarnCategoryMethodImpl is false, check declarations in class 2889 // extension; as well as those in categories. 2890 if (!WarnCategoryMethodImpl) { 2891 for (auto *Cat : I->visible_categories()) 2892 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2893 IMPDecl, Cat, IncompleteImpl, 2894 ImmediateClass && Cat->IsClassExtension(), 2895 WarnCategoryMethodImpl); 2896 } else { 2897 // Also methods in class extensions need be looked at next. 2898 for (auto *Ext : I->visible_extensions()) 2899 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2900 IMPDecl, Ext, IncompleteImpl, false, 2901 WarnCategoryMethodImpl); 2902 } 2903 2904 // Check for any implementation of a methods declared in protocol. 2905 for (auto *PI : I->all_referenced_protocols()) 2906 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2907 IMPDecl, PI, IncompleteImpl, false, 2908 WarnCategoryMethodImpl); 2909 2910 // FIXME. For now, we are not checking for exact match of methods 2911 // in category implementation and its primary class's super class. 2912 if (!WarnCategoryMethodImpl && I->getSuperClass()) 2913 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2914 IMPDecl, 2915 I->getSuperClass(), IncompleteImpl, false); 2916 } 2917 } 2918 2919 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in 2920 /// category matches with those implemented in its primary class and 2921 /// warns each time an exact match is found. 2922 void Sema::CheckCategoryVsClassMethodMatches( 2923 ObjCCategoryImplDecl *CatIMPDecl) { 2924 // Get category's primary class. 2925 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl(); 2926 if (!CatDecl) 2927 return; 2928 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface(); 2929 if (!IDecl) 2930 return; 2931 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass(); 2932 SelectorSet InsMap, ClsMap; 2933 2934 for (const auto *I : CatIMPDecl->instance_methods()) { 2935 Selector Sel = I->getSelector(); 2936 // When checking for methods implemented in the category, skip over 2937 // those declared in category class's super class. This is because 2938 // the super class must implement the method. 2939 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true)) 2940 continue; 2941 InsMap.insert(Sel); 2942 } 2943 2944 for (const auto *I : CatIMPDecl->class_methods()) { 2945 Selector Sel = I->getSelector(); 2946 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false)) 2947 continue; 2948 ClsMap.insert(Sel); 2949 } 2950 if (InsMap.empty() && ClsMap.empty()) 2951 return; 2952 2953 SelectorSet InsMapSeen, ClsMapSeen; 2954 bool IncompleteImpl = false; 2955 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2956 CatIMPDecl, IDecl, 2957 IncompleteImpl, false, 2958 true /*WarnCategoryMethodImpl*/); 2959 } 2960 2961 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, 2962 ObjCContainerDecl* CDecl, 2963 bool IncompleteImpl) { 2964 SelectorSet InsMap; 2965 // Check and see if instance methods in class interface have been 2966 // implemented in the implementation class. 2967 for (const auto *I : IMPDecl->instance_methods()) 2968 InsMap.insert(I->getSelector()); 2969 2970 // Add the selectors for getters/setters of @dynamic properties. 2971 for (const auto *PImpl : IMPDecl->property_impls()) { 2972 // We only care about @dynamic implementations. 2973 if (PImpl->getPropertyImplementation() != ObjCPropertyImplDecl::Dynamic) 2974 continue; 2975 2976 const auto *P = PImpl->getPropertyDecl(); 2977 if (!P) continue; 2978 2979 InsMap.insert(P->getGetterName()); 2980 if (!P->getSetterName().isNull()) 2981 InsMap.insert(P->getSetterName()); 2982 } 2983 2984 // Check and see if properties declared in the interface have either 1) 2985 // an implementation or 2) there is a @synthesize/@dynamic implementation 2986 // of the property in the @implementation. 2987 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 2988 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties && 2989 LangOpts.ObjCRuntime.isNonFragile() && 2990 !IDecl->isObjCRequiresPropertyDefs(); 2991 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties); 2992 } 2993 2994 // Diagnose null-resettable synthesized setters. 2995 diagnoseNullResettableSynthesizedSetters(IMPDecl); 2996 2997 SelectorSet ClsMap; 2998 for (const auto *I : IMPDecl->class_methods()) 2999 ClsMap.insert(I->getSelector()); 3000 3001 // Check for type conflict of methods declared in a class/protocol and 3002 // its implementation; if any. 3003 SelectorSet InsMapSeen, ClsMapSeen; 3004 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 3005 IMPDecl, CDecl, 3006 IncompleteImpl, true); 3007 3008 // check all methods implemented in category against those declared 3009 // in its primary class. 3010 if (ObjCCategoryImplDecl *CatDecl = 3011 dyn_cast<ObjCCategoryImplDecl>(IMPDecl)) 3012 CheckCategoryVsClassMethodMatches(CatDecl); 3013 3014 // Check the protocol list for unimplemented methods in the @implementation 3015 // class. 3016 // Check and see if class methods in class interface have been 3017 // implemented in the implementation class. 3018 3019 LazyProtocolNameSet ExplicitImplProtocols; 3020 3021 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) { 3022 for (auto *PI : I->all_referenced_protocols()) 3023 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl, 3024 InsMap, ClsMap, I, ExplicitImplProtocols); 3025 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) { 3026 // For extended class, unimplemented methods in its protocols will 3027 // be reported in the primary class. 3028 if (!C->IsClassExtension()) { 3029 for (auto *P : C->protocols()) 3030 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P, 3031 IncompleteImpl, InsMap, ClsMap, CDecl, 3032 ExplicitImplProtocols); 3033 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, 3034 /*SynthesizeProperties=*/false); 3035 } 3036 } else 3037 llvm_unreachable("invalid ObjCContainerDecl type."); 3038 } 3039 3040 Sema::DeclGroupPtrTy 3041 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc, 3042 IdentifierInfo **IdentList, 3043 SourceLocation *IdentLocs, 3044 ArrayRef<ObjCTypeParamList *> TypeParamLists, 3045 unsigned NumElts) { 3046 SmallVector<Decl *, 8> DeclsInGroup; 3047 for (unsigned i = 0; i != NumElts; ++i) { 3048 // Check for another declaration kind with the same name. 3049 NamedDecl *PrevDecl 3050 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i], 3051 LookupOrdinaryName, forRedeclarationInCurContext()); 3052 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 3053 // GCC apparently allows the following idiom: 3054 // 3055 // typedef NSObject < XCElementTogglerP > XCElementToggler; 3056 // @class XCElementToggler; 3057 // 3058 // Here we have chosen to ignore the forward class declaration 3059 // with a warning. Since this is the implied behavior. 3060 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl); 3061 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) { 3062 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i]; 3063 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 3064 } else { 3065 // a forward class declaration matching a typedef name of a class refers 3066 // to the underlying class. Just ignore the forward class with a warning 3067 // as this will force the intended behavior which is to lookup the 3068 // typedef name. 3069 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) { 3070 Diag(AtClassLoc, diag::warn_forward_class_redefinition) 3071 << IdentList[i]; 3072 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 3073 continue; 3074 } 3075 } 3076 } 3077 3078 // Create a declaration to describe this forward declaration. 3079 ObjCInterfaceDecl *PrevIDecl 3080 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 3081 3082 IdentifierInfo *ClassName = IdentList[i]; 3083 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) { 3084 // A previous decl with a different name is because of 3085 // @compatibility_alias, for example: 3086 // \code 3087 // @class NewImage; 3088 // @compatibility_alias OldImage NewImage; 3089 // \endcode 3090 // A lookup for 'OldImage' will return the 'NewImage' decl. 3091 // 3092 // In such a case use the real declaration name, instead of the alias one, 3093 // otherwise we will break IdentifierResolver and redecls-chain invariants. 3094 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl 3095 // has been aliased. 3096 ClassName = PrevIDecl->getIdentifier(); 3097 } 3098 3099 // If this forward declaration has type parameters, compare them with the 3100 // type parameters of the previous declaration. 3101 ObjCTypeParamList *TypeParams = TypeParamLists[i]; 3102 if (PrevIDecl && TypeParams) { 3103 if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) { 3104 // Check for consistency with the previous declaration. 3105 if (checkTypeParamListConsistency( 3106 *this, PrevTypeParams, TypeParams, 3107 TypeParamListContext::ForwardDeclaration)) { 3108 TypeParams = nullptr; 3109 } 3110 } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) { 3111 // The @interface does not have type parameters. Complain. 3112 Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class) 3113 << ClassName 3114 << TypeParams->getSourceRange(); 3115 Diag(Def->getLocation(), diag::note_defined_here) 3116 << ClassName; 3117 3118 TypeParams = nullptr; 3119 } 3120 } 3121 3122 ObjCInterfaceDecl *IDecl 3123 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc, 3124 ClassName, TypeParams, PrevIDecl, 3125 IdentLocs[i]); 3126 IDecl->setAtEndRange(IdentLocs[i]); 3127 3128 PushOnScopeChains(IDecl, TUScope); 3129 CheckObjCDeclScope(IDecl); 3130 DeclsInGroup.push_back(IDecl); 3131 } 3132 3133 return BuildDeclaratorGroup(DeclsInGroup); 3134 } 3135 3136 static bool tryMatchRecordTypes(ASTContext &Context, 3137 Sema::MethodMatchStrategy strategy, 3138 const Type *left, const Type *right); 3139 3140 static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy, 3141 QualType leftQT, QualType rightQT) { 3142 const Type *left = 3143 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr(); 3144 const Type *right = 3145 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr(); 3146 3147 if (left == right) return true; 3148 3149 // If we're doing a strict match, the types have to match exactly. 3150 if (strategy == Sema::MMS_strict) return false; 3151 3152 if (left->isIncompleteType() || right->isIncompleteType()) return false; 3153 3154 // Otherwise, use this absurdly complicated algorithm to try to 3155 // validate the basic, low-level compatibility of the two types. 3156 3157 // As a minimum, require the sizes and alignments to match. 3158 TypeInfo LeftTI = Context.getTypeInfo(left); 3159 TypeInfo RightTI = Context.getTypeInfo(right); 3160 if (LeftTI.Width != RightTI.Width) 3161 return false; 3162 3163 if (LeftTI.Align != RightTI.Align) 3164 return false; 3165 3166 // Consider all the kinds of non-dependent canonical types: 3167 // - functions and arrays aren't possible as return and parameter types 3168 3169 // - vector types of equal size can be arbitrarily mixed 3170 if (isa<VectorType>(left)) return isa<VectorType>(right); 3171 if (isa<VectorType>(right)) return false; 3172 3173 // - references should only match references of identical type 3174 // - structs, unions, and Objective-C objects must match more-or-less 3175 // exactly 3176 // - everything else should be a scalar 3177 if (!left->isScalarType() || !right->isScalarType()) 3178 return tryMatchRecordTypes(Context, strategy, left, right); 3179 3180 // Make scalars agree in kind, except count bools as chars, and group 3181 // all non-member pointers together. 3182 Type::ScalarTypeKind leftSK = left->getScalarTypeKind(); 3183 Type::ScalarTypeKind rightSK = right->getScalarTypeKind(); 3184 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral; 3185 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral; 3186 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer) 3187 leftSK = Type::STK_ObjCObjectPointer; 3188 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer) 3189 rightSK = Type::STK_ObjCObjectPointer; 3190 3191 // Note that data member pointers and function member pointers don't 3192 // intermix because of the size differences. 3193 3194 return (leftSK == rightSK); 3195 } 3196 3197 static bool tryMatchRecordTypes(ASTContext &Context, 3198 Sema::MethodMatchStrategy strategy, 3199 const Type *lt, const Type *rt) { 3200 assert(lt && rt && lt != rt); 3201 3202 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false; 3203 RecordDecl *left = cast<RecordType>(lt)->getDecl(); 3204 RecordDecl *right = cast<RecordType>(rt)->getDecl(); 3205 3206 // Require union-hood to match. 3207 if (left->isUnion() != right->isUnion()) return false; 3208 3209 // Require an exact match if either is non-POD. 3210 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) || 3211 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD())) 3212 return false; 3213 3214 // Require size and alignment to match. 3215 TypeInfo LeftTI = Context.getTypeInfo(lt); 3216 TypeInfo RightTI = Context.getTypeInfo(rt); 3217 if (LeftTI.Width != RightTI.Width) 3218 return false; 3219 3220 if (LeftTI.Align != RightTI.Align) 3221 return false; 3222 3223 // Require fields to match. 3224 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end(); 3225 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end(); 3226 for (; li != le && ri != re; ++li, ++ri) { 3227 if (!matchTypes(Context, strategy, li->getType(), ri->getType())) 3228 return false; 3229 } 3230 return (li == le && ri == re); 3231 } 3232 3233 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and 3234 /// returns true, or false, accordingly. 3235 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons 3236 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left, 3237 const ObjCMethodDecl *right, 3238 MethodMatchStrategy strategy) { 3239 if (!matchTypes(Context, strategy, left->getReturnType(), 3240 right->getReturnType())) 3241 return false; 3242 3243 // If either is hidden, it is not considered to match. 3244 if (!left->isUnconditionallyVisible() || !right->isUnconditionallyVisible()) 3245 return false; 3246 3247 if (left->isDirectMethod() != right->isDirectMethod()) 3248 return false; 3249 3250 if (getLangOpts().ObjCAutoRefCount && 3251 (left->hasAttr<NSReturnsRetainedAttr>() 3252 != right->hasAttr<NSReturnsRetainedAttr>() || 3253 left->hasAttr<NSConsumesSelfAttr>() 3254 != right->hasAttr<NSConsumesSelfAttr>())) 3255 return false; 3256 3257 ObjCMethodDecl::param_const_iterator 3258 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(), 3259 re = right->param_end(); 3260 3261 for (; li != le && ri != re; ++li, ++ri) { 3262 assert(ri != right->param_end() && "Param mismatch"); 3263 const ParmVarDecl *lparm = *li, *rparm = *ri; 3264 3265 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType())) 3266 return false; 3267 3268 if (getLangOpts().ObjCAutoRefCount && 3269 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>()) 3270 return false; 3271 } 3272 return true; 3273 } 3274 3275 static bool isMethodContextSameForKindofLookup(ObjCMethodDecl *Method, 3276 ObjCMethodDecl *MethodInList) { 3277 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext()); 3278 auto *MethodInListProtocol = 3279 dyn_cast<ObjCProtocolDecl>(MethodInList->getDeclContext()); 3280 // If this method belongs to a protocol but the method in list does not, or 3281 // vice versa, we say the context is not the same. 3282 if ((MethodProtocol && !MethodInListProtocol) || 3283 (!MethodProtocol && MethodInListProtocol)) 3284 return false; 3285 3286 if (MethodProtocol && MethodInListProtocol) 3287 return true; 3288 3289 ObjCInterfaceDecl *MethodInterface = Method->getClassInterface(); 3290 ObjCInterfaceDecl *MethodInListInterface = 3291 MethodInList->getClassInterface(); 3292 return MethodInterface == MethodInListInterface; 3293 } 3294 3295 void Sema::addMethodToGlobalList(ObjCMethodList *List, 3296 ObjCMethodDecl *Method) { 3297 // Record at the head of the list whether there were 0, 1, or >= 2 methods 3298 // inside categories. 3299 if (ObjCCategoryDecl *CD = 3300 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext())) 3301 if (!CD->IsClassExtension() && List->getBits() < 2) 3302 List->setBits(List->getBits() + 1); 3303 3304 // If the list is empty, make it a singleton list. 3305 if (List->getMethod() == nullptr) { 3306 List->setMethod(Method); 3307 List->setNext(nullptr); 3308 return; 3309 } 3310 3311 // We've seen a method with this name, see if we have already seen this type 3312 // signature. 3313 ObjCMethodList *Previous = List; 3314 ObjCMethodList *ListWithSameDeclaration = nullptr; 3315 for (; List; Previous = List, List = List->getNext()) { 3316 // If we are building a module, keep all of the methods. 3317 if (getLangOpts().isCompilingModule()) 3318 continue; 3319 3320 bool SameDeclaration = MatchTwoMethodDeclarations(Method, 3321 List->getMethod()); 3322 // Looking for method with a type bound requires the correct context exists. 3323 // We need to insert a method into the list if the context is different. 3324 // If the method's declaration matches the list 3325 // a> the method belongs to a different context: we need to insert it, in 3326 // order to emit the availability message, we need to prioritize over 3327 // availability among the methods with the same declaration. 3328 // b> the method belongs to the same context: there is no need to insert a 3329 // new entry. 3330 // If the method's declaration does not match the list, we insert it to the 3331 // end. 3332 if (!SameDeclaration || 3333 !isMethodContextSameForKindofLookup(Method, List->getMethod())) { 3334 // Even if two method types do not match, we would like to say 3335 // there is more than one declaration so unavailability/deprecated 3336 // warning is not too noisy. 3337 if (!Method->isDefined()) 3338 List->setHasMoreThanOneDecl(true); 3339 3340 // For methods with the same declaration, the one that is deprecated 3341 // should be put in the front for better diagnostics. 3342 if (Method->isDeprecated() && SameDeclaration && 3343 !ListWithSameDeclaration && !List->getMethod()->isDeprecated()) 3344 ListWithSameDeclaration = List; 3345 3346 if (Method->isUnavailable() && SameDeclaration && 3347 !ListWithSameDeclaration && 3348 List->getMethod()->getAvailability() < AR_Deprecated) 3349 ListWithSameDeclaration = List; 3350 continue; 3351 } 3352 3353 ObjCMethodDecl *PrevObjCMethod = List->getMethod(); 3354 3355 // Propagate the 'defined' bit. 3356 if (Method->isDefined()) 3357 PrevObjCMethod->setDefined(true); 3358 else { 3359 // Objective-C doesn't allow an @interface for a class after its 3360 // @implementation. So if Method is not defined and there already is 3361 // an entry for this type signature, Method has to be for a different 3362 // class than PrevObjCMethod. 3363 List->setHasMoreThanOneDecl(true); 3364 } 3365 3366 // If a method is deprecated, push it in the global pool. 3367 // This is used for better diagnostics. 3368 if (Method->isDeprecated()) { 3369 if (!PrevObjCMethod->isDeprecated()) 3370 List->setMethod(Method); 3371 } 3372 // If the new method is unavailable, push it into global pool 3373 // unless previous one is deprecated. 3374 if (Method->isUnavailable()) { 3375 if (PrevObjCMethod->getAvailability() < AR_Deprecated) 3376 List->setMethod(Method); 3377 } 3378 3379 return; 3380 } 3381 3382 // We have a new signature for an existing method - add it. 3383 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded". 3384 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>(); 3385 3386 // We insert it right before ListWithSameDeclaration. 3387 if (ListWithSameDeclaration) { 3388 auto *List = new (Mem) ObjCMethodList(*ListWithSameDeclaration); 3389 // FIXME: should we clear the other bits in ListWithSameDeclaration? 3390 ListWithSameDeclaration->setMethod(Method); 3391 ListWithSameDeclaration->setNext(List); 3392 return; 3393 } 3394 3395 Previous->setNext(new (Mem) ObjCMethodList(Method)); 3396 } 3397 3398 /// Read the contents of the method pool for a given selector from 3399 /// external storage. 3400 void Sema::ReadMethodPool(Selector Sel) { 3401 assert(ExternalSource && "We need an external AST source"); 3402 ExternalSource->ReadMethodPool(Sel); 3403 } 3404 3405 void Sema::updateOutOfDateSelector(Selector Sel) { 3406 if (!ExternalSource) 3407 return; 3408 ExternalSource->updateOutOfDateSelector(Sel); 3409 } 3410 3411 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, 3412 bool instance) { 3413 // Ignore methods of invalid containers. 3414 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl()) 3415 return; 3416 3417 if (ExternalSource) 3418 ReadMethodPool(Method->getSelector()); 3419 3420 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector()); 3421 if (Pos == MethodPool.end()) 3422 Pos = MethodPool.insert(std::make_pair(Method->getSelector(), 3423 GlobalMethods())).first; 3424 3425 Method->setDefined(impl); 3426 3427 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second; 3428 addMethodToGlobalList(&Entry, Method); 3429 } 3430 3431 /// Determines if this is an "acceptable" loose mismatch in the global 3432 /// method pool. This exists mostly as a hack to get around certain 3433 /// global mismatches which we can't afford to make warnings / errors. 3434 /// Really, what we want is a way to take a method out of the global 3435 /// method pool. 3436 static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen, 3437 ObjCMethodDecl *other) { 3438 if (!chosen->isInstanceMethod()) 3439 return false; 3440 3441 if (chosen->isDirectMethod() != other->isDirectMethod()) 3442 return false; 3443 3444 Selector sel = chosen->getSelector(); 3445 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length") 3446 return false; 3447 3448 // Don't complain about mismatches for -length if the method we 3449 // chose has an integral result type. 3450 return (chosen->getReturnType()->isIntegerType()); 3451 } 3452 3453 /// Return true if the given method is wthin the type bound. 3454 static bool FilterMethodsByTypeBound(ObjCMethodDecl *Method, 3455 const ObjCObjectType *TypeBound) { 3456 if (!TypeBound) 3457 return true; 3458 3459 if (TypeBound->isObjCId()) 3460 // FIXME: should we handle the case of bounding to id<A, B> differently? 3461 return true; 3462 3463 auto *BoundInterface = TypeBound->getInterface(); 3464 assert(BoundInterface && "unexpected object type!"); 3465 3466 // Check if the Method belongs to a protocol. We should allow any method 3467 // defined in any protocol, because any subclass could adopt the protocol. 3468 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext()); 3469 if (MethodProtocol) { 3470 return true; 3471 } 3472 3473 // If the Method belongs to a class, check if it belongs to the class 3474 // hierarchy of the class bound. 3475 if (ObjCInterfaceDecl *MethodInterface = Method->getClassInterface()) { 3476 // We allow methods declared within classes that are part of the hierarchy 3477 // of the class bound (superclass of, subclass of, or the same as the class 3478 // bound). 3479 return MethodInterface == BoundInterface || 3480 MethodInterface->isSuperClassOf(BoundInterface) || 3481 BoundInterface->isSuperClassOf(MethodInterface); 3482 } 3483 llvm_unreachable("unknown method context"); 3484 } 3485 3486 /// We first select the type of the method: Instance or Factory, then collect 3487 /// all methods with that type. 3488 bool Sema::CollectMultipleMethodsInGlobalPool( 3489 Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods, 3490 bool InstanceFirst, bool CheckTheOther, 3491 const ObjCObjectType *TypeBound) { 3492 if (ExternalSource) 3493 ReadMethodPool(Sel); 3494 3495 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 3496 if (Pos == MethodPool.end()) 3497 return false; 3498 3499 // Gather the non-hidden methods. 3500 ObjCMethodList &MethList = InstanceFirst ? Pos->second.first : 3501 Pos->second.second; 3502 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) 3503 if (M->getMethod() && M->getMethod()->isUnconditionallyVisible()) { 3504 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound)) 3505 Methods.push_back(M->getMethod()); 3506 } 3507 3508 // Return if we find any method with the desired kind. 3509 if (!Methods.empty()) 3510 return Methods.size() > 1; 3511 3512 if (!CheckTheOther) 3513 return false; 3514 3515 // Gather the other kind. 3516 ObjCMethodList &MethList2 = InstanceFirst ? Pos->second.second : 3517 Pos->second.first; 3518 for (ObjCMethodList *M = &MethList2; M; M = M->getNext()) 3519 if (M->getMethod() && M->getMethod()->isUnconditionallyVisible()) { 3520 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound)) 3521 Methods.push_back(M->getMethod()); 3522 } 3523 3524 return Methods.size() > 1; 3525 } 3526 3527 bool Sema::AreMultipleMethodsInGlobalPool( 3528 Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R, 3529 bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl *> &Methods) { 3530 // Diagnose finding more than one method in global pool. 3531 SmallVector<ObjCMethodDecl *, 4> FilteredMethods; 3532 FilteredMethods.push_back(BestMethod); 3533 3534 for (auto *M : Methods) 3535 if (M != BestMethod && !M->hasAttr<UnavailableAttr>()) 3536 FilteredMethods.push_back(M); 3537 3538 if (FilteredMethods.size() > 1) 3539 DiagnoseMultipleMethodInGlobalPool(FilteredMethods, Sel, R, 3540 receiverIdOrClass); 3541 3542 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 3543 // Test for no method in the pool which should not trigger any warning by 3544 // caller. 3545 if (Pos == MethodPool.end()) 3546 return true; 3547 ObjCMethodList &MethList = 3548 BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second; 3549 return MethList.hasMoreThanOneDecl(); 3550 } 3551 3552 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R, 3553 bool receiverIdOrClass, 3554 bool instance) { 3555 if (ExternalSource) 3556 ReadMethodPool(Sel); 3557 3558 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 3559 if (Pos == MethodPool.end()) 3560 return nullptr; 3561 3562 // Gather the non-hidden methods. 3563 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second; 3564 SmallVector<ObjCMethodDecl *, 4> Methods; 3565 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) { 3566 if (M->getMethod() && M->getMethod()->isUnconditionallyVisible()) 3567 return M->getMethod(); 3568 } 3569 return nullptr; 3570 } 3571 3572 void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods, 3573 Selector Sel, SourceRange R, 3574 bool receiverIdOrClass) { 3575 // We found multiple methods, so we may have to complain. 3576 bool issueDiagnostic = false, issueError = false; 3577 3578 // We support a warning which complains about *any* difference in 3579 // method signature. 3580 bool strictSelectorMatch = 3581 receiverIdOrClass && 3582 !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin()); 3583 if (strictSelectorMatch) { 3584 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 3585 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) { 3586 issueDiagnostic = true; 3587 break; 3588 } 3589 } 3590 } 3591 3592 // If we didn't see any strict differences, we won't see any loose 3593 // differences. In ARC, however, we also need to check for loose 3594 // mismatches, because most of them are errors. 3595 if (!strictSelectorMatch || 3596 (issueDiagnostic && getLangOpts().ObjCAutoRefCount)) 3597 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 3598 // This checks if the methods differ in type mismatch. 3599 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) && 3600 !isAcceptableMethodMismatch(Methods[0], Methods[I])) { 3601 issueDiagnostic = true; 3602 if (getLangOpts().ObjCAutoRefCount) 3603 issueError = true; 3604 break; 3605 } 3606 } 3607 3608 if (issueDiagnostic) { 3609 if (issueError) 3610 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R; 3611 else if (strictSelectorMatch) 3612 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R; 3613 else 3614 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R; 3615 3616 Diag(Methods[0]->getBeginLoc(), 3617 issueError ? diag::note_possibility : diag::note_using) 3618 << Methods[0]->getSourceRange(); 3619 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 3620 Diag(Methods[I]->getBeginLoc(), diag::note_also_found) 3621 << Methods[I]->getSourceRange(); 3622 } 3623 } 3624 } 3625 3626 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) { 3627 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 3628 if (Pos == MethodPool.end()) 3629 return nullptr; 3630 3631 GlobalMethods &Methods = Pos->second; 3632 for (const ObjCMethodList *Method = &Methods.first; Method; 3633 Method = Method->getNext()) 3634 if (Method->getMethod() && 3635 (Method->getMethod()->isDefined() || 3636 Method->getMethod()->isPropertyAccessor())) 3637 return Method->getMethod(); 3638 3639 for (const ObjCMethodList *Method = &Methods.second; Method; 3640 Method = Method->getNext()) 3641 if (Method->getMethod() && 3642 (Method->getMethod()->isDefined() || 3643 Method->getMethod()->isPropertyAccessor())) 3644 return Method->getMethod(); 3645 return nullptr; 3646 } 3647 3648 static void 3649 HelperSelectorsForTypoCorrection( 3650 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod, 3651 StringRef Typo, const ObjCMethodDecl * Method) { 3652 const unsigned MaxEditDistance = 1; 3653 unsigned BestEditDistance = MaxEditDistance + 1; 3654 std::string MethodName = Method->getSelector().getAsString(); 3655 3656 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size()); 3657 if (MinPossibleEditDistance > 0 && 3658 Typo.size() / MinPossibleEditDistance < 1) 3659 return; 3660 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance); 3661 if (EditDistance > MaxEditDistance) 3662 return; 3663 if (EditDistance == BestEditDistance) 3664 BestMethod.push_back(Method); 3665 else if (EditDistance < BestEditDistance) { 3666 BestMethod.clear(); 3667 BestMethod.push_back(Method); 3668 } 3669 } 3670 3671 static bool HelperIsMethodInObjCType(Sema &S, Selector Sel, 3672 QualType ObjectType) { 3673 if (ObjectType.isNull()) 3674 return true; 3675 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/)) 3676 return true; 3677 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) != 3678 nullptr; 3679 } 3680 3681 const ObjCMethodDecl * 3682 Sema::SelectorsForTypoCorrection(Selector Sel, 3683 QualType ObjectType) { 3684 unsigned NumArgs = Sel.getNumArgs(); 3685 SmallVector<const ObjCMethodDecl *, 8> Methods; 3686 bool ObjectIsId = true, ObjectIsClass = true; 3687 if (ObjectType.isNull()) 3688 ObjectIsId = ObjectIsClass = false; 3689 else if (!ObjectType->isObjCObjectPointerType()) 3690 return nullptr; 3691 else if (const ObjCObjectPointerType *ObjCPtr = 3692 ObjectType->getAsObjCInterfacePointerType()) { 3693 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0); 3694 ObjectIsId = ObjectIsClass = false; 3695 } 3696 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType()) 3697 ObjectIsClass = false; 3698 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType()) 3699 ObjectIsId = false; 3700 else 3701 return nullptr; 3702 3703 for (GlobalMethodPool::iterator b = MethodPool.begin(), 3704 e = MethodPool.end(); b != e; b++) { 3705 // instance methods 3706 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext()) 3707 if (M->getMethod() && 3708 (M->getMethod()->getSelector().getNumArgs() == NumArgs) && 3709 (M->getMethod()->getSelector() != Sel)) { 3710 if (ObjectIsId) 3711 Methods.push_back(M->getMethod()); 3712 else if (!ObjectIsClass && 3713 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(), 3714 ObjectType)) 3715 Methods.push_back(M->getMethod()); 3716 } 3717 // class methods 3718 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext()) 3719 if (M->getMethod() && 3720 (M->getMethod()->getSelector().getNumArgs() == NumArgs) && 3721 (M->getMethod()->getSelector() != Sel)) { 3722 if (ObjectIsClass) 3723 Methods.push_back(M->getMethod()); 3724 else if (!ObjectIsId && 3725 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(), 3726 ObjectType)) 3727 Methods.push_back(M->getMethod()); 3728 } 3729 } 3730 3731 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods; 3732 for (unsigned i = 0, e = Methods.size(); i < e; i++) { 3733 HelperSelectorsForTypoCorrection(SelectedMethods, 3734 Sel.getAsString(), Methods[i]); 3735 } 3736 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr; 3737 } 3738 3739 /// DiagnoseDuplicateIvars - 3740 /// Check for duplicate ivars in the entire class at the start of 3741 /// \@implementation. This becomes necesssary because class extension can 3742 /// add ivars to a class in random order which will not be known until 3743 /// class's \@implementation is seen. 3744 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, 3745 ObjCInterfaceDecl *SID) { 3746 for (auto *Ivar : ID->ivars()) { 3747 if (Ivar->isInvalidDecl()) 3748 continue; 3749 if (IdentifierInfo *II = Ivar->getIdentifier()) { 3750 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II); 3751 if (prevIvar) { 3752 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II; 3753 Diag(prevIvar->getLocation(), diag::note_previous_declaration); 3754 Ivar->setInvalidDecl(); 3755 } 3756 } 3757 } 3758 } 3759 3760 /// Diagnose attempts to define ARC-__weak ivars when __weak is disabled. 3761 static void DiagnoseWeakIvars(Sema &S, ObjCImplementationDecl *ID) { 3762 if (S.getLangOpts().ObjCWeak) return; 3763 3764 for (auto ivar = ID->getClassInterface()->all_declared_ivar_begin(); 3765 ivar; ivar = ivar->getNextIvar()) { 3766 if (ivar->isInvalidDecl()) continue; 3767 if (ivar->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 3768 if (S.getLangOpts().ObjCWeakRuntime) { 3769 S.Diag(ivar->getLocation(), diag::err_arc_weak_disabled); 3770 } else { 3771 S.Diag(ivar->getLocation(), diag::err_arc_weak_no_runtime); 3772 } 3773 } 3774 } 3775 } 3776 3777 /// Diagnose attempts to use flexible array member with retainable object type. 3778 static void DiagnoseRetainableFlexibleArrayMember(Sema &S, 3779 ObjCInterfaceDecl *ID) { 3780 if (!S.getLangOpts().ObjCAutoRefCount) 3781 return; 3782 3783 for (auto ivar = ID->all_declared_ivar_begin(); ivar; 3784 ivar = ivar->getNextIvar()) { 3785 if (ivar->isInvalidDecl()) 3786 continue; 3787 QualType IvarTy = ivar->getType(); 3788 if (IvarTy->isIncompleteArrayType() && 3789 (IvarTy.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) && 3790 IvarTy->isObjCLifetimeType()) { 3791 S.Diag(ivar->getLocation(), diag::err_flexible_array_arc_retainable); 3792 ivar->setInvalidDecl(); 3793 } 3794 } 3795 } 3796 3797 Sema::ObjCContainerKind Sema::getObjCContainerKind() const { 3798 switch (CurContext->getDeclKind()) { 3799 case Decl::ObjCInterface: 3800 return Sema::OCK_Interface; 3801 case Decl::ObjCProtocol: 3802 return Sema::OCK_Protocol; 3803 case Decl::ObjCCategory: 3804 if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension()) 3805 return Sema::OCK_ClassExtension; 3806 return Sema::OCK_Category; 3807 case Decl::ObjCImplementation: 3808 return Sema::OCK_Implementation; 3809 case Decl::ObjCCategoryImpl: 3810 return Sema::OCK_CategoryImplementation; 3811 3812 default: 3813 return Sema::OCK_None; 3814 } 3815 } 3816 3817 static bool IsVariableSizedType(QualType T) { 3818 if (T->isIncompleteArrayType()) 3819 return true; 3820 const auto *RecordTy = T->getAs<RecordType>(); 3821 return (RecordTy && RecordTy->getDecl()->hasFlexibleArrayMember()); 3822 } 3823 3824 static void DiagnoseVariableSizedIvars(Sema &S, ObjCContainerDecl *OCD) { 3825 ObjCInterfaceDecl *IntfDecl = nullptr; 3826 ObjCInterfaceDecl::ivar_range Ivars = llvm::make_range( 3827 ObjCInterfaceDecl::ivar_iterator(), ObjCInterfaceDecl::ivar_iterator()); 3828 if ((IntfDecl = dyn_cast<ObjCInterfaceDecl>(OCD))) { 3829 Ivars = IntfDecl->ivars(); 3830 } else if (auto *ImplDecl = dyn_cast<ObjCImplementationDecl>(OCD)) { 3831 IntfDecl = ImplDecl->getClassInterface(); 3832 Ivars = ImplDecl->ivars(); 3833 } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(OCD)) { 3834 if (CategoryDecl->IsClassExtension()) { 3835 IntfDecl = CategoryDecl->getClassInterface(); 3836 Ivars = CategoryDecl->ivars(); 3837 } 3838 } 3839 3840 // Check if variable sized ivar is in interface and visible to subclasses. 3841 if (!isa<ObjCInterfaceDecl>(OCD)) { 3842 for (auto ivar : Ivars) { 3843 if (!ivar->isInvalidDecl() && IsVariableSizedType(ivar->getType())) { 3844 S.Diag(ivar->getLocation(), diag::warn_variable_sized_ivar_visibility) 3845 << ivar->getDeclName() << ivar->getType(); 3846 } 3847 } 3848 } 3849 3850 // Subsequent checks require interface decl. 3851 if (!IntfDecl) 3852 return; 3853 3854 // Check if variable sized ivar is followed by another ivar. 3855 for (ObjCIvarDecl *ivar = IntfDecl->all_declared_ivar_begin(); ivar; 3856 ivar = ivar->getNextIvar()) { 3857 if (ivar->isInvalidDecl() || !ivar->getNextIvar()) 3858 continue; 3859 QualType IvarTy = ivar->getType(); 3860 bool IsInvalidIvar = false; 3861 if (IvarTy->isIncompleteArrayType()) { 3862 S.Diag(ivar->getLocation(), diag::err_flexible_array_not_at_end) 3863 << ivar->getDeclName() << IvarTy 3864 << TTK_Class; // Use "class" for Obj-C. 3865 IsInvalidIvar = true; 3866 } else if (const RecordType *RecordTy = IvarTy->getAs<RecordType>()) { 3867 if (RecordTy->getDecl()->hasFlexibleArrayMember()) { 3868 S.Diag(ivar->getLocation(), 3869 diag::err_objc_variable_sized_type_not_at_end) 3870 << ivar->getDeclName() << IvarTy; 3871 IsInvalidIvar = true; 3872 } 3873 } 3874 if (IsInvalidIvar) { 3875 S.Diag(ivar->getNextIvar()->getLocation(), 3876 diag::note_next_ivar_declaration) 3877 << ivar->getNextIvar()->getSynthesize(); 3878 ivar->setInvalidDecl(); 3879 } 3880 } 3881 3882 // Check if ObjC container adds ivars after variable sized ivar in superclass. 3883 // Perform the check only if OCD is the first container to declare ivars to 3884 // avoid multiple warnings for the same ivar. 3885 ObjCIvarDecl *FirstIvar = 3886 (Ivars.begin() == Ivars.end()) ? nullptr : *Ivars.begin(); 3887 if (FirstIvar && (FirstIvar == IntfDecl->all_declared_ivar_begin())) { 3888 const ObjCInterfaceDecl *SuperClass = IntfDecl->getSuperClass(); 3889 while (SuperClass && SuperClass->ivar_empty()) 3890 SuperClass = SuperClass->getSuperClass(); 3891 if (SuperClass) { 3892 auto IvarIter = SuperClass->ivar_begin(); 3893 std::advance(IvarIter, SuperClass->ivar_size() - 1); 3894 const ObjCIvarDecl *LastIvar = *IvarIter; 3895 if (IsVariableSizedType(LastIvar->getType())) { 3896 S.Diag(FirstIvar->getLocation(), 3897 diag::warn_superclass_variable_sized_type_not_at_end) 3898 << FirstIvar->getDeclName() << LastIvar->getDeclName() 3899 << LastIvar->getType() << SuperClass->getDeclName(); 3900 S.Diag(LastIvar->getLocation(), diag::note_entity_declared_at) 3901 << LastIvar->getDeclName(); 3902 } 3903 } 3904 } 3905 } 3906 3907 // Note: For class/category implementations, allMethods is always null. 3908 Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods, 3909 ArrayRef<DeclGroupPtrTy> allTUVars) { 3910 if (getObjCContainerKind() == Sema::OCK_None) 3911 return nullptr; 3912 3913 assert(AtEnd.isValid() && "Invalid location for '@end'"); 3914 3915 auto *OCD = cast<ObjCContainerDecl>(CurContext); 3916 Decl *ClassDecl = OCD; 3917 3918 bool isInterfaceDeclKind = 3919 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl) 3920 || isa<ObjCProtocolDecl>(ClassDecl); 3921 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl); 3922 3923 // Make synthesized accessor stub functions visible. 3924 // ActOnPropertyImplDecl() creates them as not visible in case 3925 // they are overridden by an explicit method that is encountered 3926 // later. 3927 if (auto *OID = dyn_cast<ObjCImplementationDecl>(CurContext)) { 3928 for (auto PropImpl : OID->property_impls()) { 3929 if (auto *Getter = PropImpl->getGetterMethodDecl()) 3930 if (Getter->isSynthesizedAccessorStub()) 3931 OID->addDecl(Getter); 3932 if (auto *Setter = PropImpl->getSetterMethodDecl()) 3933 if (Setter->isSynthesizedAccessorStub()) 3934 OID->addDecl(Setter); 3935 } 3936 } 3937 3938 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext. 3939 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap; 3940 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap; 3941 3942 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) { 3943 ObjCMethodDecl *Method = 3944 cast_or_null<ObjCMethodDecl>(allMethods[i]); 3945 3946 if (!Method) continue; // Already issued a diagnostic. 3947 if (Method->isInstanceMethod()) { 3948 /// Check for instance method of the same name with incompatible types 3949 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()]; 3950 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod) 3951 : false; 3952 if ((isInterfaceDeclKind && PrevMethod && !match) 3953 || (checkIdenticalMethods && match)) { 3954 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 3955 << Method->getDeclName(); 3956 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 3957 Method->setInvalidDecl(); 3958 } else { 3959 if (PrevMethod) { 3960 Method->setAsRedeclaration(PrevMethod); 3961 if (!Context.getSourceManager().isInSystemHeader( 3962 Method->getLocation())) 3963 Diag(Method->getLocation(), diag::warn_duplicate_method_decl) 3964 << Method->getDeclName(); 3965 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 3966 } 3967 InsMap[Method->getSelector()] = Method; 3968 /// The following allows us to typecheck messages to "id". 3969 AddInstanceMethodToGlobalPool(Method); 3970 } 3971 } else { 3972 /// Check for class method of the same name with incompatible types 3973 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()]; 3974 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod) 3975 : false; 3976 if ((isInterfaceDeclKind && PrevMethod && !match) 3977 || (checkIdenticalMethods && match)) { 3978 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 3979 << Method->getDeclName(); 3980 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 3981 Method->setInvalidDecl(); 3982 } else { 3983 if (PrevMethod) { 3984 Method->setAsRedeclaration(PrevMethod); 3985 if (!Context.getSourceManager().isInSystemHeader( 3986 Method->getLocation())) 3987 Diag(Method->getLocation(), diag::warn_duplicate_method_decl) 3988 << Method->getDeclName(); 3989 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 3990 } 3991 ClsMap[Method->getSelector()] = Method; 3992 AddFactoryMethodToGlobalPool(Method); 3993 } 3994 } 3995 } 3996 if (isa<ObjCInterfaceDecl>(ClassDecl)) { 3997 // Nothing to do here. 3998 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) { 3999 // Categories are used to extend the class by declaring new methods. 4000 // By the same token, they are also used to add new properties. No 4001 // need to compare the added property to those in the class. 4002 4003 if (C->IsClassExtension()) { 4004 ObjCInterfaceDecl *CCPrimary = C->getClassInterface(); 4005 DiagnoseClassExtensionDupMethods(C, CCPrimary); 4006 } 4007 } 4008 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) { 4009 if (CDecl->getIdentifier()) 4010 // ProcessPropertyDecl is responsible for diagnosing conflicts with any 4011 // user-defined setter/getter. It also synthesizes setter/getter methods 4012 // and adds them to the DeclContext and global method pools. 4013 for (auto *I : CDecl->properties()) 4014 ProcessPropertyDecl(I); 4015 CDecl->setAtEndRange(AtEnd); 4016 } 4017 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) { 4018 IC->setAtEndRange(AtEnd); 4019 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) { 4020 // Any property declared in a class extension might have user 4021 // declared setter or getter in current class extension or one 4022 // of the other class extensions. Mark them as synthesized as 4023 // property will be synthesized when property with same name is 4024 // seen in the @implementation. 4025 for (const auto *Ext : IDecl->visible_extensions()) { 4026 for (const auto *Property : Ext->instance_properties()) { 4027 // Skip over properties declared @dynamic 4028 if (const ObjCPropertyImplDecl *PIDecl 4029 = IC->FindPropertyImplDecl(Property->getIdentifier(), 4030 Property->getQueryKind())) 4031 if (PIDecl->getPropertyImplementation() 4032 == ObjCPropertyImplDecl::Dynamic) 4033 continue; 4034 4035 for (const auto *Ext : IDecl->visible_extensions()) { 4036 if (ObjCMethodDecl *GetterMethod = 4037 Ext->getInstanceMethod(Property->getGetterName())) 4038 GetterMethod->setPropertyAccessor(true); 4039 if (!Property->isReadOnly()) 4040 if (ObjCMethodDecl *SetterMethod 4041 = Ext->getInstanceMethod(Property->getSetterName())) 4042 SetterMethod->setPropertyAccessor(true); 4043 } 4044 } 4045 } 4046 ImplMethodsVsClassMethods(S, IC, IDecl); 4047 AtomicPropertySetterGetterRules(IC, IDecl); 4048 DiagnoseOwningPropertyGetterSynthesis(IC); 4049 DiagnoseUnusedBackingIvarInAccessor(S, IC); 4050 if (IDecl->hasDesignatedInitializers()) 4051 DiagnoseMissingDesignatedInitOverrides(IC, IDecl); 4052 DiagnoseWeakIvars(*this, IC); 4053 DiagnoseRetainableFlexibleArrayMember(*this, IDecl); 4054 4055 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>(); 4056 if (IDecl->getSuperClass() == nullptr) { 4057 // This class has no superclass, so check that it has been marked with 4058 // __attribute((objc_root_class)). 4059 if (!HasRootClassAttr) { 4060 SourceLocation DeclLoc(IDecl->getLocation()); 4061 SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc)); 4062 Diag(DeclLoc, diag::warn_objc_root_class_missing) 4063 << IDecl->getIdentifier(); 4064 // See if NSObject is in the current scope, and if it is, suggest 4065 // adding " : NSObject " to the class declaration. 4066 NamedDecl *IF = LookupSingleName(TUScope, 4067 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject), 4068 DeclLoc, LookupOrdinaryName); 4069 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); 4070 if (NSObjectDecl && NSObjectDecl->getDefinition()) { 4071 Diag(SuperClassLoc, diag::note_objc_needs_superclass) 4072 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject "); 4073 } else { 4074 Diag(SuperClassLoc, diag::note_objc_needs_superclass); 4075 } 4076 } 4077 } else if (HasRootClassAttr) { 4078 // Complain that only root classes may have this attribute. 4079 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass); 4080 } 4081 4082 if (const ObjCInterfaceDecl *Super = IDecl->getSuperClass()) { 4083 // An interface can subclass another interface with a 4084 // objc_subclassing_restricted attribute when it has that attribute as 4085 // well (because of interfaces imported from Swift). Therefore we have 4086 // to check if we can subclass in the implementation as well. 4087 if (IDecl->hasAttr<ObjCSubclassingRestrictedAttr>() && 4088 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) { 4089 Diag(IC->getLocation(), diag::err_restricted_superclass_mismatch); 4090 Diag(Super->getLocation(), diag::note_class_declared); 4091 } 4092 } 4093 4094 if (IDecl->hasAttr<ObjCClassStubAttr>()) 4095 Diag(IC->getLocation(), diag::err_implementation_of_class_stub); 4096 4097 if (LangOpts.ObjCRuntime.isNonFragile()) { 4098 while (IDecl->getSuperClass()) { 4099 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass()); 4100 IDecl = IDecl->getSuperClass(); 4101 } 4102 } 4103 } 4104 SetIvarInitializers(IC); 4105 } else if (ObjCCategoryImplDecl* CatImplClass = 4106 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) { 4107 CatImplClass->setAtEndRange(AtEnd); 4108 4109 // Find category interface decl and then check that all methods declared 4110 // in this interface are implemented in the category @implementation. 4111 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) { 4112 if (ObjCCategoryDecl *Cat 4113 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) { 4114 ImplMethodsVsClassMethods(S, CatImplClass, Cat); 4115 } 4116 } 4117 } else if (const auto *IntfDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) { 4118 if (const ObjCInterfaceDecl *Super = IntfDecl->getSuperClass()) { 4119 if (!IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>() && 4120 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) { 4121 Diag(IntfDecl->getLocation(), diag::err_restricted_superclass_mismatch); 4122 Diag(Super->getLocation(), diag::note_class_declared); 4123 } 4124 } 4125 4126 if (IntfDecl->hasAttr<ObjCClassStubAttr>() && 4127 !IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>()) 4128 Diag(IntfDecl->getLocation(), diag::err_class_stub_subclassing_mismatch); 4129 } 4130 DiagnoseVariableSizedIvars(*this, OCD); 4131 if (isInterfaceDeclKind) { 4132 // Reject invalid vardecls. 4133 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) { 4134 DeclGroupRef DG = allTUVars[i].get(); 4135 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) 4136 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) { 4137 if (!VDecl->hasExternalStorage()) 4138 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass); 4139 } 4140 } 4141 } 4142 ActOnObjCContainerFinishDefinition(); 4143 4144 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) { 4145 DeclGroupRef DG = allTUVars[i].get(); 4146 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) 4147 (*I)->setTopLevelDeclInObjCContainer(); 4148 Consumer.HandleTopLevelDeclInObjCContainer(DG); 4149 } 4150 4151 ActOnDocumentableDecl(ClassDecl); 4152 return ClassDecl; 4153 } 4154 4155 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for 4156 /// objective-c's type qualifier from the parser version of the same info. 4157 static Decl::ObjCDeclQualifier 4158 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) { 4159 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal; 4160 } 4161 4162 /// Check whether the declared result type of the given Objective-C 4163 /// method declaration is compatible with the method's class. 4164 /// 4165 static Sema::ResultTypeCompatibilityKind 4166 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method, 4167 ObjCInterfaceDecl *CurrentClass) { 4168 QualType ResultType = Method->getReturnType(); 4169 4170 // If an Objective-C method inherits its related result type, then its 4171 // declared result type must be compatible with its own class type. The 4172 // declared result type is compatible if: 4173 if (const ObjCObjectPointerType *ResultObjectType 4174 = ResultType->getAs<ObjCObjectPointerType>()) { 4175 // - it is id or qualified id, or 4176 if (ResultObjectType->isObjCIdType() || 4177 ResultObjectType->isObjCQualifiedIdType()) 4178 return Sema::RTC_Compatible; 4179 4180 if (CurrentClass) { 4181 if (ObjCInterfaceDecl *ResultClass 4182 = ResultObjectType->getInterfaceDecl()) { 4183 // - it is the same as the method's class type, or 4184 if (declaresSameEntity(CurrentClass, ResultClass)) 4185 return Sema::RTC_Compatible; 4186 4187 // - it is a superclass of the method's class type 4188 if (ResultClass->isSuperClassOf(CurrentClass)) 4189 return Sema::RTC_Compatible; 4190 } 4191 } else { 4192 // Any Objective-C pointer type might be acceptable for a protocol 4193 // method; we just don't know. 4194 return Sema::RTC_Unknown; 4195 } 4196 } 4197 4198 return Sema::RTC_Incompatible; 4199 } 4200 4201 namespace { 4202 /// A helper class for searching for methods which a particular method 4203 /// overrides. 4204 class OverrideSearch { 4205 public: 4206 const ObjCMethodDecl *Method; 4207 llvm::SmallSetVector<ObjCMethodDecl*, 4> Overridden; 4208 bool Recursive; 4209 4210 public: 4211 OverrideSearch(Sema &S, const ObjCMethodDecl *method) : Method(method) { 4212 Selector selector = method->getSelector(); 4213 4214 // Bypass this search if we've never seen an instance/class method 4215 // with this selector before. 4216 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector); 4217 if (it == S.MethodPool.end()) { 4218 if (!S.getExternalSource()) return; 4219 S.ReadMethodPool(selector); 4220 4221 it = S.MethodPool.find(selector); 4222 if (it == S.MethodPool.end()) 4223 return; 4224 } 4225 const ObjCMethodList &list = 4226 method->isInstanceMethod() ? it->second.first : it->second.second; 4227 if (!list.getMethod()) return; 4228 4229 const ObjCContainerDecl *container 4230 = cast<ObjCContainerDecl>(method->getDeclContext()); 4231 4232 // Prevent the search from reaching this container again. This is 4233 // important with categories, which override methods from the 4234 // interface and each other. 4235 if (const ObjCCategoryDecl *Category = 4236 dyn_cast<ObjCCategoryDecl>(container)) { 4237 searchFromContainer(container); 4238 if (const ObjCInterfaceDecl *Interface = Category->getClassInterface()) 4239 searchFromContainer(Interface); 4240 } else { 4241 searchFromContainer(container); 4242 } 4243 } 4244 4245 typedef decltype(Overridden)::iterator iterator; 4246 iterator begin() const { return Overridden.begin(); } 4247 iterator end() const { return Overridden.end(); } 4248 4249 private: 4250 void searchFromContainer(const ObjCContainerDecl *container) { 4251 if (container->isInvalidDecl()) return; 4252 4253 switch (container->getDeclKind()) { 4254 #define OBJCCONTAINER(type, base) \ 4255 case Decl::type: \ 4256 searchFrom(cast<type##Decl>(container)); \ 4257 break; 4258 #define ABSTRACT_DECL(expansion) 4259 #define DECL(type, base) \ 4260 case Decl::type: 4261 #include "clang/AST/DeclNodes.inc" 4262 llvm_unreachable("not an ObjC container!"); 4263 } 4264 } 4265 4266 void searchFrom(const ObjCProtocolDecl *protocol) { 4267 if (!protocol->hasDefinition()) 4268 return; 4269 4270 // A method in a protocol declaration overrides declarations from 4271 // referenced ("parent") protocols. 4272 search(protocol->getReferencedProtocols()); 4273 } 4274 4275 void searchFrom(const ObjCCategoryDecl *category) { 4276 // A method in a category declaration overrides declarations from 4277 // the main class and from protocols the category references. 4278 // The main class is handled in the constructor. 4279 search(category->getReferencedProtocols()); 4280 } 4281 4282 void searchFrom(const ObjCCategoryImplDecl *impl) { 4283 // A method in a category definition that has a category 4284 // declaration overrides declarations from the category 4285 // declaration. 4286 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) { 4287 search(category); 4288 if (ObjCInterfaceDecl *Interface = category->getClassInterface()) 4289 search(Interface); 4290 4291 // Otherwise it overrides declarations from the class. 4292 } else if (const auto *Interface = impl->getClassInterface()) { 4293 search(Interface); 4294 } 4295 } 4296 4297 void searchFrom(const ObjCInterfaceDecl *iface) { 4298 // A method in a class declaration overrides declarations from 4299 if (!iface->hasDefinition()) 4300 return; 4301 4302 // - categories, 4303 for (auto *Cat : iface->known_categories()) 4304 search(Cat); 4305 4306 // - the super class, and 4307 if (ObjCInterfaceDecl *super = iface->getSuperClass()) 4308 search(super); 4309 4310 // - any referenced protocols. 4311 search(iface->getReferencedProtocols()); 4312 } 4313 4314 void searchFrom(const ObjCImplementationDecl *impl) { 4315 // A method in a class implementation overrides declarations from 4316 // the class interface. 4317 if (const auto *Interface = impl->getClassInterface()) 4318 search(Interface); 4319 } 4320 4321 void search(const ObjCProtocolList &protocols) { 4322 for (const auto *Proto : protocols) 4323 search(Proto); 4324 } 4325 4326 void search(const ObjCContainerDecl *container) { 4327 // Check for a method in this container which matches this selector. 4328 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(), 4329 Method->isInstanceMethod(), 4330 /*AllowHidden=*/true); 4331 4332 // If we find one, record it and bail out. 4333 if (meth) { 4334 Overridden.insert(meth); 4335 return; 4336 } 4337 4338 // Otherwise, search for methods that a hypothetical method here 4339 // would have overridden. 4340 4341 // Note that we're now in a recursive case. 4342 Recursive = true; 4343 4344 searchFromContainer(container); 4345 } 4346 }; 4347 } // end anonymous namespace 4348 4349 void Sema::CheckObjCMethodDirectOverrides(ObjCMethodDecl *method, 4350 ObjCMethodDecl *overridden) { 4351 if (const auto *attr = overridden->getAttr<ObjCDirectAttr>()) { 4352 Diag(method->getLocation(), diag::err_objc_override_direct_method); 4353 Diag(attr->getLocation(), diag::note_previous_declaration); 4354 } else if (const auto *attr = method->getAttr<ObjCDirectAttr>()) { 4355 Diag(attr->getLocation(), diag::err_objc_direct_on_override) 4356 << isa<ObjCProtocolDecl>(overridden->getDeclContext()); 4357 Diag(overridden->getLocation(), diag::note_previous_declaration); 4358 } 4359 } 4360 4361 void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, 4362 ObjCInterfaceDecl *CurrentClass, 4363 ResultTypeCompatibilityKind RTC) { 4364 if (!ObjCMethod) 4365 return; 4366 // Search for overridden methods and merge information down from them. 4367 OverrideSearch overrides(*this, ObjCMethod); 4368 // Keep track if the method overrides any method in the class's base classes, 4369 // its protocols, or its categories' protocols; we will keep that info 4370 // in the ObjCMethodDecl. 4371 // For this info, a method in an implementation is not considered as 4372 // overriding the same method in the interface or its categories. 4373 bool hasOverriddenMethodsInBaseOrProtocol = false; 4374 for (ObjCMethodDecl *overridden : overrides) { 4375 if (!hasOverriddenMethodsInBaseOrProtocol) { 4376 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) || 4377 CurrentClass != overridden->getClassInterface() || 4378 overridden->isOverriding()) { 4379 CheckObjCMethodDirectOverrides(ObjCMethod, overridden); 4380 hasOverriddenMethodsInBaseOrProtocol = true; 4381 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) { 4382 // OverrideSearch will return as "overridden" the same method in the 4383 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to 4384 // check whether a category of a base class introduced a method with the 4385 // same selector, after the interface method declaration. 4386 // To avoid unnecessary lookups in the majority of cases, we use the 4387 // extra info bits in GlobalMethodPool to check whether there were any 4388 // category methods with this selector. 4389 GlobalMethodPool::iterator It = 4390 MethodPool.find(ObjCMethod->getSelector()); 4391 if (It != MethodPool.end()) { 4392 ObjCMethodList &List = 4393 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second; 4394 unsigned CategCount = List.getBits(); 4395 if (CategCount > 0) { 4396 // If the method is in a category we'll do lookup if there were at 4397 // least 2 category methods recorded, otherwise only one will do. 4398 if (CategCount > 1 || 4399 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) { 4400 OverrideSearch overrides(*this, overridden); 4401 for (ObjCMethodDecl *SuperOverridden : overrides) { 4402 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) || 4403 CurrentClass != SuperOverridden->getClassInterface()) { 4404 CheckObjCMethodDirectOverrides(ObjCMethod, SuperOverridden); 4405 hasOverriddenMethodsInBaseOrProtocol = true; 4406 overridden->setOverriding(true); 4407 break; 4408 } 4409 } 4410 } 4411 } 4412 } 4413 } 4414 } 4415 4416 // Propagate down the 'related result type' bit from overridden methods. 4417 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType()) 4418 ObjCMethod->setRelatedResultType(); 4419 4420 // Then merge the declarations. 4421 mergeObjCMethodDecls(ObjCMethod, overridden); 4422 4423 if (ObjCMethod->isImplicit() && overridden->isImplicit()) 4424 continue; // Conflicting properties are detected elsewhere. 4425 4426 // Check for overriding methods 4427 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) || 4428 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext())) 4429 CheckConflictingOverridingMethod(ObjCMethod, overridden, 4430 isa<ObjCProtocolDecl>(overridden->getDeclContext())); 4431 4432 if (CurrentClass && overridden->getDeclContext() != CurrentClass && 4433 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) && 4434 !overridden->isImplicit() /* not meant for properties */) { 4435 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(), 4436 E = ObjCMethod->param_end(); 4437 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(), 4438 PrevE = overridden->param_end(); 4439 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) { 4440 assert(PrevI != overridden->param_end() && "Param mismatch"); 4441 QualType T1 = Context.getCanonicalType((*ParamI)->getType()); 4442 QualType T2 = Context.getCanonicalType((*PrevI)->getType()); 4443 // If type of argument of method in this class does not match its 4444 // respective argument type in the super class method, issue warning; 4445 if (!Context.typesAreCompatible(T1, T2)) { 4446 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super) 4447 << T1 << T2; 4448 Diag(overridden->getLocation(), diag::note_previous_declaration); 4449 break; 4450 } 4451 } 4452 } 4453 } 4454 4455 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol); 4456 } 4457 4458 /// Merge type nullability from for a redeclaration of the same entity, 4459 /// producing the updated type of the redeclared entity. 4460 static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc, 4461 QualType type, 4462 bool usesCSKeyword, 4463 SourceLocation prevLoc, 4464 QualType prevType, 4465 bool prevUsesCSKeyword) { 4466 // Determine the nullability of both types. 4467 auto nullability = type->getNullability(S.Context); 4468 auto prevNullability = prevType->getNullability(S.Context); 4469 4470 // Easy case: both have nullability. 4471 if (nullability.hasValue() == prevNullability.hasValue()) { 4472 // Neither has nullability; continue. 4473 if (!nullability) 4474 return type; 4475 4476 // The nullabilities are equivalent; do nothing. 4477 if (*nullability == *prevNullability) 4478 return type; 4479 4480 // Complain about mismatched nullability. 4481 S.Diag(loc, diag::err_nullability_conflicting) 4482 << DiagNullabilityKind(*nullability, usesCSKeyword) 4483 << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword); 4484 return type; 4485 } 4486 4487 // If it's the redeclaration that has nullability, don't change anything. 4488 if (nullability) 4489 return type; 4490 4491 // Otherwise, provide the result with the same nullability. 4492 return S.Context.getAttributedType( 4493 AttributedType::getNullabilityAttrKind(*prevNullability), 4494 type, type); 4495 } 4496 4497 /// Merge information from the declaration of a method in the \@interface 4498 /// (or a category/extension) into the corresponding method in the 4499 /// @implementation (for a class or category). 4500 static void mergeInterfaceMethodToImpl(Sema &S, 4501 ObjCMethodDecl *method, 4502 ObjCMethodDecl *prevMethod) { 4503 // Merge the objc_requires_super attribute. 4504 if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() && 4505 !method->hasAttr<ObjCRequiresSuperAttr>()) { 4506 // merge the attribute into implementation. 4507 method->addAttr( 4508 ObjCRequiresSuperAttr::CreateImplicit(S.Context, 4509 method->getLocation())); 4510 } 4511 4512 // Merge nullability of the result type. 4513 QualType newReturnType 4514 = mergeTypeNullabilityForRedecl( 4515 S, method->getReturnTypeSourceRange().getBegin(), 4516 method->getReturnType(), 4517 method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability, 4518 prevMethod->getReturnTypeSourceRange().getBegin(), 4519 prevMethod->getReturnType(), 4520 prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability); 4521 method->setReturnType(newReturnType); 4522 4523 // Handle each of the parameters. 4524 unsigned numParams = method->param_size(); 4525 unsigned numPrevParams = prevMethod->param_size(); 4526 for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) { 4527 ParmVarDecl *param = method->param_begin()[i]; 4528 ParmVarDecl *prevParam = prevMethod->param_begin()[i]; 4529 4530 // Merge nullability. 4531 QualType newParamType 4532 = mergeTypeNullabilityForRedecl( 4533 S, param->getLocation(), param->getType(), 4534 param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability, 4535 prevParam->getLocation(), prevParam->getType(), 4536 prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability); 4537 param->setType(newParamType); 4538 } 4539 } 4540 4541 /// Verify that the method parameters/return value have types that are supported 4542 /// by the x86 target. 4543 static void checkObjCMethodX86VectorTypes(Sema &SemaRef, 4544 const ObjCMethodDecl *Method) { 4545 assert(SemaRef.getASTContext().getTargetInfo().getTriple().getArch() == 4546 llvm::Triple::x86 && 4547 "x86-specific check invoked for a different target"); 4548 SourceLocation Loc; 4549 QualType T; 4550 for (const ParmVarDecl *P : Method->parameters()) { 4551 if (P->getType()->isVectorType()) { 4552 Loc = P->getBeginLoc(); 4553 T = P->getType(); 4554 break; 4555 } 4556 } 4557 if (Loc.isInvalid()) { 4558 if (Method->getReturnType()->isVectorType()) { 4559 Loc = Method->getReturnTypeSourceRange().getBegin(); 4560 T = Method->getReturnType(); 4561 } else 4562 return; 4563 } 4564 4565 // Vector parameters/return values are not supported by objc_msgSend on x86 in 4566 // iOS < 9 and macOS < 10.11. 4567 const auto &Triple = SemaRef.getASTContext().getTargetInfo().getTriple(); 4568 VersionTuple AcceptedInVersion; 4569 if (Triple.getOS() == llvm::Triple::IOS) 4570 AcceptedInVersion = VersionTuple(/*Major=*/9); 4571 else if (Triple.isMacOSX()) 4572 AcceptedInVersion = VersionTuple(/*Major=*/10, /*Minor=*/11); 4573 else 4574 return; 4575 if (SemaRef.getASTContext().getTargetInfo().getPlatformMinVersion() >= 4576 AcceptedInVersion) 4577 return; 4578 SemaRef.Diag(Loc, diag::err_objc_method_unsupported_param_ret_type) 4579 << T << (Method->getReturnType()->isVectorType() ? /*return value*/ 1 4580 : /*parameter*/ 0) 4581 << (Triple.isMacOSX() ? "macOS 10.11" : "iOS 9"); 4582 } 4583 4584 static void mergeObjCDirectMembers(Sema &S, Decl *CD, ObjCMethodDecl *Method) { 4585 if (!Method->isDirectMethod() && !Method->hasAttr<UnavailableAttr>() && 4586 CD->hasAttr<ObjCDirectMembersAttr>()) { 4587 Method->addAttr( 4588 ObjCDirectAttr::CreateImplicit(S.Context, Method->getLocation())); 4589 } 4590 } 4591 4592 static void checkObjCDirectMethodClashes(Sema &S, ObjCInterfaceDecl *IDecl, 4593 ObjCMethodDecl *Method, 4594 ObjCImplDecl *ImpDecl = nullptr) { 4595 auto Sel = Method->getSelector(); 4596 bool isInstance = Method->isInstanceMethod(); 4597 bool diagnosed = false; 4598 4599 auto diagClash = [&](const ObjCMethodDecl *IMD) { 4600 if (diagnosed || IMD->isImplicit()) 4601 return; 4602 if (Method->isDirectMethod() || IMD->isDirectMethod()) { 4603 S.Diag(Method->getLocation(), diag::err_objc_direct_duplicate_decl) 4604 << Method->isDirectMethod() << /* method */ 0 << IMD->isDirectMethod() 4605 << Method->getDeclName(); 4606 S.Diag(IMD->getLocation(), diag::note_previous_declaration); 4607 diagnosed = true; 4608 } 4609 }; 4610 4611 // Look for any other declaration of this method anywhere we can see in this 4612 // compilation unit. 4613 // 4614 // We do not use IDecl->lookupMethod() because we have specific needs: 4615 // 4616 // - we absolutely do not need to walk protocols, because 4617 // diag::err_objc_direct_on_protocol has already been emitted 4618 // during parsing if there's a conflict, 4619 // 4620 // - when we do not find a match in a given @interface container, 4621 // we need to attempt looking it up in the @implementation block if the 4622 // translation unit sees it to find more clashes. 4623 4624 if (auto *IMD = IDecl->getMethod(Sel, isInstance)) 4625 diagClash(IMD); 4626 else if (auto *Impl = IDecl->getImplementation()) 4627 if (Impl != ImpDecl) 4628 if (auto *IMD = IDecl->getImplementation()->getMethod(Sel, isInstance)) 4629 diagClash(IMD); 4630 4631 for (const auto *Cat : IDecl->visible_categories()) 4632 if (auto *IMD = Cat->getMethod(Sel, isInstance)) 4633 diagClash(IMD); 4634 else if (auto CatImpl = Cat->getImplementation()) 4635 if (CatImpl != ImpDecl) 4636 if (auto *IMD = Cat->getMethod(Sel, isInstance)) 4637 diagClash(IMD); 4638 } 4639 4640 Decl *Sema::ActOnMethodDeclaration( 4641 Scope *S, SourceLocation MethodLoc, SourceLocation EndLoc, 4642 tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType, 4643 ArrayRef<SourceLocation> SelectorLocs, Selector Sel, 4644 // optional arguments. The number of types/arguments is obtained 4645 // from the Sel.getNumArgs(). 4646 ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo, 4647 unsigned CNumArgs, // c-style args 4648 const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodDeclKind, 4649 bool isVariadic, bool MethodDefinition) { 4650 // Make sure we can establish a context for the method. 4651 if (!CurContext->isObjCContainer()) { 4652 Diag(MethodLoc, diag::err_missing_method_context); 4653 return nullptr; 4654 } 4655 4656 Decl *ClassDecl = cast<ObjCContainerDecl>(CurContext); 4657 QualType resultDeclType; 4658 4659 bool HasRelatedResultType = false; 4660 TypeSourceInfo *ReturnTInfo = nullptr; 4661 if (ReturnType) { 4662 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo); 4663 4664 if (CheckFunctionReturnType(resultDeclType, MethodLoc)) 4665 return nullptr; 4666 4667 QualType bareResultType = resultDeclType; 4668 (void)AttributedType::stripOuterNullability(bareResultType); 4669 HasRelatedResultType = (bareResultType == Context.getObjCInstanceType()); 4670 } else { // get the type for "id". 4671 resultDeclType = Context.getObjCIdType(); 4672 Diag(MethodLoc, diag::warn_missing_method_return_type) 4673 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)"); 4674 } 4675 4676 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create( 4677 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext, 4678 MethodType == tok::minus, isVariadic, 4679 /*isPropertyAccessor=*/false, /*isSynthesizedAccessorStub=*/false, 4680 /*isImplicitlyDeclared=*/false, /*isDefined=*/false, 4681 MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional 4682 : ObjCMethodDecl::Required, 4683 HasRelatedResultType); 4684 4685 SmallVector<ParmVarDecl*, 16> Params; 4686 4687 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) { 4688 QualType ArgType; 4689 TypeSourceInfo *DI; 4690 4691 if (!ArgInfo[i].Type) { 4692 ArgType = Context.getObjCIdType(); 4693 DI = nullptr; 4694 } else { 4695 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI); 4696 } 4697 4698 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc, 4699 LookupOrdinaryName, forRedeclarationInCurContext()); 4700 LookupName(R, S); 4701 if (R.isSingleResult()) { 4702 NamedDecl *PrevDecl = R.getFoundDecl(); 4703 if (S->isDeclScope(PrevDecl)) { 4704 Diag(ArgInfo[i].NameLoc, 4705 (MethodDefinition ? diag::warn_method_param_redefinition 4706 : diag::warn_method_param_declaration)) 4707 << ArgInfo[i].Name; 4708 Diag(PrevDecl->getLocation(), 4709 diag::note_previous_declaration); 4710 } 4711 } 4712 4713 SourceLocation StartLoc = DI 4714 ? DI->getTypeLoc().getBeginLoc() 4715 : ArgInfo[i].NameLoc; 4716 4717 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc, 4718 ArgInfo[i].NameLoc, ArgInfo[i].Name, 4719 ArgType, DI, SC_None); 4720 4721 Param->setObjCMethodScopeInfo(i); 4722 4723 Param->setObjCDeclQualifier( 4724 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier())); 4725 4726 // Apply the attributes to the parameter. 4727 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs); 4728 AddPragmaAttributes(TUScope, Param); 4729 4730 if (Param->hasAttr<BlocksAttr>()) { 4731 Diag(Param->getLocation(), diag::err_block_on_nonlocal); 4732 Param->setInvalidDecl(); 4733 } 4734 S->AddDecl(Param); 4735 IdResolver.AddDecl(Param); 4736 4737 Params.push_back(Param); 4738 } 4739 4740 for (unsigned i = 0, e = CNumArgs; i != e; ++i) { 4741 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param); 4742 QualType ArgType = Param->getType(); 4743 if (ArgType.isNull()) 4744 ArgType = Context.getObjCIdType(); 4745 else 4746 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]). 4747 ArgType = Context.getAdjustedParameterType(ArgType); 4748 4749 Param->setDeclContext(ObjCMethod); 4750 Params.push_back(Param); 4751 } 4752 4753 ObjCMethod->setMethodParams(Context, Params, SelectorLocs); 4754 ObjCMethod->setObjCDeclQualifier( 4755 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier())); 4756 4757 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList); 4758 AddPragmaAttributes(TUScope, ObjCMethod); 4759 4760 // Add the method now. 4761 const ObjCMethodDecl *PrevMethod = nullptr; 4762 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) { 4763 if (MethodType == tok::minus) { 4764 PrevMethod = ImpDecl->getInstanceMethod(Sel); 4765 ImpDecl->addInstanceMethod(ObjCMethod); 4766 } else { 4767 PrevMethod = ImpDecl->getClassMethod(Sel); 4768 ImpDecl->addClassMethod(ObjCMethod); 4769 } 4770 4771 // If this method overrides a previous @synthesize declaration, 4772 // register it with the property. Linear search through all 4773 // properties here, because the autosynthesized stub hasn't been 4774 // made visible yet, so it can be overriden by a later 4775 // user-specified implementation. 4776 for (ObjCPropertyImplDecl *PropertyImpl : ImpDecl->property_impls()) { 4777 if (auto *Setter = PropertyImpl->getSetterMethodDecl()) 4778 if (Setter->getSelector() == Sel && 4779 Setter->isInstanceMethod() == ObjCMethod->isInstanceMethod()) { 4780 assert(Setter->isSynthesizedAccessorStub() && "autosynth stub expected"); 4781 PropertyImpl->setSetterMethodDecl(ObjCMethod); 4782 } 4783 if (auto *Getter = PropertyImpl->getGetterMethodDecl()) 4784 if (Getter->getSelector() == Sel && 4785 Getter->isInstanceMethod() == ObjCMethod->isInstanceMethod()) { 4786 assert(Getter->isSynthesizedAccessorStub() && "autosynth stub expected"); 4787 PropertyImpl->setGetterMethodDecl(ObjCMethod); 4788 break; 4789 } 4790 } 4791 4792 // A method is either tagged direct explicitly, or inherits it from its 4793 // canonical declaration. 4794 // 4795 // We have to do the merge upfront and not in mergeInterfaceMethodToImpl() 4796 // because IDecl->lookupMethod() returns more possible matches than just 4797 // the canonical declaration. 4798 if (!ObjCMethod->isDirectMethod()) { 4799 const ObjCMethodDecl *CanonicalMD = ObjCMethod->getCanonicalDecl(); 4800 if (const auto *attr = CanonicalMD->getAttr<ObjCDirectAttr>()) { 4801 ObjCMethod->addAttr( 4802 ObjCDirectAttr::CreateImplicit(Context, attr->getLocation())); 4803 } 4804 } 4805 4806 // Merge information from the @interface declaration into the 4807 // @implementation. 4808 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) { 4809 if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(), 4810 ObjCMethod->isInstanceMethod())) { 4811 mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD); 4812 4813 // The Idecl->lookupMethod() above will find declarations for ObjCMethod 4814 // in one of these places: 4815 // 4816 // (1) the canonical declaration in an @interface container paired 4817 // with the ImplDecl, 4818 // (2) non canonical declarations in @interface not paired with the 4819 // ImplDecl for the same Class, 4820 // (3) any superclass container. 4821 // 4822 // Direct methods only allow for canonical declarations in the matching 4823 // container (case 1). 4824 // 4825 // Direct methods overriding a superclass declaration (case 3) is 4826 // handled during overrides checks in CheckObjCMethodOverrides(). 4827 // 4828 // We deal with same-class container mismatches (Case 2) here. 4829 if (IDecl == IMD->getClassInterface()) { 4830 auto diagContainerMismatch = [&] { 4831 int decl = 0, impl = 0; 4832 4833 if (auto *Cat = dyn_cast<ObjCCategoryDecl>(IMD->getDeclContext())) 4834 decl = Cat->IsClassExtension() ? 1 : 2; 4835 4836 if (isa<ObjCCategoryImplDecl>(ImpDecl)) 4837 impl = 1 + (decl != 0); 4838 4839 Diag(ObjCMethod->getLocation(), 4840 diag::err_objc_direct_impl_decl_mismatch) 4841 << decl << impl; 4842 Diag(IMD->getLocation(), diag::note_previous_declaration); 4843 }; 4844 4845 if (const auto *attr = ObjCMethod->getAttr<ObjCDirectAttr>()) { 4846 if (ObjCMethod->getCanonicalDecl() != IMD) { 4847 diagContainerMismatch(); 4848 } else if (!IMD->isDirectMethod()) { 4849 Diag(attr->getLocation(), diag::err_objc_direct_missing_on_decl); 4850 Diag(IMD->getLocation(), diag::note_previous_declaration); 4851 } 4852 } else if (const auto *attr = IMD->getAttr<ObjCDirectAttr>()) { 4853 if (ObjCMethod->getCanonicalDecl() != IMD) { 4854 diagContainerMismatch(); 4855 } else { 4856 ObjCMethod->addAttr( 4857 ObjCDirectAttr::CreateImplicit(Context, attr->getLocation())); 4858 } 4859 } 4860 } 4861 4862 // Warn about defining -dealloc in a category. 4863 if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() && 4864 ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) { 4865 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category) 4866 << ObjCMethod->getDeclName(); 4867 } 4868 } else { 4869 mergeObjCDirectMembers(*this, ClassDecl, ObjCMethod); 4870 checkObjCDirectMethodClashes(*this, IDecl, ObjCMethod, ImpDecl); 4871 } 4872 4873 // Warn if a method declared in a protocol to which a category or 4874 // extension conforms is non-escaping and the implementation's method is 4875 // escaping. 4876 for (auto *C : IDecl->visible_categories()) 4877 for (auto &P : C->protocols()) 4878 if (auto *IMD = P->lookupMethod(ObjCMethod->getSelector(), 4879 ObjCMethod->isInstanceMethod())) { 4880 assert(ObjCMethod->parameters().size() == 4881 IMD->parameters().size() && 4882 "Methods have different number of parameters"); 4883 auto OI = IMD->param_begin(), OE = IMD->param_end(); 4884 auto NI = ObjCMethod->param_begin(); 4885 for (; OI != OE; ++OI, ++NI) 4886 diagnoseNoescape(*NI, *OI, C, P, *this); 4887 } 4888 } 4889 } else { 4890 if (!isa<ObjCProtocolDecl>(ClassDecl)) { 4891 mergeObjCDirectMembers(*this, ClassDecl, ObjCMethod); 4892 4893 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl); 4894 if (!IDecl) 4895 IDecl = cast<ObjCCategoryDecl>(ClassDecl)->getClassInterface(); 4896 // For valid code, we should always know the primary interface 4897 // declaration by now, however for invalid code we'll keep parsing 4898 // but we won't find the primary interface and IDecl will be nil. 4899 if (IDecl) 4900 checkObjCDirectMethodClashes(*this, IDecl, ObjCMethod); 4901 } 4902 4903 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod); 4904 } 4905 4906 if (PrevMethod) { 4907 // You can never have two method definitions with the same name. 4908 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl) 4909 << ObjCMethod->getDeclName(); 4910 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 4911 ObjCMethod->setInvalidDecl(); 4912 return ObjCMethod; 4913 } 4914 4915 // If this Objective-C method does not have a related result type, but we 4916 // are allowed to infer related result types, try to do so based on the 4917 // method family. 4918 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl); 4919 if (!CurrentClass) { 4920 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl)) 4921 CurrentClass = Cat->getClassInterface(); 4922 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl)) 4923 CurrentClass = Impl->getClassInterface(); 4924 else if (ObjCCategoryImplDecl *CatImpl 4925 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) 4926 CurrentClass = CatImpl->getClassInterface(); 4927 } 4928 4929 ResultTypeCompatibilityKind RTC 4930 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass); 4931 4932 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC); 4933 4934 bool ARCError = false; 4935 if (getLangOpts().ObjCAutoRefCount) 4936 ARCError = CheckARCMethodDecl(ObjCMethod); 4937 4938 // Infer the related result type when possible. 4939 if (!ARCError && RTC == Sema::RTC_Compatible && 4940 !ObjCMethod->hasRelatedResultType() && 4941 LangOpts.ObjCInferRelatedResultType) { 4942 bool InferRelatedResultType = false; 4943 switch (ObjCMethod->getMethodFamily()) { 4944 case OMF_None: 4945 case OMF_copy: 4946 case OMF_dealloc: 4947 case OMF_finalize: 4948 case OMF_mutableCopy: 4949 case OMF_release: 4950 case OMF_retainCount: 4951 case OMF_initialize: 4952 case OMF_performSelector: 4953 break; 4954 4955 case OMF_alloc: 4956 case OMF_new: 4957 InferRelatedResultType = ObjCMethod->isClassMethod(); 4958 break; 4959 4960 case OMF_init: 4961 case OMF_autorelease: 4962 case OMF_retain: 4963 case OMF_self: 4964 InferRelatedResultType = ObjCMethod->isInstanceMethod(); 4965 break; 4966 } 4967 4968 if (InferRelatedResultType && 4969 !ObjCMethod->getReturnType()->isObjCIndependentClassType()) 4970 ObjCMethod->setRelatedResultType(); 4971 } 4972 4973 if (MethodDefinition && 4974 Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86) 4975 checkObjCMethodX86VectorTypes(*this, ObjCMethod); 4976 4977 // + load method cannot have availability attributes. It get called on 4978 // startup, so it has to have the availability of the deployment target. 4979 if (const auto *attr = ObjCMethod->getAttr<AvailabilityAttr>()) { 4980 if (ObjCMethod->isClassMethod() && 4981 ObjCMethod->getSelector().getAsString() == "load") { 4982 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 4983 << 0; 4984 ObjCMethod->dropAttr<AvailabilityAttr>(); 4985 } 4986 } 4987 4988 // Insert the invisible arguments, self and _cmd! 4989 ObjCMethod->createImplicitParams(Context, ObjCMethod->getClassInterface()); 4990 4991 ActOnDocumentableDecl(ObjCMethod); 4992 4993 return ObjCMethod; 4994 } 4995 4996 bool Sema::CheckObjCDeclScope(Decl *D) { 4997 // Following is also an error. But it is caused by a missing @end 4998 // and diagnostic is issued elsewhere. 4999 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext())) 5000 return false; 5001 5002 // If we switched context to translation unit while we are still lexically in 5003 // an objc container, it means the parser missed emitting an error. 5004 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext())) 5005 return false; 5006 5007 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope); 5008 D->setInvalidDecl(); 5009 5010 return true; 5011 } 5012 5013 /// Called whenever \@defs(ClassName) is encountered in the source. Inserts the 5014 /// instance variables of ClassName into Decls. 5015 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, 5016 IdentifierInfo *ClassName, 5017 SmallVectorImpl<Decl*> &Decls) { 5018 // Check that ClassName is a valid class 5019 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart); 5020 if (!Class) { 5021 Diag(DeclStart, diag::err_undef_interface) << ClassName; 5022 return; 5023 } 5024 if (LangOpts.ObjCRuntime.isNonFragile()) { 5025 Diag(DeclStart, diag::err_atdef_nonfragile_interface); 5026 return; 5027 } 5028 5029 // Collect the instance variables 5030 SmallVector<const ObjCIvarDecl*, 32> Ivars; 5031 Context.DeepCollectObjCIvars(Class, true, Ivars); 5032 // For each ivar, create a fresh ObjCAtDefsFieldDecl. 5033 for (unsigned i = 0; i < Ivars.size(); i++) { 5034 const FieldDecl* ID = Ivars[i]; 5035 RecordDecl *Record = dyn_cast<RecordDecl>(TagD); 5036 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record, 5037 /*FIXME: StartL=*/ID->getLocation(), 5038 ID->getLocation(), 5039 ID->getIdentifier(), ID->getType(), 5040 ID->getBitWidth()); 5041 Decls.push_back(FD); 5042 } 5043 5044 // Introduce all of these fields into the appropriate scope. 5045 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin(); 5046 D != Decls.end(); ++D) { 5047 FieldDecl *FD = cast<FieldDecl>(*D); 5048 if (getLangOpts().CPlusPlus) 5049 PushOnScopeChains(FD, S); 5050 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD)) 5051 Record->addDecl(FD); 5052 } 5053 } 5054 5055 /// Build a type-check a new Objective-C exception variable declaration. 5056 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T, 5057 SourceLocation StartLoc, 5058 SourceLocation IdLoc, 5059 IdentifierInfo *Id, 5060 bool Invalid) { 5061 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 5062 // duration shall not be qualified by an address-space qualifier." 5063 // Since all parameters have automatic store duration, they can not have 5064 // an address space. 5065 if (T.getAddressSpace() != LangAS::Default) { 5066 Diag(IdLoc, diag::err_arg_with_address_space); 5067 Invalid = true; 5068 } 5069 5070 // An @catch parameter must be an unqualified object pointer type; 5071 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"? 5072 if (Invalid) { 5073 // Don't do any further checking. 5074 } else if (T->isDependentType()) { 5075 // Okay: we don't know what this type will instantiate to. 5076 } else if (T->isObjCQualifiedIdType()) { 5077 Invalid = true; 5078 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm); 5079 } else if (T->isObjCIdType()) { 5080 // Okay: we don't know what this type will instantiate to. 5081 } else if (!T->isObjCObjectPointerType()) { 5082 Invalid = true; 5083 Diag(IdLoc, diag::err_catch_param_not_objc_type); 5084 } else if (!T->castAs<ObjCObjectPointerType>()->getInterfaceType()) { 5085 Invalid = true; 5086 Diag(IdLoc, diag::err_catch_param_not_objc_type); 5087 } 5088 5089 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id, 5090 T, TInfo, SC_None); 5091 New->setExceptionVariable(true); 5092 5093 // In ARC, infer 'retaining' for variables of retainable type. 5094 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New)) 5095 Invalid = true; 5096 5097 if (Invalid) 5098 New->setInvalidDecl(); 5099 return New; 5100 } 5101 5102 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) { 5103 const DeclSpec &DS = D.getDeclSpec(); 5104 5105 // We allow the "register" storage class on exception variables because 5106 // GCC did, but we drop it completely. Any other storage class is an error. 5107 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 5108 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm) 5109 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc())); 5110 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 5111 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm) 5112 << DeclSpec::getSpecifierName(SCS); 5113 } 5114 if (DS.isInlineSpecified()) 5115 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 5116 << getLangOpts().CPlusPlus17; 5117 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 5118 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5119 diag::err_invalid_thread) 5120 << DeclSpec::getSpecifierName(TSCS); 5121 D.getMutableDeclSpec().ClearStorageClassSpecs(); 5122 5123 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5124 5125 // Check that there are no default arguments inside the type of this 5126 // exception object (C++ only). 5127 if (getLangOpts().CPlusPlus) 5128 CheckExtraCXXDefaultArguments(D); 5129 5130 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5131 QualType ExceptionType = TInfo->getType(); 5132 5133 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType, 5134 D.getSourceRange().getBegin(), 5135 D.getIdentifierLoc(), 5136 D.getIdentifier(), 5137 D.isInvalidType()); 5138 5139 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 5140 if (D.getCXXScopeSpec().isSet()) { 5141 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm) 5142 << D.getCXXScopeSpec().getRange(); 5143 New->setInvalidDecl(); 5144 } 5145 5146 // Add the parameter declaration into this scope. 5147 S->AddDecl(New); 5148 if (D.getIdentifier()) 5149 IdResolver.AddDecl(New); 5150 5151 ProcessDeclAttributes(S, New, D); 5152 5153 if (New->hasAttr<BlocksAttr>()) 5154 Diag(New->getLocation(), diag::err_block_on_nonlocal); 5155 return New; 5156 } 5157 5158 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require 5159 /// initialization. 5160 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, 5161 SmallVectorImpl<ObjCIvarDecl*> &Ivars) { 5162 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv; 5163 Iv= Iv->getNextIvar()) { 5164 QualType QT = Context.getBaseElementType(Iv->getType()); 5165 if (QT->isRecordType()) 5166 Ivars.push_back(Iv); 5167 } 5168 } 5169 5170 void Sema::DiagnoseUseOfUnimplementedSelectors() { 5171 // Load referenced selectors from the external source. 5172 if (ExternalSource) { 5173 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels; 5174 ExternalSource->ReadReferencedSelectors(Sels); 5175 for (unsigned I = 0, N = Sels.size(); I != N; ++I) 5176 ReferencedSelectors[Sels[I].first] = Sels[I].second; 5177 } 5178 5179 // Warning will be issued only when selector table is 5180 // generated (which means there is at lease one implementation 5181 // in the TU). This is to match gcc's behavior. 5182 if (ReferencedSelectors.empty() || 5183 !Context.AnyObjCImplementation()) 5184 return; 5185 for (auto &SelectorAndLocation : ReferencedSelectors) { 5186 Selector Sel = SelectorAndLocation.first; 5187 SourceLocation Loc = SelectorAndLocation.second; 5188 if (!LookupImplementedMethodInGlobalPool(Sel)) 5189 Diag(Loc, diag::warn_unimplemented_selector) << Sel; 5190 } 5191 } 5192 5193 ObjCIvarDecl * 5194 Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, 5195 const ObjCPropertyDecl *&PDecl) const { 5196 if (Method->isClassMethod()) 5197 return nullptr; 5198 const ObjCInterfaceDecl *IDecl = Method->getClassInterface(); 5199 if (!IDecl) 5200 return nullptr; 5201 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true, 5202 /*shallowCategoryLookup=*/false, 5203 /*followSuper=*/false); 5204 if (!Method || !Method->isPropertyAccessor()) 5205 return nullptr; 5206 if ((PDecl = Method->findPropertyDecl())) 5207 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) { 5208 // property backing ivar must belong to property's class 5209 // or be a private ivar in class's implementation. 5210 // FIXME. fix the const-ness issue. 5211 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable( 5212 IV->getIdentifier()); 5213 return IV; 5214 } 5215 return nullptr; 5216 } 5217 5218 namespace { 5219 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property 5220 /// accessor references the backing ivar. 5221 class UnusedBackingIvarChecker : 5222 public RecursiveASTVisitor<UnusedBackingIvarChecker> { 5223 public: 5224 Sema &S; 5225 const ObjCMethodDecl *Method; 5226 const ObjCIvarDecl *IvarD; 5227 bool AccessedIvar; 5228 bool InvokedSelfMethod; 5229 5230 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method, 5231 const ObjCIvarDecl *IvarD) 5232 : S(S), Method(Method), IvarD(IvarD), 5233 AccessedIvar(false), InvokedSelfMethod(false) { 5234 assert(IvarD); 5235 } 5236 5237 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 5238 if (E->getDecl() == IvarD) { 5239 AccessedIvar = true; 5240 return false; 5241 } 5242 return true; 5243 } 5244 5245 bool VisitObjCMessageExpr(ObjCMessageExpr *E) { 5246 if (E->getReceiverKind() == ObjCMessageExpr::Instance && 5247 S.isSelfExpr(E->getInstanceReceiver(), Method)) { 5248 InvokedSelfMethod = true; 5249 } 5250 return true; 5251 } 5252 }; 5253 } // end anonymous namespace 5254 5255 void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S, 5256 const ObjCImplementationDecl *ImplD) { 5257 if (S->hasUnrecoverableErrorOccurred()) 5258 return; 5259 5260 for (const auto *CurMethod : ImplD->instance_methods()) { 5261 unsigned DIAG = diag::warn_unused_property_backing_ivar; 5262 SourceLocation Loc = CurMethod->getLocation(); 5263 if (Diags.isIgnored(DIAG, Loc)) 5264 continue; 5265 5266 const ObjCPropertyDecl *PDecl; 5267 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl); 5268 if (!IV) 5269 continue; 5270 5271 if (CurMethod->isSynthesizedAccessorStub()) 5272 continue; 5273 5274 UnusedBackingIvarChecker Checker(*this, CurMethod, IV); 5275 Checker.TraverseStmt(CurMethod->getBody()); 5276 if (Checker.AccessedIvar) 5277 continue; 5278 5279 // Do not issue this warning if backing ivar is used somewhere and accessor 5280 // implementation makes a self call. This is to prevent false positive in 5281 // cases where the ivar is accessed by another method that the accessor 5282 // delegates to. 5283 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) { 5284 Diag(Loc, DIAG) << IV; 5285 Diag(PDecl->getLocation(), diag::note_property_declare); 5286 } 5287 } 5288 } 5289