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