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