1 //===--- SemaObjCProperty.cpp - Semantic Analysis for ObjC @property ------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for Objective C @property and 10 // @synthesize declarations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/SemaInternal.h" 15 #include "clang/AST/ASTMutationListener.h" 16 #include "clang/AST/DeclObjC.h" 17 #include "clang/AST/ExprCXX.h" 18 #include "clang/AST/ExprObjC.h" 19 #include "clang/Basic/SourceManager.h" 20 #include "clang/Lex/Lexer.h" 21 #include "clang/Lex/Preprocessor.h" 22 #include "clang/Sema/Initialization.h" 23 #include "llvm/ADT/DenseSet.h" 24 #include "llvm/ADT/SmallString.h" 25 26 using namespace clang; 27 28 //===----------------------------------------------------------------------===// 29 // Grammar actions. 30 //===----------------------------------------------------------------------===// 31 32 /// getImpliedARCOwnership - Given a set of property attributes and a 33 /// type, infer an expected lifetime. The type's ownership qualification 34 /// is not considered. 35 /// 36 /// Returns OCL_None if the attributes as stated do not imply an ownership. 37 /// Never returns OCL_Autoreleasing. 38 static Qualifiers::ObjCLifetime getImpliedARCOwnership( 39 ObjCPropertyDecl::PropertyAttributeKind attrs, 40 QualType type) { 41 // retain, strong, copy, weak, and unsafe_unretained are only legal 42 // on properties of retainable pointer type. 43 if (attrs & (ObjCPropertyDecl::OBJC_PR_retain | 44 ObjCPropertyDecl::OBJC_PR_strong | 45 ObjCPropertyDecl::OBJC_PR_copy)) { 46 return Qualifiers::OCL_Strong; 47 } else if (attrs & ObjCPropertyDecl::OBJC_PR_weak) { 48 return Qualifiers::OCL_Weak; 49 } else if (attrs & ObjCPropertyDecl::OBJC_PR_unsafe_unretained) { 50 return Qualifiers::OCL_ExplicitNone; 51 } 52 53 // assign can appear on other types, so we have to check the 54 // property type. 55 if (attrs & ObjCPropertyDecl::OBJC_PR_assign && 56 type->isObjCRetainableType()) { 57 return Qualifiers::OCL_ExplicitNone; 58 } 59 60 return Qualifiers::OCL_None; 61 } 62 63 /// Check the internal consistency of a property declaration with 64 /// an explicit ownership qualifier. 65 static void checkPropertyDeclWithOwnership(Sema &S, 66 ObjCPropertyDecl *property) { 67 if (property->isInvalidDecl()) return; 68 69 ObjCPropertyDecl::PropertyAttributeKind propertyKind 70 = property->getPropertyAttributes(); 71 Qualifiers::ObjCLifetime propertyLifetime 72 = property->getType().getObjCLifetime(); 73 74 assert(propertyLifetime != Qualifiers::OCL_None); 75 76 Qualifiers::ObjCLifetime expectedLifetime 77 = getImpliedARCOwnership(propertyKind, property->getType()); 78 if (!expectedLifetime) { 79 // We have a lifetime qualifier but no dominating property 80 // attribute. That's okay, but restore reasonable invariants by 81 // setting the property attribute according to the lifetime 82 // qualifier. 83 ObjCPropertyDecl::PropertyAttributeKind attr; 84 if (propertyLifetime == Qualifiers::OCL_Strong) { 85 attr = ObjCPropertyDecl::OBJC_PR_strong; 86 } else if (propertyLifetime == Qualifiers::OCL_Weak) { 87 attr = ObjCPropertyDecl::OBJC_PR_weak; 88 } else { 89 assert(propertyLifetime == Qualifiers::OCL_ExplicitNone); 90 attr = ObjCPropertyDecl::OBJC_PR_unsafe_unretained; 91 } 92 property->setPropertyAttributes(attr); 93 return; 94 } 95 96 if (propertyLifetime == expectedLifetime) return; 97 98 property->setInvalidDecl(); 99 S.Diag(property->getLocation(), 100 diag::err_arc_inconsistent_property_ownership) 101 << property->getDeclName() 102 << expectedLifetime 103 << propertyLifetime; 104 } 105 106 /// Check this Objective-C property against a property declared in the 107 /// given protocol. 108 static void 109 CheckPropertyAgainstProtocol(Sema &S, ObjCPropertyDecl *Prop, 110 ObjCProtocolDecl *Proto, 111 llvm::SmallPtrSetImpl<ObjCProtocolDecl *> &Known) { 112 // Have we seen this protocol before? 113 if (!Known.insert(Proto).second) 114 return; 115 116 // Look for a property with the same name. 117 DeclContext::lookup_result R = Proto->lookup(Prop->getDeclName()); 118 for (unsigned I = 0, N = R.size(); I != N; ++I) { 119 if (ObjCPropertyDecl *ProtoProp = dyn_cast<ObjCPropertyDecl>(R[I])) { 120 S.DiagnosePropertyMismatch(Prop, ProtoProp, Proto->getIdentifier(), true); 121 return; 122 } 123 } 124 125 // Check this property against any protocols we inherit. 126 for (auto *P : Proto->protocols()) 127 CheckPropertyAgainstProtocol(S, Prop, P, Known); 128 } 129 130 static unsigned deducePropertyOwnershipFromType(Sema &S, QualType T) { 131 // In GC mode, just look for the __weak qualifier. 132 if (S.getLangOpts().getGC() != LangOptions::NonGC) { 133 if (T.isObjCGCWeak()) return ObjCDeclSpec::DQ_PR_weak; 134 135 // In ARC/MRC, look for an explicit ownership qualifier. 136 // For some reason, this only applies to __weak. 137 } else if (auto ownership = T.getObjCLifetime()) { 138 switch (ownership) { 139 case Qualifiers::OCL_Weak: 140 return ObjCDeclSpec::DQ_PR_weak; 141 case Qualifiers::OCL_Strong: 142 return ObjCDeclSpec::DQ_PR_strong; 143 case Qualifiers::OCL_ExplicitNone: 144 return ObjCDeclSpec::DQ_PR_unsafe_unretained; 145 case Qualifiers::OCL_Autoreleasing: 146 case Qualifiers::OCL_None: 147 return 0; 148 } 149 llvm_unreachable("bad qualifier"); 150 } 151 152 return 0; 153 } 154 155 static const unsigned OwnershipMask = 156 (ObjCPropertyDecl::OBJC_PR_assign | 157 ObjCPropertyDecl::OBJC_PR_retain | 158 ObjCPropertyDecl::OBJC_PR_copy | 159 ObjCPropertyDecl::OBJC_PR_weak | 160 ObjCPropertyDecl::OBJC_PR_strong | 161 ObjCPropertyDecl::OBJC_PR_unsafe_unretained); 162 163 static unsigned getOwnershipRule(unsigned attr) { 164 unsigned result = attr & OwnershipMask; 165 166 // From an ownership perspective, assign and unsafe_unretained are 167 // identical; make sure one also implies the other. 168 if (result & (ObjCPropertyDecl::OBJC_PR_assign | 169 ObjCPropertyDecl::OBJC_PR_unsafe_unretained)) { 170 result |= ObjCPropertyDecl::OBJC_PR_assign | 171 ObjCPropertyDecl::OBJC_PR_unsafe_unretained; 172 } 173 174 return result; 175 } 176 177 Decl *Sema::ActOnProperty(Scope *S, SourceLocation AtLoc, 178 SourceLocation LParenLoc, 179 FieldDeclarator &FD, 180 ObjCDeclSpec &ODS, 181 Selector GetterSel, 182 Selector SetterSel, 183 tok::ObjCKeywordKind MethodImplKind, 184 DeclContext *lexicalDC) { 185 unsigned Attributes = ODS.getPropertyAttributes(); 186 FD.D.setObjCWeakProperty((Attributes & ObjCDeclSpec::DQ_PR_weak) != 0); 187 TypeSourceInfo *TSI = GetTypeForDeclarator(FD.D, S); 188 QualType T = TSI->getType(); 189 if (!getOwnershipRule(Attributes)) { 190 Attributes |= deducePropertyOwnershipFromType(*this, T); 191 } 192 bool isReadWrite = ((Attributes & ObjCDeclSpec::DQ_PR_readwrite) || 193 // default is readwrite! 194 !(Attributes & ObjCDeclSpec::DQ_PR_readonly)); 195 196 // Proceed with constructing the ObjCPropertyDecls. 197 ObjCContainerDecl *ClassDecl = cast<ObjCContainerDecl>(CurContext); 198 ObjCPropertyDecl *Res = nullptr; 199 if (ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(ClassDecl)) { 200 if (CDecl->IsClassExtension()) { 201 Res = HandlePropertyInClassExtension(S, AtLoc, LParenLoc, 202 FD, 203 GetterSel, ODS.getGetterNameLoc(), 204 SetterSel, ODS.getSetterNameLoc(), 205 isReadWrite, Attributes, 206 ODS.getPropertyAttributes(), 207 T, TSI, MethodImplKind); 208 if (!Res) 209 return nullptr; 210 } 211 } 212 213 if (!Res) { 214 Res = CreatePropertyDecl(S, ClassDecl, AtLoc, LParenLoc, FD, 215 GetterSel, ODS.getGetterNameLoc(), SetterSel, 216 ODS.getSetterNameLoc(), isReadWrite, Attributes, 217 ODS.getPropertyAttributes(), T, TSI, 218 MethodImplKind); 219 if (lexicalDC) 220 Res->setLexicalDeclContext(lexicalDC); 221 } 222 223 // Validate the attributes on the @property. 224 CheckObjCPropertyAttributes(Res, AtLoc, Attributes, 225 (isa<ObjCInterfaceDecl>(ClassDecl) || 226 isa<ObjCProtocolDecl>(ClassDecl))); 227 228 // Check consistency if the type has explicit ownership qualification. 229 if (Res->getType().getObjCLifetime()) 230 checkPropertyDeclWithOwnership(*this, Res); 231 232 llvm::SmallPtrSet<ObjCProtocolDecl *, 16> KnownProtos; 233 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) { 234 // For a class, compare the property against a property in our superclass. 235 bool FoundInSuper = false; 236 ObjCInterfaceDecl *CurrentInterfaceDecl = IFace; 237 while (ObjCInterfaceDecl *Super = CurrentInterfaceDecl->getSuperClass()) { 238 DeclContext::lookup_result R = Super->lookup(Res->getDeclName()); 239 for (unsigned I = 0, N = R.size(); I != N; ++I) { 240 if (ObjCPropertyDecl *SuperProp = dyn_cast<ObjCPropertyDecl>(R[I])) { 241 DiagnosePropertyMismatch(Res, SuperProp, Super->getIdentifier(), false); 242 FoundInSuper = true; 243 break; 244 } 245 } 246 if (FoundInSuper) 247 break; 248 else 249 CurrentInterfaceDecl = Super; 250 } 251 252 if (FoundInSuper) { 253 // Also compare the property against a property in our protocols. 254 for (auto *P : CurrentInterfaceDecl->protocols()) { 255 CheckPropertyAgainstProtocol(*this, Res, P, KnownProtos); 256 } 257 } else { 258 // Slower path: look in all protocols we referenced. 259 for (auto *P : IFace->all_referenced_protocols()) { 260 CheckPropertyAgainstProtocol(*this, Res, P, KnownProtos); 261 } 262 } 263 } else if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl)) { 264 // We don't check if class extension. Because properties in class extension 265 // are meant to override some of the attributes and checking has already done 266 // when property in class extension is constructed. 267 if (!Cat->IsClassExtension()) 268 for (auto *P : Cat->protocols()) 269 CheckPropertyAgainstProtocol(*this, Res, P, KnownProtos); 270 } else { 271 ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(ClassDecl); 272 for (auto *P : Proto->protocols()) 273 CheckPropertyAgainstProtocol(*this, Res, P, KnownProtos); 274 } 275 276 ActOnDocumentableDecl(Res); 277 return Res; 278 } 279 280 static ObjCPropertyDecl::PropertyAttributeKind 281 makePropertyAttributesAsWritten(unsigned Attributes) { 282 unsigned attributesAsWritten = 0; 283 if (Attributes & ObjCDeclSpec::DQ_PR_readonly) 284 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_readonly; 285 if (Attributes & ObjCDeclSpec::DQ_PR_readwrite) 286 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_readwrite; 287 if (Attributes & ObjCDeclSpec::DQ_PR_getter) 288 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_getter; 289 if (Attributes & ObjCDeclSpec::DQ_PR_setter) 290 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_setter; 291 if (Attributes & ObjCDeclSpec::DQ_PR_assign) 292 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_assign; 293 if (Attributes & ObjCDeclSpec::DQ_PR_retain) 294 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_retain; 295 if (Attributes & ObjCDeclSpec::DQ_PR_strong) 296 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_strong; 297 if (Attributes & ObjCDeclSpec::DQ_PR_weak) 298 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_weak; 299 if (Attributes & ObjCDeclSpec::DQ_PR_copy) 300 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_copy; 301 if (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained) 302 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_unsafe_unretained; 303 if (Attributes & ObjCDeclSpec::DQ_PR_nonatomic) 304 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_nonatomic; 305 if (Attributes & ObjCDeclSpec::DQ_PR_atomic) 306 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_atomic; 307 if (Attributes & ObjCDeclSpec::DQ_PR_class) 308 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_class; 309 if (Attributes & ObjCDeclSpec::DQ_PR_direct) 310 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_direct; 311 312 return (ObjCPropertyDecl::PropertyAttributeKind)attributesAsWritten; 313 } 314 315 static bool LocPropertyAttribute( ASTContext &Context, const char *attrName, 316 SourceLocation LParenLoc, SourceLocation &Loc) { 317 if (LParenLoc.isMacroID()) 318 return false; 319 320 SourceManager &SM = Context.getSourceManager(); 321 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(LParenLoc); 322 // Try to load the file buffer. 323 bool invalidTemp = false; 324 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp); 325 if (invalidTemp) 326 return false; 327 const char *tokenBegin = file.data() + locInfo.second; 328 329 // Lex from the start of the given location. 330 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), 331 Context.getLangOpts(), 332 file.begin(), tokenBegin, file.end()); 333 Token Tok; 334 do { 335 lexer.LexFromRawLexer(Tok); 336 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == attrName) { 337 Loc = Tok.getLocation(); 338 return true; 339 } 340 } while (Tok.isNot(tok::r_paren)); 341 return false; 342 } 343 344 /// Check for a mismatch in the atomicity of the given properties. 345 static void checkAtomicPropertyMismatch(Sema &S, 346 ObjCPropertyDecl *OldProperty, 347 ObjCPropertyDecl *NewProperty, 348 bool PropagateAtomicity) { 349 // If the atomicity of both matches, we're done. 350 bool OldIsAtomic = 351 (OldProperty->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) 352 == 0; 353 bool NewIsAtomic = 354 (NewProperty->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) 355 == 0; 356 if (OldIsAtomic == NewIsAtomic) return; 357 358 // Determine whether the given property is readonly and implicitly 359 // atomic. 360 auto isImplicitlyReadonlyAtomic = [](ObjCPropertyDecl *Property) -> bool { 361 // Is it readonly? 362 auto Attrs = Property->getPropertyAttributes(); 363 if ((Attrs & ObjCPropertyDecl::OBJC_PR_readonly) == 0) return false; 364 365 // Is it nonatomic? 366 if (Attrs & ObjCPropertyDecl::OBJC_PR_nonatomic) return false; 367 368 // Was 'atomic' specified directly? 369 if (Property->getPropertyAttributesAsWritten() & 370 ObjCPropertyDecl::OBJC_PR_atomic) 371 return false; 372 373 return true; 374 }; 375 376 // If we're allowed to propagate atomicity, and the new property did 377 // not specify atomicity at all, propagate. 378 const unsigned AtomicityMask = 379 (ObjCPropertyDecl::OBJC_PR_atomic | ObjCPropertyDecl::OBJC_PR_nonatomic); 380 if (PropagateAtomicity && 381 ((NewProperty->getPropertyAttributesAsWritten() & AtomicityMask) == 0)) { 382 unsigned Attrs = NewProperty->getPropertyAttributes(); 383 Attrs = Attrs & ~AtomicityMask; 384 if (OldIsAtomic) 385 Attrs |= ObjCPropertyDecl::OBJC_PR_atomic; 386 else 387 Attrs |= ObjCPropertyDecl::OBJC_PR_nonatomic; 388 389 NewProperty->overwritePropertyAttributes(Attrs); 390 return; 391 } 392 393 // One of the properties is atomic; if it's a readonly property, and 394 // 'atomic' wasn't explicitly specified, we're okay. 395 if ((OldIsAtomic && isImplicitlyReadonlyAtomic(OldProperty)) || 396 (NewIsAtomic && isImplicitlyReadonlyAtomic(NewProperty))) 397 return; 398 399 // Diagnose the conflict. 400 const IdentifierInfo *OldContextName; 401 auto *OldDC = OldProperty->getDeclContext(); 402 if (auto Category = dyn_cast<ObjCCategoryDecl>(OldDC)) 403 OldContextName = Category->getClassInterface()->getIdentifier(); 404 else 405 OldContextName = cast<ObjCContainerDecl>(OldDC)->getIdentifier(); 406 407 S.Diag(NewProperty->getLocation(), diag::warn_property_attribute) 408 << NewProperty->getDeclName() << "atomic" 409 << OldContextName; 410 S.Diag(OldProperty->getLocation(), diag::note_property_declare); 411 } 412 413 ObjCPropertyDecl * 414 Sema::HandlePropertyInClassExtension(Scope *S, 415 SourceLocation AtLoc, 416 SourceLocation LParenLoc, 417 FieldDeclarator &FD, 418 Selector GetterSel, 419 SourceLocation GetterNameLoc, 420 Selector SetterSel, 421 SourceLocation SetterNameLoc, 422 const bool isReadWrite, 423 unsigned &Attributes, 424 const unsigned AttributesAsWritten, 425 QualType T, 426 TypeSourceInfo *TSI, 427 tok::ObjCKeywordKind MethodImplKind) { 428 ObjCCategoryDecl *CDecl = cast<ObjCCategoryDecl>(CurContext); 429 // Diagnose if this property is already in continuation class. 430 DeclContext *DC = CurContext; 431 IdentifierInfo *PropertyId = FD.D.getIdentifier(); 432 ObjCInterfaceDecl *CCPrimary = CDecl->getClassInterface(); 433 434 // We need to look in the @interface to see if the @property was 435 // already declared. 436 if (!CCPrimary) { 437 Diag(CDecl->getLocation(), diag::err_continuation_class); 438 return nullptr; 439 } 440 441 bool isClassProperty = (AttributesAsWritten & ObjCDeclSpec::DQ_PR_class) || 442 (Attributes & ObjCDeclSpec::DQ_PR_class); 443 444 // Find the property in the extended class's primary class or 445 // extensions. 446 ObjCPropertyDecl *PIDecl = CCPrimary->FindPropertyVisibleInPrimaryClass( 447 PropertyId, ObjCPropertyDecl::getQueryKind(isClassProperty)); 448 449 // If we found a property in an extension, complain. 450 if (PIDecl && isa<ObjCCategoryDecl>(PIDecl->getDeclContext())) { 451 Diag(AtLoc, diag::err_duplicate_property); 452 Diag(PIDecl->getLocation(), diag::note_property_declare); 453 return nullptr; 454 } 455 456 // Check for consistency with the previous declaration, if there is one. 457 if (PIDecl) { 458 // A readonly property declared in the primary class can be refined 459 // by adding a readwrite property within an extension. 460 // Anything else is an error. 461 if (!(PIDecl->isReadOnly() && isReadWrite)) { 462 // Tailor the diagnostics for the common case where a readwrite 463 // property is declared both in the @interface and the continuation. 464 // This is a common error where the user often intended the original 465 // declaration to be readonly. 466 unsigned diag = 467 (Attributes & ObjCDeclSpec::DQ_PR_readwrite) && 468 (PIDecl->getPropertyAttributesAsWritten() & 469 ObjCPropertyDecl::OBJC_PR_readwrite) 470 ? diag::err_use_continuation_class_redeclaration_readwrite 471 : diag::err_use_continuation_class; 472 Diag(AtLoc, diag) 473 << CCPrimary->getDeclName(); 474 Diag(PIDecl->getLocation(), diag::note_property_declare); 475 return nullptr; 476 } 477 478 // Check for consistency of getters. 479 if (PIDecl->getGetterName() != GetterSel) { 480 // If the getter was written explicitly, complain. 481 if (AttributesAsWritten & ObjCDeclSpec::DQ_PR_getter) { 482 Diag(AtLoc, diag::warn_property_redecl_getter_mismatch) 483 << PIDecl->getGetterName() << GetterSel; 484 Diag(PIDecl->getLocation(), diag::note_property_declare); 485 } 486 487 // Always adopt the getter from the original declaration. 488 GetterSel = PIDecl->getGetterName(); 489 Attributes |= ObjCDeclSpec::DQ_PR_getter; 490 } 491 492 // Check consistency of ownership. 493 unsigned ExistingOwnership 494 = getOwnershipRule(PIDecl->getPropertyAttributes()); 495 unsigned NewOwnership = getOwnershipRule(Attributes); 496 if (ExistingOwnership && NewOwnership != ExistingOwnership) { 497 // If the ownership was written explicitly, complain. 498 if (getOwnershipRule(AttributesAsWritten)) { 499 Diag(AtLoc, diag::warn_property_attr_mismatch); 500 Diag(PIDecl->getLocation(), diag::note_property_declare); 501 } 502 503 // Take the ownership from the original property. 504 Attributes = (Attributes & ~OwnershipMask) | ExistingOwnership; 505 } 506 507 // If the redeclaration is 'weak' but the original property is not, 508 if ((Attributes & ObjCPropertyDecl::OBJC_PR_weak) && 509 !(PIDecl->getPropertyAttributesAsWritten() 510 & ObjCPropertyDecl::OBJC_PR_weak) && 511 PIDecl->getType()->getAs<ObjCObjectPointerType>() && 512 PIDecl->getType().getObjCLifetime() == Qualifiers::OCL_None) { 513 Diag(AtLoc, diag::warn_property_implicitly_mismatched); 514 Diag(PIDecl->getLocation(), diag::note_property_declare); 515 } 516 } 517 518 // Create a new ObjCPropertyDecl with the DeclContext being 519 // the class extension. 520 ObjCPropertyDecl *PDecl = CreatePropertyDecl(S, CDecl, AtLoc, LParenLoc, 521 FD, GetterSel, GetterNameLoc, 522 SetterSel, SetterNameLoc, 523 isReadWrite, 524 Attributes, AttributesAsWritten, 525 T, TSI, MethodImplKind, DC); 526 527 // If there was no declaration of a property with the same name in 528 // the primary class, we're done. 529 if (!PIDecl) { 530 ProcessPropertyDecl(PDecl); 531 return PDecl; 532 } 533 534 if (!Context.hasSameType(PIDecl->getType(), PDecl->getType())) { 535 bool IncompatibleObjC = false; 536 QualType ConvertedType; 537 // Relax the strict type matching for property type in continuation class. 538 // Allow property object type of continuation class to be different as long 539 // as it narrows the object type in its primary class property. Note that 540 // this conversion is safe only because the wider type is for a 'readonly' 541 // property in primary class and 'narrowed' type for a 'readwrite' property 542 // in continuation class. 543 QualType PrimaryClassPropertyT = Context.getCanonicalType(PIDecl->getType()); 544 QualType ClassExtPropertyT = Context.getCanonicalType(PDecl->getType()); 545 if (!isa<ObjCObjectPointerType>(PrimaryClassPropertyT) || 546 !isa<ObjCObjectPointerType>(ClassExtPropertyT) || 547 (!isObjCPointerConversion(ClassExtPropertyT, PrimaryClassPropertyT, 548 ConvertedType, IncompatibleObjC)) 549 || IncompatibleObjC) { 550 Diag(AtLoc, 551 diag::err_type_mismatch_continuation_class) << PDecl->getType(); 552 Diag(PIDecl->getLocation(), diag::note_property_declare); 553 return nullptr; 554 } 555 } 556 557 // Check that atomicity of property in class extension matches the previous 558 // declaration. 559 checkAtomicPropertyMismatch(*this, PIDecl, PDecl, true); 560 561 // Make sure getter/setter are appropriately synthesized. 562 ProcessPropertyDecl(PDecl); 563 return PDecl; 564 } 565 566 ObjCPropertyDecl *Sema::CreatePropertyDecl(Scope *S, 567 ObjCContainerDecl *CDecl, 568 SourceLocation AtLoc, 569 SourceLocation LParenLoc, 570 FieldDeclarator &FD, 571 Selector GetterSel, 572 SourceLocation GetterNameLoc, 573 Selector SetterSel, 574 SourceLocation SetterNameLoc, 575 const bool isReadWrite, 576 const unsigned Attributes, 577 const unsigned AttributesAsWritten, 578 QualType T, 579 TypeSourceInfo *TInfo, 580 tok::ObjCKeywordKind MethodImplKind, 581 DeclContext *lexicalDC){ 582 IdentifierInfo *PropertyId = FD.D.getIdentifier(); 583 584 // Property defaults to 'assign' if it is readwrite, unless this is ARC 585 // and the type is retainable. 586 bool isAssign; 587 if (Attributes & (ObjCDeclSpec::DQ_PR_assign | 588 ObjCDeclSpec::DQ_PR_unsafe_unretained)) { 589 isAssign = true; 590 } else if (getOwnershipRule(Attributes) || !isReadWrite) { 591 isAssign = false; 592 } else { 593 isAssign = (!getLangOpts().ObjCAutoRefCount || 594 !T->isObjCRetainableType()); 595 } 596 597 // Issue a warning if property is 'assign' as default and its 598 // object, which is gc'able conforms to NSCopying protocol 599 if (getLangOpts().getGC() != LangOptions::NonGC && 600 isAssign && !(Attributes & ObjCDeclSpec::DQ_PR_assign)) { 601 if (const ObjCObjectPointerType *ObjPtrTy = 602 T->getAs<ObjCObjectPointerType>()) { 603 ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface(); 604 if (IDecl) 605 if (ObjCProtocolDecl* PNSCopying = 606 LookupProtocol(&Context.Idents.get("NSCopying"), AtLoc)) 607 if (IDecl->ClassImplementsProtocol(PNSCopying, true)) 608 Diag(AtLoc, diag::warn_implements_nscopying) << PropertyId; 609 } 610 } 611 612 if (T->isObjCObjectType()) { 613 SourceLocation StarLoc = TInfo->getTypeLoc().getEndLoc(); 614 StarLoc = getLocForEndOfToken(StarLoc); 615 Diag(FD.D.getIdentifierLoc(), diag::err_statically_allocated_object) 616 << FixItHint::CreateInsertion(StarLoc, "*"); 617 T = Context.getObjCObjectPointerType(T); 618 SourceLocation TLoc = TInfo->getTypeLoc().getBeginLoc(); 619 TInfo = Context.getTrivialTypeSourceInfo(T, TLoc); 620 } 621 622 DeclContext *DC = CDecl; 623 ObjCPropertyDecl *PDecl = ObjCPropertyDecl::Create(Context, DC, 624 FD.D.getIdentifierLoc(), 625 PropertyId, AtLoc, 626 LParenLoc, T, TInfo); 627 628 bool isClassProperty = (AttributesAsWritten & ObjCDeclSpec::DQ_PR_class) || 629 (Attributes & ObjCDeclSpec::DQ_PR_class); 630 // Class property and instance property can have the same name. 631 if (ObjCPropertyDecl *prevDecl = ObjCPropertyDecl::findPropertyDecl( 632 DC, PropertyId, ObjCPropertyDecl::getQueryKind(isClassProperty))) { 633 Diag(PDecl->getLocation(), diag::err_duplicate_property); 634 Diag(prevDecl->getLocation(), diag::note_property_declare); 635 PDecl->setInvalidDecl(); 636 } 637 else { 638 DC->addDecl(PDecl); 639 if (lexicalDC) 640 PDecl->setLexicalDeclContext(lexicalDC); 641 } 642 643 if (T->isArrayType() || T->isFunctionType()) { 644 Diag(AtLoc, diag::err_property_type) << T; 645 PDecl->setInvalidDecl(); 646 } 647 648 ProcessDeclAttributes(S, PDecl, FD.D); 649 650 // Regardless of setter/getter attribute, we save the default getter/setter 651 // selector names in anticipation of declaration of setter/getter methods. 652 PDecl->setGetterName(GetterSel, GetterNameLoc); 653 PDecl->setSetterName(SetterSel, SetterNameLoc); 654 PDecl->setPropertyAttributesAsWritten( 655 makePropertyAttributesAsWritten(AttributesAsWritten)); 656 657 if (Attributes & ObjCDeclSpec::DQ_PR_readonly) 658 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readonly); 659 660 if (Attributes & ObjCDeclSpec::DQ_PR_getter) 661 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_getter); 662 663 if (Attributes & ObjCDeclSpec::DQ_PR_setter) 664 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_setter); 665 666 if (isReadWrite) 667 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readwrite); 668 669 if (Attributes & ObjCDeclSpec::DQ_PR_retain) 670 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_retain); 671 672 if (Attributes & ObjCDeclSpec::DQ_PR_strong) 673 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong); 674 675 if (Attributes & ObjCDeclSpec::DQ_PR_weak) 676 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_weak); 677 678 if (Attributes & ObjCDeclSpec::DQ_PR_copy) 679 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_copy); 680 681 if (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained) 682 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_unsafe_unretained); 683 684 if (isAssign) 685 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_assign); 686 687 // In the semantic attributes, one of nonatomic or atomic is always set. 688 if (Attributes & ObjCDeclSpec::DQ_PR_nonatomic) 689 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_nonatomic); 690 else 691 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_atomic); 692 693 // 'unsafe_unretained' is alias for 'assign'. 694 if (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained) 695 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_assign); 696 if (isAssign) 697 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_unsafe_unretained); 698 699 if (MethodImplKind == tok::objc_required) 700 PDecl->setPropertyImplementation(ObjCPropertyDecl::Required); 701 else if (MethodImplKind == tok::objc_optional) 702 PDecl->setPropertyImplementation(ObjCPropertyDecl::Optional); 703 704 if (Attributes & ObjCDeclSpec::DQ_PR_nullability) 705 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_nullability); 706 707 if (Attributes & ObjCDeclSpec::DQ_PR_null_resettable) 708 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_null_resettable); 709 710 if (Attributes & ObjCDeclSpec::DQ_PR_class) 711 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_class); 712 713 if ((Attributes & ObjCDeclSpec::DQ_PR_direct) || 714 CDecl->hasAttr<ObjCDirectMembersAttr>()) { 715 if (isa<ObjCProtocolDecl>(CDecl)) { 716 Diag(PDecl->getLocation(), diag::err_objc_direct_on_protocol) << true; 717 } else if (getLangOpts().ObjCRuntime.allowsDirectDispatch()) { 718 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_direct); 719 } else { 720 Diag(PDecl->getLocation(), diag::warn_objc_direct_property_ignored) 721 << PDecl->getDeclName(); 722 } 723 } 724 725 return PDecl; 726 } 727 728 static void checkARCPropertyImpl(Sema &S, SourceLocation propertyImplLoc, 729 ObjCPropertyDecl *property, 730 ObjCIvarDecl *ivar) { 731 if (property->isInvalidDecl() || ivar->isInvalidDecl()) return; 732 733 QualType ivarType = ivar->getType(); 734 Qualifiers::ObjCLifetime ivarLifetime = ivarType.getObjCLifetime(); 735 736 // The lifetime implied by the property's attributes. 737 Qualifiers::ObjCLifetime propertyLifetime = 738 getImpliedARCOwnership(property->getPropertyAttributes(), 739 property->getType()); 740 741 // We're fine if they match. 742 if (propertyLifetime == ivarLifetime) return; 743 744 // None isn't a valid lifetime for an object ivar in ARC, and 745 // __autoreleasing is never valid; don't diagnose twice. 746 if ((ivarLifetime == Qualifiers::OCL_None && 747 S.getLangOpts().ObjCAutoRefCount) || 748 ivarLifetime == Qualifiers::OCL_Autoreleasing) 749 return; 750 751 // If the ivar is private, and it's implicitly __unsafe_unretained 752 // because of its type, then pretend it was actually implicitly 753 // __strong. This is only sound because we're processing the 754 // property implementation before parsing any method bodies. 755 if (ivarLifetime == Qualifiers::OCL_ExplicitNone && 756 propertyLifetime == Qualifiers::OCL_Strong && 757 ivar->getAccessControl() == ObjCIvarDecl::Private) { 758 SplitQualType split = ivarType.split(); 759 if (split.Quals.hasObjCLifetime()) { 760 assert(ivarType->isObjCARCImplicitlyUnretainedType()); 761 split.Quals.setObjCLifetime(Qualifiers::OCL_Strong); 762 ivarType = S.Context.getQualifiedType(split); 763 ivar->setType(ivarType); 764 return; 765 } 766 } 767 768 switch (propertyLifetime) { 769 case Qualifiers::OCL_Strong: 770 S.Diag(ivar->getLocation(), diag::err_arc_strong_property_ownership) 771 << property->getDeclName() 772 << ivar->getDeclName() 773 << ivarLifetime; 774 break; 775 776 case Qualifiers::OCL_Weak: 777 S.Diag(ivar->getLocation(), diag::err_weak_property) 778 << property->getDeclName() 779 << ivar->getDeclName(); 780 break; 781 782 case Qualifiers::OCL_ExplicitNone: 783 S.Diag(ivar->getLocation(), diag::err_arc_assign_property_ownership) 784 << property->getDeclName() 785 << ivar->getDeclName() 786 << ((property->getPropertyAttributesAsWritten() 787 & ObjCPropertyDecl::OBJC_PR_assign) != 0); 788 break; 789 790 case Qualifiers::OCL_Autoreleasing: 791 llvm_unreachable("properties cannot be autoreleasing"); 792 793 case Qualifiers::OCL_None: 794 // Any other property should be ignored. 795 return; 796 } 797 798 S.Diag(property->getLocation(), diag::note_property_declare); 799 if (propertyImplLoc.isValid()) 800 S.Diag(propertyImplLoc, diag::note_property_synthesize); 801 } 802 803 /// setImpliedPropertyAttributeForReadOnlyProperty - 804 /// This routine evaludates life-time attributes for a 'readonly' 805 /// property with no known lifetime of its own, using backing 806 /// 'ivar's attribute, if any. If no backing 'ivar', property's 807 /// life-time is assumed 'strong'. 808 static void setImpliedPropertyAttributeForReadOnlyProperty( 809 ObjCPropertyDecl *property, ObjCIvarDecl *ivar) { 810 Qualifiers::ObjCLifetime propertyLifetime = 811 getImpliedARCOwnership(property->getPropertyAttributes(), 812 property->getType()); 813 if (propertyLifetime != Qualifiers::OCL_None) 814 return; 815 816 if (!ivar) { 817 // if no backing ivar, make property 'strong'. 818 property->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong); 819 return; 820 } 821 // property assumes owenership of backing ivar. 822 QualType ivarType = ivar->getType(); 823 Qualifiers::ObjCLifetime ivarLifetime = ivarType.getObjCLifetime(); 824 if (ivarLifetime == Qualifiers::OCL_Strong) 825 property->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong); 826 else if (ivarLifetime == Qualifiers::OCL_Weak) 827 property->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_weak); 828 } 829 830 static bool 831 isIncompatiblePropertyAttribute(unsigned Attr1, unsigned Attr2, 832 ObjCPropertyDecl::PropertyAttributeKind Kind) { 833 return (Attr1 & Kind) != (Attr2 & Kind); 834 } 835 836 static bool areIncompatiblePropertyAttributes(unsigned Attr1, unsigned Attr2, 837 unsigned Kinds) { 838 return ((Attr1 & Kinds) != 0) != ((Attr2 & Kinds) != 0); 839 } 840 841 /// SelectPropertyForSynthesisFromProtocols - Finds the most appropriate 842 /// property declaration that should be synthesised in all of the inherited 843 /// protocols. It also diagnoses properties declared in inherited protocols with 844 /// mismatched types or attributes, since any of them can be candidate for 845 /// synthesis. 846 static ObjCPropertyDecl * 847 SelectPropertyForSynthesisFromProtocols(Sema &S, SourceLocation AtLoc, 848 ObjCInterfaceDecl *ClassDecl, 849 ObjCPropertyDecl *Property) { 850 assert(isa<ObjCProtocolDecl>(Property->getDeclContext()) && 851 "Expected a property from a protocol"); 852 ObjCInterfaceDecl::ProtocolPropertySet ProtocolSet; 853 ObjCInterfaceDecl::PropertyDeclOrder Properties; 854 for (const auto *PI : ClassDecl->all_referenced_protocols()) { 855 if (const ObjCProtocolDecl *PDecl = PI->getDefinition()) 856 PDecl->collectInheritedProtocolProperties(Property, ProtocolSet, 857 Properties); 858 } 859 if (ObjCInterfaceDecl *SDecl = ClassDecl->getSuperClass()) { 860 while (SDecl) { 861 for (const auto *PI : SDecl->all_referenced_protocols()) { 862 if (const ObjCProtocolDecl *PDecl = PI->getDefinition()) 863 PDecl->collectInheritedProtocolProperties(Property, ProtocolSet, 864 Properties); 865 } 866 SDecl = SDecl->getSuperClass(); 867 } 868 } 869 870 if (Properties.empty()) 871 return Property; 872 873 ObjCPropertyDecl *OriginalProperty = Property; 874 size_t SelectedIndex = 0; 875 for (const auto &Prop : llvm::enumerate(Properties)) { 876 // Select the 'readwrite' property if such property exists. 877 if (Property->isReadOnly() && !Prop.value()->isReadOnly()) { 878 Property = Prop.value(); 879 SelectedIndex = Prop.index(); 880 } 881 } 882 if (Property != OriginalProperty) { 883 // Check that the old property is compatible with the new one. 884 Properties[SelectedIndex] = OriginalProperty; 885 } 886 887 QualType RHSType = S.Context.getCanonicalType(Property->getType()); 888 unsigned OriginalAttributes = Property->getPropertyAttributesAsWritten(); 889 enum MismatchKind { 890 IncompatibleType = 0, 891 HasNoExpectedAttribute, 892 HasUnexpectedAttribute, 893 DifferentGetter, 894 DifferentSetter 895 }; 896 // Represents a property from another protocol that conflicts with the 897 // selected declaration. 898 struct MismatchingProperty { 899 const ObjCPropertyDecl *Prop; 900 MismatchKind Kind; 901 StringRef AttributeName; 902 }; 903 SmallVector<MismatchingProperty, 4> Mismatches; 904 for (ObjCPropertyDecl *Prop : Properties) { 905 // Verify the property attributes. 906 unsigned Attr = Prop->getPropertyAttributesAsWritten(); 907 if (Attr != OriginalAttributes) { 908 auto Diag = [&](bool OriginalHasAttribute, StringRef AttributeName) { 909 MismatchKind Kind = OriginalHasAttribute ? HasNoExpectedAttribute 910 : HasUnexpectedAttribute; 911 Mismatches.push_back({Prop, Kind, AttributeName}); 912 }; 913 // The ownership might be incompatible unless the property has no explicit 914 // ownership. 915 bool HasOwnership = (Attr & (ObjCPropertyDecl::OBJC_PR_retain | 916 ObjCPropertyDecl::OBJC_PR_strong | 917 ObjCPropertyDecl::OBJC_PR_copy | 918 ObjCPropertyDecl::OBJC_PR_assign | 919 ObjCPropertyDecl::OBJC_PR_unsafe_unretained | 920 ObjCPropertyDecl::OBJC_PR_weak)) != 0; 921 if (HasOwnership && 922 isIncompatiblePropertyAttribute(OriginalAttributes, Attr, 923 ObjCPropertyDecl::OBJC_PR_copy)) { 924 Diag(OriginalAttributes & ObjCPropertyDecl::OBJC_PR_copy, "copy"); 925 continue; 926 } 927 if (HasOwnership && areIncompatiblePropertyAttributes( 928 OriginalAttributes, Attr, 929 ObjCPropertyDecl::OBJC_PR_retain | 930 ObjCPropertyDecl::OBJC_PR_strong)) { 931 Diag(OriginalAttributes & (ObjCPropertyDecl::OBJC_PR_retain | 932 ObjCPropertyDecl::OBJC_PR_strong), 933 "retain (or strong)"); 934 continue; 935 } 936 if (isIncompatiblePropertyAttribute(OriginalAttributes, Attr, 937 ObjCPropertyDecl::OBJC_PR_atomic)) { 938 Diag(OriginalAttributes & ObjCPropertyDecl::OBJC_PR_atomic, "atomic"); 939 continue; 940 } 941 } 942 if (Property->getGetterName() != Prop->getGetterName()) { 943 Mismatches.push_back({Prop, DifferentGetter, ""}); 944 continue; 945 } 946 if (!Property->isReadOnly() && !Prop->isReadOnly() && 947 Property->getSetterName() != Prop->getSetterName()) { 948 Mismatches.push_back({Prop, DifferentSetter, ""}); 949 continue; 950 } 951 QualType LHSType = S.Context.getCanonicalType(Prop->getType()); 952 if (!S.Context.propertyTypesAreCompatible(LHSType, RHSType)) { 953 bool IncompatibleObjC = false; 954 QualType ConvertedType; 955 if (!S.isObjCPointerConversion(RHSType, LHSType, ConvertedType, IncompatibleObjC) 956 || IncompatibleObjC) { 957 Mismatches.push_back({Prop, IncompatibleType, ""}); 958 continue; 959 } 960 } 961 } 962 963 if (Mismatches.empty()) 964 return Property; 965 966 // Diagnose incompability. 967 { 968 bool HasIncompatibleAttributes = false; 969 for (const auto &Note : Mismatches) 970 HasIncompatibleAttributes = 971 Note.Kind != IncompatibleType ? true : HasIncompatibleAttributes; 972 // Promote the warning to an error if there are incompatible attributes or 973 // incompatible types together with readwrite/readonly incompatibility. 974 auto Diag = S.Diag(Property->getLocation(), 975 Property != OriginalProperty || HasIncompatibleAttributes 976 ? diag::err_protocol_property_mismatch 977 : diag::warn_protocol_property_mismatch); 978 Diag << Mismatches[0].Kind; 979 switch (Mismatches[0].Kind) { 980 case IncompatibleType: 981 Diag << Property->getType(); 982 break; 983 case HasNoExpectedAttribute: 984 case HasUnexpectedAttribute: 985 Diag << Mismatches[0].AttributeName; 986 break; 987 case DifferentGetter: 988 Diag << Property->getGetterName(); 989 break; 990 case DifferentSetter: 991 Diag << Property->getSetterName(); 992 break; 993 } 994 } 995 for (const auto &Note : Mismatches) { 996 auto Diag = 997 S.Diag(Note.Prop->getLocation(), diag::note_protocol_property_declare) 998 << Note.Kind; 999 switch (Note.Kind) { 1000 case IncompatibleType: 1001 Diag << Note.Prop->getType(); 1002 break; 1003 case HasNoExpectedAttribute: 1004 case HasUnexpectedAttribute: 1005 Diag << Note.AttributeName; 1006 break; 1007 case DifferentGetter: 1008 Diag << Note.Prop->getGetterName(); 1009 break; 1010 case DifferentSetter: 1011 Diag << Note.Prop->getSetterName(); 1012 break; 1013 } 1014 } 1015 if (AtLoc.isValid()) 1016 S.Diag(AtLoc, diag::note_property_synthesize); 1017 1018 return Property; 1019 } 1020 1021 /// Determine whether any storage attributes were written on the property. 1022 static bool hasWrittenStorageAttribute(ObjCPropertyDecl *Prop, 1023 ObjCPropertyQueryKind QueryKind) { 1024 if (Prop->getPropertyAttributesAsWritten() & OwnershipMask) return true; 1025 1026 // If this is a readwrite property in a class extension that refines 1027 // a readonly property in the original class definition, check it as 1028 // well. 1029 1030 // If it's a readonly property, we're not interested. 1031 if (Prop->isReadOnly()) return false; 1032 1033 // Is it declared in an extension? 1034 auto Category = dyn_cast<ObjCCategoryDecl>(Prop->getDeclContext()); 1035 if (!Category || !Category->IsClassExtension()) return false; 1036 1037 // Find the corresponding property in the primary class definition. 1038 auto OrigClass = Category->getClassInterface(); 1039 for (auto Found : OrigClass->lookup(Prop->getDeclName())) { 1040 if (ObjCPropertyDecl *OrigProp = dyn_cast<ObjCPropertyDecl>(Found)) 1041 return OrigProp->getPropertyAttributesAsWritten() & OwnershipMask; 1042 } 1043 1044 // Look through all of the protocols. 1045 for (const auto *Proto : OrigClass->all_referenced_protocols()) { 1046 if (ObjCPropertyDecl *OrigProp = Proto->FindPropertyDeclaration( 1047 Prop->getIdentifier(), QueryKind)) 1048 return OrigProp->getPropertyAttributesAsWritten() & OwnershipMask; 1049 } 1050 1051 return false; 1052 } 1053 1054 /// Create a synthesized property accessor stub inside the \@implementation. 1055 static ObjCMethodDecl * 1056 RedeclarePropertyAccessor(ASTContext &Context, ObjCImplementationDecl *Impl, 1057 ObjCMethodDecl *AccessorDecl, SourceLocation AtLoc, 1058 SourceLocation PropertyLoc) { 1059 ObjCMethodDecl *Decl = AccessorDecl; 1060 ObjCMethodDecl *ImplDecl = ObjCMethodDecl::Create( 1061 Context, AtLoc.isValid() ? AtLoc : Decl->getBeginLoc(), 1062 PropertyLoc.isValid() ? PropertyLoc : Decl->getEndLoc(), 1063 Decl->getSelector(), Decl->getReturnType(), 1064 Decl->getReturnTypeSourceInfo(), Impl, Decl->isInstanceMethod(), 1065 Decl->isVariadic(), Decl->isPropertyAccessor(), 1066 /* isSynthesized*/ true, Decl->isImplicit(), Decl->isDefined(), 1067 Decl->getImplementationControl(), Decl->hasRelatedResultType()); 1068 ImplDecl->getMethodFamily(); 1069 if (Decl->hasAttrs()) 1070 ImplDecl->setAttrs(Decl->getAttrs()); 1071 ImplDecl->setSelfDecl(Decl->getSelfDecl()); 1072 ImplDecl->setCmdDecl(Decl->getCmdDecl()); 1073 SmallVector<SourceLocation, 1> SelLocs; 1074 Decl->getSelectorLocs(SelLocs); 1075 ImplDecl->setMethodParams(Context, Decl->parameters(), SelLocs); 1076 ImplDecl->setLexicalDeclContext(Impl); 1077 ImplDecl->setDefined(false); 1078 return ImplDecl; 1079 } 1080 1081 /// ActOnPropertyImplDecl - This routine performs semantic checks and 1082 /// builds the AST node for a property implementation declaration; declared 1083 /// as \@synthesize or \@dynamic. 1084 /// 1085 Decl *Sema::ActOnPropertyImplDecl(Scope *S, 1086 SourceLocation AtLoc, 1087 SourceLocation PropertyLoc, 1088 bool Synthesize, 1089 IdentifierInfo *PropertyId, 1090 IdentifierInfo *PropertyIvar, 1091 SourceLocation PropertyIvarLoc, 1092 ObjCPropertyQueryKind QueryKind) { 1093 ObjCContainerDecl *ClassImpDecl = 1094 dyn_cast<ObjCContainerDecl>(CurContext); 1095 // Make sure we have a context for the property implementation declaration. 1096 if (!ClassImpDecl) { 1097 Diag(AtLoc, diag::err_missing_property_context); 1098 return nullptr; 1099 } 1100 if (PropertyIvarLoc.isInvalid()) 1101 PropertyIvarLoc = PropertyLoc; 1102 SourceLocation PropertyDiagLoc = PropertyLoc; 1103 if (PropertyDiagLoc.isInvalid()) 1104 PropertyDiagLoc = ClassImpDecl->getBeginLoc(); 1105 ObjCPropertyDecl *property = nullptr; 1106 ObjCInterfaceDecl *IDecl = nullptr; 1107 // Find the class or category class where this property must have 1108 // a declaration. 1109 ObjCImplementationDecl *IC = nullptr; 1110 ObjCCategoryImplDecl *CatImplClass = nullptr; 1111 if ((IC = dyn_cast<ObjCImplementationDecl>(ClassImpDecl))) { 1112 IDecl = IC->getClassInterface(); 1113 // We always synthesize an interface for an implementation 1114 // without an interface decl. So, IDecl is always non-zero. 1115 assert(IDecl && 1116 "ActOnPropertyImplDecl - @implementation without @interface"); 1117 1118 // Look for this property declaration in the @implementation's @interface 1119 property = IDecl->FindPropertyDeclaration(PropertyId, QueryKind); 1120 if (!property) { 1121 Diag(PropertyLoc, diag::err_bad_property_decl) << IDecl->getDeclName(); 1122 return nullptr; 1123 } 1124 if (property->isClassProperty() && Synthesize) { 1125 Diag(PropertyLoc, diag::err_synthesize_on_class_property) << PropertyId; 1126 return nullptr; 1127 } 1128 unsigned PIkind = property->getPropertyAttributesAsWritten(); 1129 if ((PIkind & (ObjCPropertyDecl::OBJC_PR_atomic | 1130 ObjCPropertyDecl::OBJC_PR_nonatomic) ) == 0) { 1131 if (AtLoc.isValid()) 1132 Diag(AtLoc, diag::warn_implicit_atomic_property); 1133 else 1134 Diag(IC->getLocation(), diag::warn_auto_implicit_atomic_property); 1135 Diag(property->getLocation(), diag::note_property_declare); 1136 } 1137 1138 if (const ObjCCategoryDecl *CD = 1139 dyn_cast<ObjCCategoryDecl>(property->getDeclContext())) { 1140 if (!CD->IsClassExtension()) { 1141 Diag(PropertyLoc, diag::err_category_property) << CD->getDeclName(); 1142 Diag(property->getLocation(), diag::note_property_declare); 1143 return nullptr; 1144 } 1145 } 1146 if (Synthesize&& 1147 (PIkind & ObjCPropertyDecl::OBJC_PR_readonly) && 1148 property->hasAttr<IBOutletAttr>() && 1149 !AtLoc.isValid()) { 1150 bool ReadWriteProperty = false; 1151 // Search into the class extensions and see if 'readonly property is 1152 // redeclared 'readwrite', then no warning is to be issued. 1153 for (auto *Ext : IDecl->known_extensions()) { 1154 DeclContext::lookup_result R = Ext->lookup(property->getDeclName()); 1155 if (!R.empty()) 1156 if (ObjCPropertyDecl *ExtProp = dyn_cast<ObjCPropertyDecl>(R[0])) { 1157 PIkind = ExtProp->getPropertyAttributesAsWritten(); 1158 if (PIkind & ObjCPropertyDecl::OBJC_PR_readwrite) { 1159 ReadWriteProperty = true; 1160 break; 1161 } 1162 } 1163 } 1164 1165 if (!ReadWriteProperty) { 1166 Diag(property->getLocation(), diag::warn_auto_readonly_iboutlet_property) 1167 << property; 1168 SourceLocation readonlyLoc; 1169 if (LocPropertyAttribute(Context, "readonly", 1170 property->getLParenLoc(), readonlyLoc)) { 1171 SourceLocation endLoc = 1172 readonlyLoc.getLocWithOffset(strlen("readonly")-1); 1173 SourceRange ReadonlySourceRange(readonlyLoc, endLoc); 1174 Diag(property->getLocation(), 1175 diag::note_auto_readonly_iboutlet_fixup_suggest) << 1176 FixItHint::CreateReplacement(ReadonlySourceRange, "readwrite"); 1177 } 1178 } 1179 } 1180 if (Synthesize && isa<ObjCProtocolDecl>(property->getDeclContext())) 1181 property = SelectPropertyForSynthesisFromProtocols(*this, AtLoc, IDecl, 1182 property); 1183 1184 } else if ((CatImplClass = dyn_cast<ObjCCategoryImplDecl>(ClassImpDecl))) { 1185 if (Synthesize) { 1186 Diag(AtLoc, diag::err_synthesize_category_decl); 1187 return nullptr; 1188 } 1189 IDecl = CatImplClass->getClassInterface(); 1190 if (!IDecl) { 1191 Diag(AtLoc, diag::err_missing_property_interface); 1192 return nullptr; 1193 } 1194 ObjCCategoryDecl *Category = 1195 IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier()); 1196 1197 // If category for this implementation not found, it is an error which 1198 // has already been reported eralier. 1199 if (!Category) 1200 return nullptr; 1201 // Look for this property declaration in @implementation's category 1202 property = Category->FindPropertyDeclaration(PropertyId, QueryKind); 1203 if (!property) { 1204 Diag(PropertyLoc, diag::err_bad_category_property_decl) 1205 << Category->getDeclName(); 1206 return nullptr; 1207 } 1208 } else { 1209 Diag(AtLoc, diag::err_bad_property_context); 1210 return nullptr; 1211 } 1212 ObjCIvarDecl *Ivar = nullptr; 1213 bool CompleteTypeErr = false; 1214 bool compat = true; 1215 // Check that we have a valid, previously declared ivar for @synthesize 1216 if (Synthesize) { 1217 // @synthesize 1218 if (!PropertyIvar) 1219 PropertyIvar = PropertyId; 1220 // Check that this is a previously declared 'ivar' in 'IDecl' interface 1221 ObjCInterfaceDecl *ClassDeclared; 1222 Ivar = IDecl->lookupInstanceVariable(PropertyIvar, ClassDeclared); 1223 QualType PropType = property->getType(); 1224 QualType PropertyIvarType = PropType.getNonReferenceType(); 1225 1226 if (RequireCompleteType(PropertyDiagLoc, PropertyIvarType, 1227 diag::err_incomplete_synthesized_property, 1228 property->getDeclName())) { 1229 Diag(property->getLocation(), diag::note_property_declare); 1230 CompleteTypeErr = true; 1231 } 1232 1233 if (getLangOpts().ObjCAutoRefCount && 1234 (property->getPropertyAttributesAsWritten() & 1235 ObjCPropertyDecl::OBJC_PR_readonly) && 1236 PropertyIvarType->isObjCRetainableType()) { 1237 setImpliedPropertyAttributeForReadOnlyProperty(property, Ivar); 1238 } 1239 1240 ObjCPropertyDecl::PropertyAttributeKind kind 1241 = property->getPropertyAttributes(); 1242 1243 bool isARCWeak = false; 1244 if (kind & ObjCPropertyDecl::OBJC_PR_weak) { 1245 // Add GC __weak to the ivar type if the property is weak. 1246 if (getLangOpts().getGC() != LangOptions::NonGC) { 1247 assert(!getLangOpts().ObjCAutoRefCount); 1248 if (PropertyIvarType.isObjCGCStrong()) { 1249 Diag(PropertyDiagLoc, diag::err_gc_weak_property_strong_type); 1250 Diag(property->getLocation(), diag::note_property_declare); 1251 } else { 1252 PropertyIvarType = 1253 Context.getObjCGCQualType(PropertyIvarType, Qualifiers::Weak); 1254 } 1255 1256 // Otherwise, check whether ARC __weak is enabled and works with 1257 // the property type. 1258 } else { 1259 if (!getLangOpts().ObjCWeak) { 1260 // Only complain here when synthesizing an ivar. 1261 if (!Ivar) { 1262 Diag(PropertyDiagLoc, 1263 getLangOpts().ObjCWeakRuntime 1264 ? diag::err_synthesizing_arc_weak_property_disabled 1265 : diag::err_synthesizing_arc_weak_property_no_runtime); 1266 Diag(property->getLocation(), diag::note_property_declare); 1267 } 1268 CompleteTypeErr = true; // suppress later diagnostics about the ivar 1269 } else { 1270 isARCWeak = true; 1271 if (const ObjCObjectPointerType *ObjT = 1272 PropertyIvarType->getAs<ObjCObjectPointerType>()) { 1273 const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl(); 1274 if (ObjI && ObjI->isArcWeakrefUnavailable()) { 1275 Diag(property->getLocation(), 1276 diag::err_arc_weak_unavailable_property) 1277 << PropertyIvarType; 1278 Diag(ClassImpDecl->getLocation(), diag::note_implemented_by_class) 1279 << ClassImpDecl->getName(); 1280 } 1281 } 1282 } 1283 } 1284 } 1285 1286 if (AtLoc.isInvalid()) { 1287 // Check when default synthesizing a property that there is 1288 // an ivar matching property name and issue warning; since this 1289 // is the most common case of not using an ivar used for backing 1290 // property in non-default synthesis case. 1291 ObjCInterfaceDecl *ClassDeclared=nullptr; 1292 ObjCIvarDecl *originalIvar = 1293 IDecl->lookupInstanceVariable(property->getIdentifier(), 1294 ClassDeclared); 1295 if (originalIvar) { 1296 Diag(PropertyDiagLoc, 1297 diag::warn_autosynthesis_property_ivar_match) 1298 << PropertyId << (Ivar == nullptr) << PropertyIvar 1299 << originalIvar->getIdentifier(); 1300 Diag(property->getLocation(), diag::note_property_declare); 1301 Diag(originalIvar->getLocation(), diag::note_ivar_decl); 1302 } 1303 } 1304 1305 if (!Ivar) { 1306 // In ARC, give the ivar a lifetime qualifier based on the 1307 // property attributes. 1308 if ((getLangOpts().ObjCAutoRefCount || isARCWeak) && 1309 !PropertyIvarType.getObjCLifetime() && 1310 PropertyIvarType->isObjCRetainableType()) { 1311 1312 // It's an error if we have to do this and the user didn't 1313 // explicitly write an ownership attribute on the property. 1314 if (!hasWrittenStorageAttribute(property, QueryKind) && 1315 !(kind & ObjCPropertyDecl::OBJC_PR_strong)) { 1316 Diag(PropertyDiagLoc, 1317 diag::err_arc_objc_property_default_assign_on_object); 1318 Diag(property->getLocation(), diag::note_property_declare); 1319 } else { 1320 Qualifiers::ObjCLifetime lifetime = 1321 getImpliedARCOwnership(kind, PropertyIvarType); 1322 assert(lifetime && "no lifetime for property?"); 1323 1324 Qualifiers qs; 1325 qs.addObjCLifetime(lifetime); 1326 PropertyIvarType = Context.getQualifiedType(PropertyIvarType, qs); 1327 } 1328 } 1329 1330 Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl, 1331 PropertyIvarLoc,PropertyIvarLoc, PropertyIvar, 1332 PropertyIvarType, /*TInfo=*/nullptr, 1333 ObjCIvarDecl::Private, 1334 (Expr *)nullptr, true); 1335 if (RequireNonAbstractType(PropertyIvarLoc, 1336 PropertyIvarType, 1337 diag::err_abstract_type_in_decl, 1338 AbstractSynthesizedIvarType)) { 1339 Diag(property->getLocation(), diag::note_property_declare); 1340 // An abstract type is as bad as an incomplete type. 1341 CompleteTypeErr = true; 1342 } 1343 if (!CompleteTypeErr) { 1344 const RecordType *RecordTy = PropertyIvarType->getAs<RecordType>(); 1345 if (RecordTy && RecordTy->getDecl()->hasFlexibleArrayMember()) { 1346 Diag(PropertyIvarLoc, diag::err_synthesize_variable_sized_ivar) 1347 << PropertyIvarType; 1348 CompleteTypeErr = true; // suppress later diagnostics about the ivar 1349 } 1350 } 1351 if (CompleteTypeErr) 1352 Ivar->setInvalidDecl(); 1353 ClassImpDecl->addDecl(Ivar); 1354 IDecl->makeDeclVisibleInContext(Ivar); 1355 1356 if (getLangOpts().ObjCRuntime.isFragile()) 1357 Diag(PropertyDiagLoc, diag::err_missing_property_ivar_decl) 1358 << PropertyId; 1359 // Note! I deliberately want it to fall thru so, we have a 1360 // a property implementation and to avoid future warnings. 1361 } else if (getLangOpts().ObjCRuntime.isNonFragile() && 1362 !declaresSameEntity(ClassDeclared, IDecl)) { 1363 Diag(PropertyDiagLoc, diag::err_ivar_in_superclass_use) 1364 << property->getDeclName() << Ivar->getDeclName() 1365 << ClassDeclared->getDeclName(); 1366 Diag(Ivar->getLocation(), diag::note_previous_access_declaration) 1367 << Ivar << Ivar->getName(); 1368 // Note! I deliberately want it to fall thru so more errors are caught. 1369 } 1370 property->setPropertyIvarDecl(Ivar); 1371 1372 QualType IvarType = Context.getCanonicalType(Ivar->getType()); 1373 1374 // Check that type of property and its ivar are type compatible. 1375 if (!Context.hasSameType(PropertyIvarType, IvarType)) { 1376 if (isa<ObjCObjectPointerType>(PropertyIvarType) 1377 && isa<ObjCObjectPointerType>(IvarType)) 1378 compat = 1379 Context.canAssignObjCInterfaces( 1380 PropertyIvarType->getAs<ObjCObjectPointerType>(), 1381 IvarType->getAs<ObjCObjectPointerType>()); 1382 else { 1383 compat = (CheckAssignmentConstraints(PropertyIvarLoc, PropertyIvarType, 1384 IvarType) 1385 == Compatible); 1386 } 1387 if (!compat) { 1388 Diag(PropertyDiagLoc, diag::err_property_ivar_type) 1389 << property->getDeclName() << PropType 1390 << Ivar->getDeclName() << IvarType; 1391 Diag(Ivar->getLocation(), diag::note_ivar_decl); 1392 // Note! I deliberately want it to fall thru so, we have a 1393 // a property implementation and to avoid future warnings. 1394 } 1395 else { 1396 // FIXME! Rules for properties are somewhat different that those 1397 // for assignments. Use a new routine to consolidate all cases; 1398 // specifically for property redeclarations as well as for ivars. 1399 QualType lhsType =Context.getCanonicalType(PropertyIvarType).getUnqualifiedType(); 1400 QualType rhsType =Context.getCanonicalType(IvarType).getUnqualifiedType(); 1401 if (lhsType != rhsType && 1402 lhsType->isArithmeticType()) { 1403 Diag(PropertyDiagLoc, diag::err_property_ivar_type) 1404 << property->getDeclName() << PropType 1405 << Ivar->getDeclName() << IvarType; 1406 Diag(Ivar->getLocation(), diag::note_ivar_decl); 1407 // Fall thru - see previous comment 1408 } 1409 } 1410 // __weak is explicit. So it works on Canonical type. 1411 if ((PropType.isObjCGCWeak() && !IvarType.isObjCGCWeak() && 1412 getLangOpts().getGC() != LangOptions::NonGC)) { 1413 Diag(PropertyDiagLoc, diag::err_weak_property) 1414 << property->getDeclName() << Ivar->getDeclName(); 1415 Diag(Ivar->getLocation(), diag::note_ivar_decl); 1416 // Fall thru - see previous comment 1417 } 1418 // Fall thru - see previous comment 1419 if ((property->getType()->isObjCObjectPointerType() || 1420 PropType.isObjCGCStrong()) && IvarType.isObjCGCWeak() && 1421 getLangOpts().getGC() != LangOptions::NonGC) { 1422 Diag(PropertyDiagLoc, diag::err_strong_property) 1423 << property->getDeclName() << Ivar->getDeclName(); 1424 // Fall thru - see previous comment 1425 } 1426 } 1427 if (getLangOpts().ObjCAutoRefCount || isARCWeak || 1428 Ivar->getType().getObjCLifetime()) 1429 checkARCPropertyImpl(*this, PropertyLoc, property, Ivar); 1430 } else if (PropertyIvar) 1431 // @dynamic 1432 Diag(PropertyDiagLoc, diag::err_dynamic_property_ivar_decl); 1433 1434 assert (property && "ActOnPropertyImplDecl - property declaration missing"); 1435 ObjCPropertyImplDecl *PIDecl = 1436 ObjCPropertyImplDecl::Create(Context, CurContext, AtLoc, PropertyLoc, 1437 property, 1438 (Synthesize ? 1439 ObjCPropertyImplDecl::Synthesize 1440 : ObjCPropertyImplDecl::Dynamic), 1441 Ivar, PropertyIvarLoc); 1442 1443 if (CompleteTypeErr || !compat) 1444 PIDecl->setInvalidDecl(); 1445 1446 if (ObjCMethodDecl *getterMethod = property->getGetterMethodDecl()) { 1447 getterMethod->createImplicitParams(Context, IDecl); 1448 1449 // Redeclare the getter within the implementation as DeclContext. 1450 if (Synthesize) { 1451 // If the method hasn't been overridden, create a synthesized implementation. 1452 ObjCMethodDecl *OMD = ClassImpDecl->getMethod( 1453 getterMethod->getSelector(), getterMethod->isInstanceMethod()); 1454 if (!OMD) 1455 OMD = RedeclarePropertyAccessor(Context, IC, getterMethod, AtLoc, 1456 PropertyLoc); 1457 PIDecl->setGetterMethodDecl(OMD); 1458 } 1459 1460 if (getLangOpts().CPlusPlus && Synthesize && !CompleteTypeErr && 1461 Ivar->getType()->isRecordType()) { 1462 // For Objective-C++, need to synthesize the AST for the IVAR object to be 1463 // returned by the getter as it must conform to C++'s copy-return rules. 1464 // FIXME. Eventually we want to do this for Objective-C as well. 1465 SynthesizedFunctionScope Scope(*this, getterMethod); 1466 ImplicitParamDecl *SelfDecl = getterMethod->getSelfDecl(); 1467 DeclRefExpr *SelfExpr = new (Context) 1468 DeclRefExpr(Context, SelfDecl, false, SelfDecl->getType(), VK_LValue, 1469 PropertyDiagLoc); 1470 MarkDeclRefReferenced(SelfExpr); 1471 Expr *LoadSelfExpr = 1472 ImplicitCastExpr::Create(Context, SelfDecl->getType(), 1473 CK_LValueToRValue, SelfExpr, nullptr, 1474 VK_RValue); 1475 Expr *IvarRefExpr = 1476 new (Context) ObjCIvarRefExpr(Ivar, 1477 Ivar->getUsageType(SelfDecl->getType()), 1478 PropertyDiagLoc, 1479 Ivar->getLocation(), 1480 LoadSelfExpr, true, true); 1481 ExprResult Res = PerformCopyInitialization( 1482 InitializedEntity::InitializeResult(PropertyDiagLoc, 1483 getterMethod->getReturnType(), 1484 /*NRVO=*/false), 1485 PropertyDiagLoc, IvarRefExpr); 1486 if (!Res.isInvalid()) { 1487 Expr *ResExpr = Res.getAs<Expr>(); 1488 if (ResExpr) 1489 ResExpr = MaybeCreateExprWithCleanups(ResExpr); 1490 PIDecl->setGetterCXXConstructor(ResExpr); 1491 } 1492 } 1493 if (property->hasAttr<NSReturnsNotRetainedAttr>() && 1494 !getterMethod->hasAttr<NSReturnsNotRetainedAttr>()) { 1495 Diag(getterMethod->getLocation(), 1496 diag::warn_property_getter_owning_mismatch); 1497 Diag(property->getLocation(), diag::note_property_declare); 1498 } 1499 if (getLangOpts().ObjCAutoRefCount && Synthesize) 1500 switch (getterMethod->getMethodFamily()) { 1501 case OMF_retain: 1502 case OMF_retainCount: 1503 case OMF_release: 1504 case OMF_autorelease: 1505 Diag(getterMethod->getLocation(), diag::err_arc_illegal_method_def) 1506 << 1 << getterMethod->getSelector(); 1507 break; 1508 default: 1509 break; 1510 } 1511 } 1512 1513 if (ObjCMethodDecl *setterMethod = property->getSetterMethodDecl()) { 1514 setterMethod->createImplicitParams(Context, IDecl); 1515 1516 // Redeclare the setter within the implementation as DeclContext. 1517 if (Synthesize) { 1518 ObjCMethodDecl *OMD = ClassImpDecl->getMethod( 1519 setterMethod->getSelector(), setterMethod->isInstanceMethod()); 1520 if (!OMD) 1521 OMD = RedeclarePropertyAccessor(Context, IC, setterMethod, 1522 AtLoc, PropertyLoc); 1523 PIDecl->setSetterMethodDecl(OMD); 1524 } 1525 1526 if (getLangOpts().CPlusPlus && Synthesize && !CompleteTypeErr && 1527 Ivar->getType()->isRecordType()) { 1528 // FIXME. Eventually we want to do this for Objective-C as well. 1529 SynthesizedFunctionScope Scope(*this, setterMethod); 1530 ImplicitParamDecl *SelfDecl = setterMethod->getSelfDecl(); 1531 DeclRefExpr *SelfExpr = new (Context) 1532 DeclRefExpr(Context, SelfDecl, false, SelfDecl->getType(), VK_LValue, 1533 PropertyDiagLoc); 1534 MarkDeclRefReferenced(SelfExpr); 1535 Expr *LoadSelfExpr = 1536 ImplicitCastExpr::Create(Context, SelfDecl->getType(), 1537 CK_LValueToRValue, SelfExpr, nullptr, 1538 VK_RValue); 1539 Expr *lhs = 1540 new (Context) ObjCIvarRefExpr(Ivar, 1541 Ivar->getUsageType(SelfDecl->getType()), 1542 PropertyDiagLoc, 1543 Ivar->getLocation(), 1544 LoadSelfExpr, true, true); 1545 ObjCMethodDecl::param_iterator P = setterMethod->param_begin(); 1546 ParmVarDecl *Param = (*P); 1547 QualType T = Param->getType().getNonReferenceType(); 1548 DeclRefExpr *rhs = new (Context) 1549 DeclRefExpr(Context, Param, false, T, VK_LValue, PropertyDiagLoc); 1550 MarkDeclRefReferenced(rhs); 1551 ExprResult Res = BuildBinOp(S, PropertyDiagLoc, 1552 BO_Assign, lhs, rhs); 1553 if (property->getPropertyAttributes() & 1554 ObjCPropertyDecl::OBJC_PR_atomic) { 1555 Expr *callExpr = Res.getAs<Expr>(); 1556 if (const CXXOperatorCallExpr *CXXCE = 1557 dyn_cast_or_null<CXXOperatorCallExpr>(callExpr)) 1558 if (const FunctionDecl *FuncDecl = CXXCE->getDirectCallee()) 1559 if (!FuncDecl->isTrivial()) 1560 if (property->getType()->isReferenceType()) { 1561 Diag(PropertyDiagLoc, 1562 diag::err_atomic_property_nontrivial_assign_op) 1563 << property->getType(); 1564 Diag(FuncDecl->getBeginLoc(), diag::note_callee_decl) 1565 << FuncDecl; 1566 } 1567 } 1568 PIDecl->setSetterCXXAssignment(Res.getAs<Expr>()); 1569 } 1570 } 1571 1572 if (IC) { 1573 if (Synthesize) 1574 if (ObjCPropertyImplDecl *PPIDecl = 1575 IC->FindPropertyImplIvarDecl(PropertyIvar)) { 1576 Diag(PropertyLoc, diag::err_duplicate_ivar_use) 1577 << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier() 1578 << PropertyIvar; 1579 Diag(PPIDecl->getLocation(), diag::note_previous_use); 1580 } 1581 1582 if (ObjCPropertyImplDecl *PPIDecl 1583 = IC->FindPropertyImplDecl(PropertyId, QueryKind)) { 1584 Diag(PropertyLoc, diag::err_property_implemented) << PropertyId; 1585 Diag(PPIDecl->getLocation(), diag::note_previous_declaration); 1586 return nullptr; 1587 } 1588 IC->addPropertyImplementation(PIDecl); 1589 if (getLangOpts().ObjCDefaultSynthProperties && 1590 getLangOpts().ObjCRuntime.isNonFragile() && 1591 !IDecl->isObjCRequiresPropertyDefs()) { 1592 // Diagnose if an ivar was lazily synthesdized due to a previous 1593 // use and if 1) property is @dynamic or 2) property is synthesized 1594 // but it requires an ivar of different name. 1595 ObjCInterfaceDecl *ClassDeclared=nullptr; 1596 ObjCIvarDecl *Ivar = nullptr; 1597 if (!Synthesize) 1598 Ivar = IDecl->lookupInstanceVariable(PropertyId, ClassDeclared); 1599 else { 1600 if (PropertyIvar && PropertyIvar != PropertyId) 1601 Ivar = IDecl->lookupInstanceVariable(PropertyId, ClassDeclared); 1602 } 1603 // Issue diagnostics only if Ivar belongs to current class. 1604 if (Ivar && Ivar->getSynthesize() && 1605 declaresSameEntity(IC->getClassInterface(), ClassDeclared)) { 1606 Diag(Ivar->getLocation(), diag::err_undeclared_var_use) 1607 << PropertyId; 1608 Ivar->setInvalidDecl(); 1609 } 1610 } 1611 } else { 1612 if (Synthesize) 1613 if (ObjCPropertyImplDecl *PPIDecl = 1614 CatImplClass->FindPropertyImplIvarDecl(PropertyIvar)) { 1615 Diag(PropertyDiagLoc, diag::err_duplicate_ivar_use) 1616 << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier() 1617 << PropertyIvar; 1618 Diag(PPIDecl->getLocation(), diag::note_previous_use); 1619 } 1620 1621 if (ObjCPropertyImplDecl *PPIDecl = 1622 CatImplClass->FindPropertyImplDecl(PropertyId, QueryKind)) { 1623 Diag(PropertyDiagLoc, diag::err_property_implemented) << PropertyId; 1624 Diag(PPIDecl->getLocation(), diag::note_previous_declaration); 1625 return nullptr; 1626 } 1627 CatImplClass->addPropertyImplementation(PIDecl); 1628 } 1629 1630 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic && 1631 PIDecl->getPropertyDecl() && 1632 PIDecl->getPropertyDecl()->isDirectProperty()) { 1633 Diag(PropertyLoc, diag::err_objc_direct_dynamic_property); 1634 Diag(PIDecl->getPropertyDecl()->getLocation(), 1635 diag::note_previous_declaration); 1636 return nullptr; 1637 } 1638 1639 return PIDecl; 1640 } 1641 1642 //===----------------------------------------------------------------------===// 1643 // Helper methods. 1644 //===----------------------------------------------------------------------===// 1645 1646 /// DiagnosePropertyMismatch - Compares two properties for their 1647 /// attributes and types and warns on a variety of inconsistencies. 1648 /// 1649 void 1650 Sema::DiagnosePropertyMismatch(ObjCPropertyDecl *Property, 1651 ObjCPropertyDecl *SuperProperty, 1652 const IdentifierInfo *inheritedName, 1653 bool OverridingProtocolProperty) { 1654 ObjCPropertyDecl::PropertyAttributeKind CAttr = 1655 Property->getPropertyAttributes(); 1656 ObjCPropertyDecl::PropertyAttributeKind SAttr = 1657 SuperProperty->getPropertyAttributes(); 1658 1659 // We allow readonly properties without an explicit ownership 1660 // (assign/unsafe_unretained/weak/retain/strong/copy) in super class 1661 // to be overridden by a property with any explicit ownership in the subclass. 1662 if (!OverridingProtocolProperty && 1663 !getOwnershipRule(SAttr) && getOwnershipRule(CAttr)) 1664 ; 1665 else { 1666 if ((CAttr & ObjCPropertyDecl::OBJC_PR_readonly) 1667 && (SAttr & ObjCPropertyDecl::OBJC_PR_readwrite)) 1668 Diag(Property->getLocation(), diag::warn_readonly_property) 1669 << Property->getDeclName() << inheritedName; 1670 if ((CAttr & ObjCPropertyDecl::OBJC_PR_copy) 1671 != (SAttr & ObjCPropertyDecl::OBJC_PR_copy)) 1672 Diag(Property->getLocation(), diag::warn_property_attribute) 1673 << Property->getDeclName() << "copy" << inheritedName; 1674 else if (!(SAttr & ObjCPropertyDecl::OBJC_PR_readonly)){ 1675 unsigned CAttrRetain = 1676 (CAttr & 1677 (ObjCPropertyDecl::OBJC_PR_retain | ObjCPropertyDecl::OBJC_PR_strong)); 1678 unsigned SAttrRetain = 1679 (SAttr & 1680 (ObjCPropertyDecl::OBJC_PR_retain | ObjCPropertyDecl::OBJC_PR_strong)); 1681 bool CStrong = (CAttrRetain != 0); 1682 bool SStrong = (SAttrRetain != 0); 1683 if (CStrong != SStrong) 1684 Diag(Property->getLocation(), diag::warn_property_attribute) 1685 << Property->getDeclName() << "retain (or strong)" << inheritedName; 1686 } 1687 } 1688 1689 // Check for nonatomic; note that nonatomic is effectively 1690 // meaningless for readonly properties, so don't diagnose if the 1691 // atomic property is 'readonly'. 1692 checkAtomicPropertyMismatch(*this, SuperProperty, Property, false); 1693 // Readonly properties from protocols can be implemented as "readwrite" 1694 // with a custom setter name. 1695 if (Property->getSetterName() != SuperProperty->getSetterName() && 1696 !(SuperProperty->isReadOnly() && 1697 isa<ObjCProtocolDecl>(SuperProperty->getDeclContext()))) { 1698 Diag(Property->getLocation(), diag::warn_property_attribute) 1699 << Property->getDeclName() << "setter" << inheritedName; 1700 Diag(SuperProperty->getLocation(), diag::note_property_declare); 1701 } 1702 if (Property->getGetterName() != SuperProperty->getGetterName()) { 1703 Diag(Property->getLocation(), diag::warn_property_attribute) 1704 << Property->getDeclName() << "getter" << inheritedName; 1705 Diag(SuperProperty->getLocation(), diag::note_property_declare); 1706 } 1707 1708 QualType LHSType = 1709 Context.getCanonicalType(SuperProperty->getType()); 1710 QualType RHSType = 1711 Context.getCanonicalType(Property->getType()); 1712 1713 if (!Context.propertyTypesAreCompatible(LHSType, RHSType)) { 1714 // Do cases not handled in above. 1715 // FIXME. For future support of covariant property types, revisit this. 1716 bool IncompatibleObjC = false; 1717 QualType ConvertedType; 1718 if (!isObjCPointerConversion(RHSType, LHSType, 1719 ConvertedType, IncompatibleObjC) || 1720 IncompatibleObjC) { 1721 Diag(Property->getLocation(), diag::warn_property_types_are_incompatible) 1722 << Property->getType() << SuperProperty->getType() << inheritedName; 1723 Diag(SuperProperty->getLocation(), diag::note_property_declare); 1724 } 1725 } 1726 } 1727 1728 bool Sema::DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *property, 1729 ObjCMethodDecl *GetterMethod, 1730 SourceLocation Loc) { 1731 if (!GetterMethod) 1732 return false; 1733 QualType GetterType = GetterMethod->getReturnType().getNonReferenceType(); 1734 QualType PropertyRValueType = 1735 property->getType().getNonReferenceType().getAtomicUnqualifiedType(); 1736 bool compat = Context.hasSameType(PropertyRValueType, GetterType); 1737 if (!compat) { 1738 const ObjCObjectPointerType *propertyObjCPtr = nullptr; 1739 const ObjCObjectPointerType *getterObjCPtr = nullptr; 1740 if ((propertyObjCPtr = 1741 PropertyRValueType->getAs<ObjCObjectPointerType>()) && 1742 (getterObjCPtr = GetterType->getAs<ObjCObjectPointerType>())) 1743 compat = Context.canAssignObjCInterfaces(getterObjCPtr, propertyObjCPtr); 1744 else if (CheckAssignmentConstraints(Loc, GetterType, PropertyRValueType) 1745 != Compatible) { 1746 Diag(Loc, diag::err_property_accessor_type) 1747 << property->getDeclName() << PropertyRValueType 1748 << GetterMethod->getSelector() << GetterType; 1749 Diag(GetterMethod->getLocation(), diag::note_declared_at); 1750 return true; 1751 } else { 1752 compat = true; 1753 QualType lhsType = Context.getCanonicalType(PropertyRValueType); 1754 QualType rhsType =Context.getCanonicalType(GetterType).getUnqualifiedType(); 1755 if (lhsType != rhsType && lhsType->isArithmeticType()) 1756 compat = false; 1757 } 1758 } 1759 1760 if (!compat) { 1761 Diag(Loc, diag::warn_accessor_property_type_mismatch) 1762 << property->getDeclName() 1763 << GetterMethod->getSelector(); 1764 Diag(GetterMethod->getLocation(), diag::note_declared_at); 1765 return true; 1766 } 1767 1768 return false; 1769 } 1770 1771 /// CollectImmediateProperties - This routine collects all properties in 1772 /// the class and its conforming protocols; but not those in its super class. 1773 static void 1774 CollectImmediateProperties(ObjCContainerDecl *CDecl, 1775 ObjCContainerDecl::PropertyMap &PropMap, 1776 ObjCContainerDecl::PropertyMap &SuperPropMap, 1777 bool CollectClassPropsOnly = false, 1778 bool IncludeProtocols = true) { 1779 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 1780 for (auto *Prop : IDecl->properties()) { 1781 if (CollectClassPropsOnly && !Prop->isClassProperty()) 1782 continue; 1783 PropMap[std::make_pair(Prop->getIdentifier(), Prop->isClassProperty())] = 1784 Prop; 1785 } 1786 1787 // Collect the properties from visible extensions. 1788 for (auto *Ext : IDecl->visible_extensions()) 1789 CollectImmediateProperties(Ext, PropMap, SuperPropMap, 1790 CollectClassPropsOnly, IncludeProtocols); 1791 1792 if (IncludeProtocols) { 1793 // Scan through class's protocols. 1794 for (auto *PI : IDecl->all_referenced_protocols()) 1795 CollectImmediateProperties(PI, PropMap, SuperPropMap, 1796 CollectClassPropsOnly); 1797 } 1798 } 1799 if (ObjCCategoryDecl *CATDecl = dyn_cast<ObjCCategoryDecl>(CDecl)) { 1800 for (auto *Prop : CATDecl->properties()) { 1801 if (CollectClassPropsOnly && !Prop->isClassProperty()) 1802 continue; 1803 PropMap[std::make_pair(Prop->getIdentifier(), Prop->isClassProperty())] = 1804 Prop; 1805 } 1806 if (IncludeProtocols) { 1807 // Scan through class's protocols. 1808 for (auto *PI : CATDecl->protocols()) 1809 CollectImmediateProperties(PI, PropMap, SuperPropMap, 1810 CollectClassPropsOnly); 1811 } 1812 } 1813 else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(CDecl)) { 1814 for (auto *Prop : PDecl->properties()) { 1815 if (CollectClassPropsOnly && !Prop->isClassProperty()) 1816 continue; 1817 ObjCPropertyDecl *PropertyFromSuper = 1818 SuperPropMap[std::make_pair(Prop->getIdentifier(), 1819 Prop->isClassProperty())]; 1820 // Exclude property for protocols which conform to class's super-class, 1821 // as super-class has to implement the property. 1822 if (!PropertyFromSuper || 1823 PropertyFromSuper->getIdentifier() != Prop->getIdentifier()) { 1824 ObjCPropertyDecl *&PropEntry = 1825 PropMap[std::make_pair(Prop->getIdentifier(), 1826 Prop->isClassProperty())]; 1827 if (!PropEntry) 1828 PropEntry = Prop; 1829 } 1830 } 1831 // Scan through protocol's protocols. 1832 for (auto *PI : PDecl->protocols()) 1833 CollectImmediateProperties(PI, PropMap, SuperPropMap, 1834 CollectClassPropsOnly); 1835 } 1836 } 1837 1838 /// CollectSuperClassPropertyImplementations - This routine collects list of 1839 /// properties to be implemented in super class(s) and also coming from their 1840 /// conforming protocols. 1841 static void CollectSuperClassPropertyImplementations(ObjCInterfaceDecl *CDecl, 1842 ObjCInterfaceDecl::PropertyMap &PropMap) { 1843 if (ObjCInterfaceDecl *SDecl = CDecl->getSuperClass()) { 1844 ObjCInterfaceDecl::PropertyDeclOrder PO; 1845 while (SDecl) { 1846 SDecl->collectPropertiesToImplement(PropMap, PO); 1847 SDecl = SDecl->getSuperClass(); 1848 } 1849 } 1850 } 1851 1852 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is 1853 /// an ivar synthesized for 'Method' and 'Method' is a property accessor 1854 /// declared in class 'IFace'. 1855 bool 1856 Sema::IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, 1857 ObjCMethodDecl *Method, ObjCIvarDecl *IV) { 1858 if (!IV->getSynthesize()) 1859 return false; 1860 ObjCMethodDecl *IMD = IFace->lookupMethod(Method->getSelector(), 1861 Method->isInstanceMethod()); 1862 if (!IMD || !IMD->isPropertyAccessor()) 1863 return false; 1864 1865 // look up a property declaration whose one of its accessors is implemented 1866 // by this method. 1867 for (const auto *Property : IFace->instance_properties()) { 1868 if ((Property->getGetterName() == IMD->getSelector() || 1869 Property->getSetterName() == IMD->getSelector()) && 1870 (Property->getPropertyIvarDecl() == IV)) 1871 return true; 1872 } 1873 // Also look up property declaration in class extension whose one of its 1874 // accessors is implemented by this method. 1875 for (const auto *Ext : IFace->known_extensions()) 1876 for (const auto *Property : Ext->instance_properties()) 1877 if ((Property->getGetterName() == IMD->getSelector() || 1878 Property->getSetterName() == IMD->getSelector()) && 1879 (Property->getPropertyIvarDecl() == IV)) 1880 return true; 1881 return false; 1882 } 1883 1884 static bool SuperClassImplementsProperty(ObjCInterfaceDecl *IDecl, 1885 ObjCPropertyDecl *Prop) { 1886 bool SuperClassImplementsGetter = false; 1887 bool SuperClassImplementsSetter = false; 1888 if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_readonly) 1889 SuperClassImplementsSetter = true; 1890 1891 while (IDecl->getSuperClass()) { 1892 ObjCInterfaceDecl *SDecl = IDecl->getSuperClass(); 1893 if (!SuperClassImplementsGetter && SDecl->getInstanceMethod(Prop->getGetterName())) 1894 SuperClassImplementsGetter = true; 1895 1896 if (!SuperClassImplementsSetter && SDecl->getInstanceMethod(Prop->getSetterName())) 1897 SuperClassImplementsSetter = true; 1898 if (SuperClassImplementsGetter && SuperClassImplementsSetter) 1899 return true; 1900 IDecl = IDecl->getSuperClass(); 1901 } 1902 return false; 1903 } 1904 1905 /// Default synthesizes all properties which must be synthesized 1906 /// in class's \@implementation. 1907 void Sema::DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl, 1908 ObjCInterfaceDecl *IDecl, 1909 SourceLocation AtEnd) { 1910 ObjCInterfaceDecl::PropertyMap PropMap; 1911 ObjCInterfaceDecl::PropertyDeclOrder PropertyOrder; 1912 IDecl->collectPropertiesToImplement(PropMap, PropertyOrder); 1913 if (PropMap.empty()) 1914 return; 1915 ObjCInterfaceDecl::PropertyMap SuperPropMap; 1916 CollectSuperClassPropertyImplementations(IDecl, SuperPropMap); 1917 1918 for (unsigned i = 0, e = PropertyOrder.size(); i != e; i++) { 1919 ObjCPropertyDecl *Prop = PropertyOrder[i]; 1920 // Is there a matching property synthesize/dynamic? 1921 if (Prop->isInvalidDecl() || 1922 Prop->isClassProperty() || 1923 Prop->getPropertyImplementation() == ObjCPropertyDecl::Optional) 1924 continue; 1925 // Property may have been synthesized by user. 1926 if (IMPDecl->FindPropertyImplDecl( 1927 Prop->getIdentifier(), Prop->getQueryKind())) 1928 continue; 1929 ObjCMethodDecl *ImpMethod = IMPDecl->getInstanceMethod(Prop->getGetterName()); 1930 if (ImpMethod && !ImpMethod->getBody()) { 1931 if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_readonly) 1932 continue; 1933 ImpMethod = IMPDecl->getInstanceMethod(Prop->getSetterName()); 1934 if (ImpMethod && !ImpMethod->getBody()) 1935 continue; 1936 } 1937 if (ObjCPropertyImplDecl *PID = 1938 IMPDecl->FindPropertyImplIvarDecl(Prop->getIdentifier())) { 1939 Diag(Prop->getLocation(), diag::warn_no_autosynthesis_shared_ivar_property) 1940 << Prop->getIdentifier(); 1941 if (PID->getLocation().isValid()) 1942 Diag(PID->getLocation(), diag::note_property_synthesize); 1943 continue; 1944 } 1945 ObjCPropertyDecl *PropInSuperClass = 1946 SuperPropMap[std::make_pair(Prop->getIdentifier(), 1947 Prop->isClassProperty())]; 1948 if (ObjCProtocolDecl *Proto = 1949 dyn_cast<ObjCProtocolDecl>(Prop->getDeclContext())) { 1950 // We won't auto-synthesize properties declared in protocols. 1951 // Suppress the warning if class's superclass implements property's 1952 // getter and implements property's setter (if readwrite property). 1953 // Or, if property is going to be implemented in its super class. 1954 if (!SuperClassImplementsProperty(IDecl, Prop) && !PropInSuperClass) { 1955 Diag(IMPDecl->getLocation(), 1956 diag::warn_auto_synthesizing_protocol_property) 1957 << Prop << Proto; 1958 Diag(Prop->getLocation(), diag::note_property_declare); 1959 std::string FixIt = 1960 (Twine("@synthesize ") + Prop->getName() + ";\n\n").str(); 1961 Diag(AtEnd, diag::note_add_synthesize_directive) 1962 << FixItHint::CreateInsertion(AtEnd, FixIt); 1963 } 1964 continue; 1965 } 1966 // If property to be implemented in the super class, ignore. 1967 if (PropInSuperClass) { 1968 if ((Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_readwrite) && 1969 (PropInSuperClass->getPropertyAttributes() & 1970 ObjCPropertyDecl::OBJC_PR_readonly) && 1971 !IMPDecl->getInstanceMethod(Prop->getSetterName()) && 1972 !IDecl->HasUserDeclaredSetterMethod(Prop)) { 1973 Diag(Prop->getLocation(), diag::warn_no_autosynthesis_property) 1974 << Prop->getIdentifier(); 1975 Diag(PropInSuperClass->getLocation(), diag::note_property_declare); 1976 } 1977 else { 1978 Diag(Prop->getLocation(), diag::warn_autosynthesis_property_in_superclass) 1979 << Prop->getIdentifier(); 1980 Diag(PropInSuperClass->getLocation(), diag::note_property_declare); 1981 Diag(IMPDecl->getLocation(), diag::note_while_in_implementation); 1982 } 1983 continue; 1984 } 1985 // We use invalid SourceLocations for the synthesized ivars since they 1986 // aren't really synthesized at a particular location; they just exist. 1987 // Saying that they are located at the @implementation isn't really going 1988 // to help users. 1989 ObjCPropertyImplDecl *PIDecl = dyn_cast_or_null<ObjCPropertyImplDecl>( 1990 ActOnPropertyImplDecl(S, SourceLocation(), SourceLocation(), 1991 true, 1992 /* property = */ Prop->getIdentifier(), 1993 /* ivar = */ Prop->getDefaultSynthIvarName(Context), 1994 Prop->getLocation(), Prop->getQueryKind())); 1995 if (PIDecl && !Prop->isUnavailable()) { 1996 Diag(Prop->getLocation(), diag::warn_missing_explicit_synthesis); 1997 Diag(IMPDecl->getLocation(), diag::note_while_in_implementation); 1998 } 1999 } 2000 } 2001 2002 void Sema::DefaultSynthesizeProperties(Scope *S, Decl *D, 2003 SourceLocation AtEnd) { 2004 if (!LangOpts.ObjCDefaultSynthProperties || LangOpts.ObjCRuntime.isFragile()) 2005 return; 2006 ObjCImplementationDecl *IC=dyn_cast_or_null<ObjCImplementationDecl>(D); 2007 if (!IC) 2008 return; 2009 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) 2010 if (!IDecl->isObjCRequiresPropertyDefs()) 2011 DefaultSynthesizeProperties(S, IC, IDecl, AtEnd); 2012 } 2013 2014 static void DiagnoseUnimplementedAccessor( 2015 Sema &S, ObjCInterfaceDecl *PrimaryClass, Selector Method, 2016 ObjCImplDecl *IMPDecl, ObjCContainerDecl *CDecl, ObjCCategoryDecl *C, 2017 ObjCPropertyDecl *Prop, 2018 llvm::SmallPtrSet<const ObjCMethodDecl *, 8> &SMap) { 2019 // Check to see if we have a corresponding selector in SMap and with the 2020 // right method type. 2021 auto I = llvm::find_if(SMap, [&](const ObjCMethodDecl *x) { 2022 return x->getSelector() == Method && 2023 x->isClassMethod() == Prop->isClassProperty(); 2024 }); 2025 // When reporting on missing property setter/getter implementation in 2026 // categories, do not report when they are declared in primary class, 2027 // class's protocol, or one of it super classes. This is because, 2028 // the class is going to implement them. 2029 if (I == SMap.end() && 2030 (PrimaryClass == nullptr || 2031 !PrimaryClass->lookupPropertyAccessor(Method, C, 2032 Prop->isClassProperty()))) { 2033 unsigned diag = 2034 isa<ObjCCategoryDecl>(CDecl) 2035 ? (Prop->isClassProperty() 2036 ? diag::warn_impl_required_in_category_for_class_property 2037 : diag::warn_setter_getter_impl_required_in_category) 2038 : (Prop->isClassProperty() 2039 ? diag::warn_impl_required_for_class_property 2040 : diag::warn_setter_getter_impl_required); 2041 S.Diag(IMPDecl->getLocation(), diag) << Prop->getDeclName() << Method; 2042 S.Diag(Prop->getLocation(), diag::note_property_declare); 2043 if (S.LangOpts.ObjCDefaultSynthProperties && 2044 S.LangOpts.ObjCRuntime.isNonFragile()) 2045 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CDecl)) 2046 if (const ObjCInterfaceDecl *RID = ID->isObjCRequiresPropertyDefs()) 2047 S.Diag(RID->getLocation(), diag::note_suppressed_class_declare); 2048 } 2049 } 2050 2051 void Sema::DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, 2052 ObjCContainerDecl *CDecl, 2053 bool SynthesizeProperties) { 2054 ObjCContainerDecl::PropertyMap PropMap; 2055 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl); 2056 2057 // Since we don't synthesize class properties, we should emit diagnose even 2058 // if SynthesizeProperties is true. 2059 ObjCContainerDecl::PropertyMap NoNeedToImplPropMap; 2060 // Gather properties which need not be implemented in this class 2061 // or category. 2062 if (!IDecl) 2063 if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) { 2064 // For categories, no need to implement properties declared in 2065 // its primary class (and its super classes) if property is 2066 // declared in one of those containers. 2067 if ((IDecl = C->getClassInterface())) { 2068 ObjCInterfaceDecl::PropertyDeclOrder PO; 2069 IDecl->collectPropertiesToImplement(NoNeedToImplPropMap, PO); 2070 } 2071 } 2072 if (IDecl) 2073 CollectSuperClassPropertyImplementations(IDecl, NoNeedToImplPropMap); 2074 2075 // When SynthesizeProperties is true, we only check class properties. 2076 CollectImmediateProperties(CDecl, PropMap, NoNeedToImplPropMap, 2077 SynthesizeProperties/*CollectClassPropsOnly*/); 2078 2079 // Scan the @interface to see if any of the protocols it adopts 2080 // require an explicit implementation, via attribute 2081 // 'objc_protocol_requires_explicit_implementation'. 2082 if (IDecl) { 2083 std::unique_ptr<ObjCContainerDecl::PropertyMap> LazyMap; 2084 2085 for (auto *PDecl : IDecl->all_referenced_protocols()) { 2086 if (!PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) 2087 continue; 2088 // Lazily construct a set of all the properties in the @interface 2089 // of the class, without looking at the superclass. We cannot 2090 // use the call to CollectImmediateProperties() above as that 2091 // utilizes information from the super class's properties as well 2092 // as scans the adopted protocols. This work only triggers for protocols 2093 // with the attribute, which is very rare, and only occurs when 2094 // analyzing the @implementation. 2095 if (!LazyMap) { 2096 ObjCContainerDecl::PropertyMap NoNeedToImplPropMap; 2097 LazyMap.reset(new ObjCContainerDecl::PropertyMap()); 2098 CollectImmediateProperties(CDecl, *LazyMap, NoNeedToImplPropMap, 2099 /* CollectClassPropsOnly */ false, 2100 /* IncludeProtocols */ false); 2101 } 2102 // Add the properties of 'PDecl' to the list of properties that 2103 // need to be implemented. 2104 for (auto *PropDecl : PDecl->properties()) { 2105 if ((*LazyMap)[std::make_pair(PropDecl->getIdentifier(), 2106 PropDecl->isClassProperty())]) 2107 continue; 2108 PropMap[std::make_pair(PropDecl->getIdentifier(), 2109 PropDecl->isClassProperty())] = PropDecl; 2110 } 2111 } 2112 } 2113 2114 if (PropMap.empty()) 2115 return; 2116 2117 llvm::DenseSet<ObjCPropertyDecl *> PropImplMap; 2118 for (const auto *I : IMPDecl->property_impls()) 2119 PropImplMap.insert(I->getPropertyDecl()); 2120 2121 llvm::SmallPtrSet<const ObjCMethodDecl *, 8> InsMap; 2122 // Collect property accessors implemented in current implementation. 2123 for (const auto *I : IMPDecl->methods()) 2124 InsMap.insert(I); 2125 2126 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl); 2127 ObjCInterfaceDecl *PrimaryClass = nullptr; 2128 if (C && !C->IsClassExtension()) 2129 if ((PrimaryClass = C->getClassInterface())) 2130 // Report unimplemented properties in the category as well. 2131 if (ObjCImplDecl *IMP = PrimaryClass->getImplementation()) { 2132 // When reporting on missing setter/getters, do not report when 2133 // setter/getter is implemented in category's primary class 2134 // implementation. 2135 for (const auto *I : IMP->methods()) 2136 InsMap.insert(I); 2137 } 2138 2139 for (ObjCContainerDecl::PropertyMap::iterator 2140 P = PropMap.begin(), E = PropMap.end(); P != E; ++P) { 2141 ObjCPropertyDecl *Prop = P->second; 2142 // Is there a matching property synthesize/dynamic? 2143 if (Prop->isInvalidDecl() || 2144 Prop->getPropertyImplementation() == ObjCPropertyDecl::Optional || 2145 PropImplMap.count(Prop) || 2146 Prop->getAvailability() == AR_Unavailable) 2147 continue; 2148 2149 // Diagnose unimplemented getters and setters. 2150 DiagnoseUnimplementedAccessor(*this, 2151 PrimaryClass, Prop->getGetterName(), IMPDecl, CDecl, C, Prop, InsMap); 2152 if (!Prop->isReadOnly()) 2153 DiagnoseUnimplementedAccessor(*this, 2154 PrimaryClass, Prop->getSetterName(), 2155 IMPDecl, CDecl, C, Prop, InsMap); 2156 } 2157 } 2158 2159 void Sema::diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl) { 2160 for (const auto *propertyImpl : impDecl->property_impls()) { 2161 const auto *property = propertyImpl->getPropertyDecl(); 2162 // Warn about null_resettable properties with synthesized setters, 2163 // because the setter won't properly handle nil. 2164 if (propertyImpl->getPropertyImplementation() 2165 == ObjCPropertyImplDecl::Synthesize && 2166 (property->getPropertyAttributes() & 2167 ObjCPropertyDecl::OBJC_PR_null_resettable) && 2168 property->getGetterMethodDecl() && 2169 property->getSetterMethodDecl()) { 2170 auto *getterImpl = propertyImpl->getGetterMethodDecl(); 2171 auto *setterImpl = propertyImpl->getSetterMethodDecl(); 2172 if ((!getterImpl || getterImpl->isSynthesizedAccessorStub()) && 2173 (!setterImpl || setterImpl->isSynthesizedAccessorStub())) { 2174 SourceLocation loc = propertyImpl->getLocation(); 2175 if (loc.isInvalid()) 2176 loc = impDecl->getBeginLoc(); 2177 2178 Diag(loc, diag::warn_null_resettable_setter) 2179 << setterImpl->getSelector() << property->getDeclName(); 2180 } 2181 } 2182 } 2183 } 2184 2185 void 2186 Sema::AtomicPropertySetterGetterRules (ObjCImplDecl* IMPDecl, 2187 ObjCInterfaceDecl* IDecl) { 2188 // Rules apply in non-GC mode only 2189 if (getLangOpts().getGC() != LangOptions::NonGC) 2190 return; 2191 ObjCContainerDecl::PropertyMap PM; 2192 for (auto *Prop : IDecl->properties()) 2193 PM[std::make_pair(Prop->getIdentifier(), Prop->isClassProperty())] = Prop; 2194 for (const auto *Ext : IDecl->known_extensions()) 2195 for (auto *Prop : Ext->properties()) 2196 PM[std::make_pair(Prop->getIdentifier(), Prop->isClassProperty())] = Prop; 2197 2198 for (ObjCContainerDecl::PropertyMap::iterator I = PM.begin(), E = PM.end(); 2199 I != E; ++I) { 2200 const ObjCPropertyDecl *Property = I->second; 2201 ObjCMethodDecl *GetterMethod = nullptr; 2202 ObjCMethodDecl *SetterMethod = nullptr; 2203 2204 unsigned Attributes = Property->getPropertyAttributes(); 2205 unsigned AttributesAsWritten = Property->getPropertyAttributesAsWritten(); 2206 2207 if (!(AttributesAsWritten & ObjCPropertyDecl::OBJC_PR_atomic) && 2208 !(AttributesAsWritten & ObjCPropertyDecl::OBJC_PR_nonatomic)) { 2209 GetterMethod = Property->isClassProperty() ? 2210 IMPDecl->getClassMethod(Property->getGetterName()) : 2211 IMPDecl->getInstanceMethod(Property->getGetterName()); 2212 SetterMethod = Property->isClassProperty() ? 2213 IMPDecl->getClassMethod(Property->getSetterName()) : 2214 IMPDecl->getInstanceMethod(Property->getSetterName()); 2215 if (GetterMethod && GetterMethod->isSynthesizedAccessorStub()) 2216 GetterMethod = nullptr; 2217 if (SetterMethod && SetterMethod->isSynthesizedAccessorStub()) 2218 SetterMethod = nullptr; 2219 if (GetterMethod) { 2220 Diag(GetterMethod->getLocation(), 2221 diag::warn_default_atomic_custom_getter_setter) 2222 << Property->getIdentifier() << 0; 2223 Diag(Property->getLocation(), diag::note_property_declare); 2224 } 2225 if (SetterMethod) { 2226 Diag(SetterMethod->getLocation(), 2227 diag::warn_default_atomic_custom_getter_setter) 2228 << Property->getIdentifier() << 1; 2229 Diag(Property->getLocation(), diag::note_property_declare); 2230 } 2231 } 2232 2233 // We only care about readwrite atomic property. 2234 if ((Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) || 2235 !(Attributes & ObjCPropertyDecl::OBJC_PR_readwrite)) 2236 continue; 2237 if (const ObjCPropertyImplDecl *PIDecl = IMPDecl->FindPropertyImplDecl( 2238 Property->getIdentifier(), Property->getQueryKind())) { 2239 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) 2240 continue; 2241 GetterMethod = PIDecl->getGetterMethodDecl(); 2242 SetterMethod = PIDecl->getSetterMethodDecl(); 2243 if (GetterMethod && GetterMethod->isSynthesizedAccessorStub()) 2244 GetterMethod = nullptr; 2245 if (SetterMethod && SetterMethod->isSynthesizedAccessorStub()) 2246 SetterMethod = nullptr; 2247 if ((bool)GetterMethod ^ (bool)SetterMethod) { 2248 SourceLocation MethodLoc = 2249 (GetterMethod ? GetterMethod->getLocation() 2250 : SetterMethod->getLocation()); 2251 Diag(MethodLoc, diag::warn_atomic_property_rule) 2252 << Property->getIdentifier() << (GetterMethod != nullptr) 2253 << (SetterMethod != nullptr); 2254 // fixit stuff. 2255 if (Property->getLParenLoc().isValid() && 2256 !(AttributesAsWritten & ObjCPropertyDecl::OBJC_PR_atomic)) { 2257 // @property () ... case. 2258 SourceLocation AfterLParen = 2259 getLocForEndOfToken(Property->getLParenLoc()); 2260 StringRef NonatomicStr = AttributesAsWritten? "nonatomic, " 2261 : "nonatomic"; 2262 Diag(Property->getLocation(), 2263 diag::note_atomic_property_fixup_suggest) 2264 << FixItHint::CreateInsertion(AfterLParen, NonatomicStr); 2265 } else if (Property->getLParenLoc().isInvalid()) { 2266 //@property id etc. 2267 SourceLocation startLoc = 2268 Property->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); 2269 Diag(Property->getLocation(), 2270 diag::note_atomic_property_fixup_suggest) 2271 << FixItHint::CreateInsertion(startLoc, "(nonatomic) "); 2272 } 2273 else 2274 Diag(MethodLoc, diag::note_atomic_property_fixup_suggest); 2275 Diag(Property->getLocation(), diag::note_property_declare); 2276 } 2277 } 2278 } 2279 } 2280 2281 void Sema::DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D) { 2282 if (getLangOpts().getGC() == LangOptions::GCOnly) 2283 return; 2284 2285 for (const auto *PID : D->property_impls()) { 2286 const ObjCPropertyDecl *PD = PID->getPropertyDecl(); 2287 if (PD && !PD->hasAttr<NSReturnsNotRetainedAttr>() && 2288 !PD->isClassProperty()) { 2289 ObjCMethodDecl *IM = PID->getGetterMethodDecl(); 2290 if (IM && !IM->isSynthesizedAccessorStub()) 2291 continue; 2292 ObjCMethodDecl *method = PD->getGetterMethodDecl(); 2293 if (!method) 2294 continue; 2295 ObjCMethodFamily family = method->getMethodFamily(); 2296 if (family == OMF_alloc || family == OMF_copy || 2297 family == OMF_mutableCopy || family == OMF_new) { 2298 if (getLangOpts().ObjCAutoRefCount) 2299 Diag(PD->getLocation(), diag::err_cocoa_naming_owned_rule); 2300 else 2301 Diag(PD->getLocation(), diag::warn_cocoa_naming_owned_rule); 2302 2303 // Look for a getter explicitly declared alongside the property. 2304 // If we find one, use its location for the note. 2305 SourceLocation noteLoc = PD->getLocation(); 2306 SourceLocation fixItLoc; 2307 for (auto *getterRedecl : method->redecls()) { 2308 if (getterRedecl->isImplicit()) 2309 continue; 2310 if (getterRedecl->getDeclContext() != PD->getDeclContext()) 2311 continue; 2312 noteLoc = getterRedecl->getLocation(); 2313 fixItLoc = getterRedecl->getEndLoc(); 2314 } 2315 2316 Preprocessor &PP = getPreprocessor(); 2317 TokenValue tokens[] = { 2318 tok::kw___attribute, tok::l_paren, tok::l_paren, 2319 PP.getIdentifierInfo("objc_method_family"), tok::l_paren, 2320 PP.getIdentifierInfo("none"), tok::r_paren, 2321 tok::r_paren, tok::r_paren 2322 }; 2323 StringRef spelling = "__attribute__((objc_method_family(none)))"; 2324 StringRef macroName = PP.getLastMacroWithSpelling(noteLoc, tokens); 2325 if (!macroName.empty()) 2326 spelling = macroName; 2327 2328 auto noteDiag = Diag(noteLoc, diag::note_cocoa_naming_declare_family) 2329 << method->getDeclName() << spelling; 2330 if (fixItLoc.isValid()) { 2331 SmallString<64> fixItText(" "); 2332 fixItText += spelling; 2333 noteDiag << FixItHint::CreateInsertion(fixItLoc, fixItText); 2334 } 2335 } 2336 } 2337 } 2338 } 2339 2340 void Sema::DiagnoseMissingDesignatedInitOverrides( 2341 const ObjCImplementationDecl *ImplD, 2342 const ObjCInterfaceDecl *IFD) { 2343 assert(IFD->hasDesignatedInitializers()); 2344 const ObjCInterfaceDecl *SuperD = IFD->getSuperClass(); 2345 if (!SuperD) 2346 return; 2347 2348 SelectorSet InitSelSet; 2349 for (const auto *I : ImplD->instance_methods()) 2350 if (I->getMethodFamily() == OMF_init) 2351 InitSelSet.insert(I->getSelector()); 2352 2353 SmallVector<const ObjCMethodDecl *, 8> DesignatedInits; 2354 SuperD->getDesignatedInitializers(DesignatedInits); 2355 for (SmallVector<const ObjCMethodDecl *, 8>::iterator 2356 I = DesignatedInits.begin(), E = DesignatedInits.end(); I != E; ++I) { 2357 const ObjCMethodDecl *MD = *I; 2358 if (!InitSelSet.count(MD->getSelector())) { 2359 // Don't emit a diagnostic if the overriding method in the subclass is 2360 // marked as unavailable. 2361 bool Ignore = false; 2362 if (auto *IMD = IFD->getInstanceMethod(MD->getSelector())) { 2363 Ignore = IMD->isUnavailable(); 2364 } else { 2365 // Check the methods declared in the class extensions too. 2366 for (auto *Ext : IFD->visible_extensions()) 2367 if (auto *IMD = Ext->getInstanceMethod(MD->getSelector())) { 2368 Ignore = IMD->isUnavailable(); 2369 break; 2370 } 2371 } 2372 if (!Ignore) { 2373 Diag(ImplD->getLocation(), 2374 diag::warn_objc_implementation_missing_designated_init_override) 2375 << MD->getSelector(); 2376 Diag(MD->getLocation(), diag::note_objc_designated_init_marked_here); 2377 } 2378 } 2379 } 2380 } 2381 2382 /// AddPropertyAttrs - Propagates attributes from a property to the 2383 /// implicitly-declared getter or setter for that property. 2384 static void AddPropertyAttrs(Sema &S, ObjCMethodDecl *PropertyMethod, 2385 ObjCPropertyDecl *Property) { 2386 // Should we just clone all attributes over? 2387 for (const auto *A : Property->attrs()) { 2388 if (isa<DeprecatedAttr>(A) || 2389 isa<UnavailableAttr>(A) || 2390 isa<AvailabilityAttr>(A)) 2391 PropertyMethod->addAttr(A->clone(S.Context)); 2392 } 2393 } 2394 2395 /// ProcessPropertyDecl - Make sure that any user-defined setter/getter methods 2396 /// have the property type and issue diagnostics if they don't. 2397 /// Also synthesize a getter/setter method if none exist (and update the 2398 /// appropriate lookup tables. 2399 void Sema::ProcessPropertyDecl(ObjCPropertyDecl *property) { 2400 ObjCMethodDecl *GetterMethod, *SetterMethod; 2401 ObjCContainerDecl *CD = cast<ObjCContainerDecl>(property->getDeclContext()); 2402 if (CD->isInvalidDecl()) 2403 return; 2404 2405 bool IsClassProperty = property->isClassProperty(); 2406 GetterMethod = IsClassProperty ? 2407 CD->getClassMethod(property->getGetterName()) : 2408 CD->getInstanceMethod(property->getGetterName()); 2409 2410 // if setter or getter is not found in class extension, it might be 2411 // in the primary class. 2412 if (!GetterMethod) 2413 if (const ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CD)) 2414 if (CatDecl->IsClassExtension()) 2415 GetterMethod = IsClassProperty ? CatDecl->getClassInterface()-> 2416 getClassMethod(property->getGetterName()) : 2417 CatDecl->getClassInterface()-> 2418 getInstanceMethod(property->getGetterName()); 2419 2420 SetterMethod = IsClassProperty ? 2421 CD->getClassMethod(property->getSetterName()) : 2422 CD->getInstanceMethod(property->getSetterName()); 2423 if (!SetterMethod) 2424 if (const ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CD)) 2425 if (CatDecl->IsClassExtension()) 2426 SetterMethod = IsClassProperty ? CatDecl->getClassInterface()-> 2427 getClassMethod(property->getSetterName()) : 2428 CatDecl->getClassInterface()-> 2429 getInstanceMethod(property->getSetterName()); 2430 DiagnosePropertyAccessorMismatch(property, GetterMethod, 2431 property->getLocation()); 2432 2433 // synthesizing accessors must not result in a direct method that is not 2434 // monomorphic 2435 if (!GetterMethod) { 2436 if (const ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CD)) { 2437 auto *ExistingGetter = CatDecl->getClassInterface()->lookupMethod( 2438 property->getGetterName(), !IsClassProperty, true, false, CatDecl); 2439 if (ExistingGetter) { 2440 if (ExistingGetter->isDirectMethod() || property->isDirectProperty()) { 2441 Diag(property->getLocation(), diag::err_objc_direct_duplicate_decl) 2442 << property->isDirectProperty() << 1 /* property */ 2443 << ExistingGetter->isDirectMethod() 2444 << ExistingGetter->getDeclName(); 2445 Diag(ExistingGetter->getLocation(), diag::note_previous_declaration); 2446 } 2447 } 2448 } 2449 } 2450 2451 if (!property->isReadOnly() && !SetterMethod) { 2452 if (const ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CD)) { 2453 auto *ExistingSetter = CatDecl->getClassInterface()->lookupMethod( 2454 property->getSetterName(), !IsClassProperty, true, false, CatDecl); 2455 if (ExistingSetter) { 2456 if (ExistingSetter->isDirectMethod() || property->isDirectProperty()) { 2457 Diag(property->getLocation(), diag::err_objc_direct_duplicate_decl) 2458 << property->isDirectProperty() << 1 /* property */ 2459 << ExistingSetter->isDirectMethod() 2460 << ExistingSetter->getDeclName(); 2461 Diag(ExistingSetter->getLocation(), diag::note_previous_declaration); 2462 } 2463 } 2464 } 2465 } 2466 2467 if (!property->isReadOnly() && SetterMethod) { 2468 if (Context.getCanonicalType(SetterMethod->getReturnType()) != 2469 Context.VoidTy) 2470 Diag(SetterMethod->getLocation(), diag::err_setter_type_void); 2471 if (SetterMethod->param_size() != 1 || 2472 !Context.hasSameUnqualifiedType( 2473 (*SetterMethod->param_begin())->getType().getNonReferenceType(), 2474 property->getType().getNonReferenceType())) { 2475 Diag(property->getLocation(), 2476 diag::warn_accessor_property_type_mismatch) 2477 << property->getDeclName() 2478 << SetterMethod->getSelector(); 2479 Diag(SetterMethod->getLocation(), diag::note_declared_at); 2480 } 2481 } 2482 2483 // Synthesize getter/setter methods if none exist. 2484 // Find the default getter and if one not found, add one. 2485 // FIXME: The synthesized property we set here is misleading. We almost always 2486 // synthesize these methods unless the user explicitly provided prototypes 2487 // (which is odd, but allowed). Sema should be typechecking that the 2488 // declarations jive in that situation (which it is not currently). 2489 if (!GetterMethod) { 2490 // No instance/class method of same name as property getter name was found. 2491 // Declare a getter method and add it to the list of methods 2492 // for this class. 2493 SourceLocation Loc = property->getLocation(); 2494 2495 // The getter returns the declared property type with all qualifiers 2496 // removed. 2497 QualType resultTy = property->getType().getAtomicUnqualifiedType(); 2498 2499 // If the property is null_resettable, the getter returns nonnull. 2500 if (property->getPropertyAttributes() & 2501 ObjCPropertyDecl::OBJC_PR_null_resettable) { 2502 QualType modifiedTy = resultTy; 2503 if (auto nullability = AttributedType::stripOuterNullability(modifiedTy)) { 2504 if (*nullability == NullabilityKind::Unspecified) 2505 resultTy = Context.getAttributedType(attr::TypeNonNull, 2506 modifiedTy, modifiedTy); 2507 } 2508 } 2509 2510 GetterMethod = ObjCMethodDecl::Create( 2511 Context, Loc, Loc, property->getGetterName(), resultTy, nullptr, CD, 2512 !IsClassProperty, /*isVariadic=*/false, 2513 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 2514 /*isImplicitlyDeclared=*/true, /*isDefined=*/false, 2515 (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) 2516 ? ObjCMethodDecl::Optional 2517 : ObjCMethodDecl::Required); 2518 CD->addDecl(GetterMethod); 2519 2520 AddPropertyAttrs(*this, GetterMethod, property); 2521 2522 if (property->isDirectProperty()) 2523 GetterMethod->addAttr(ObjCDirectAttr::CreateImplicit(Context, Loc)); 2524 2525 if (property->hasAttr<NSReturnsNotRetainedAttr>()) 2526 GetterMethod->addAttr(NSReturnsNotRetainedAttr::CreateImplicit(Context, 2527 Loc)); 2528 2529 if (property->hasAttr<ObjCReturnsInnerPointerAttr>()) 2530 GetterMethod->addAttr( 2531 ObjCReturnsInnerPointerAttr::CreateImplicit(Context, Loc)); 2532 2533 if (const SectionAttr *SA = property->getAttr<SectionAttr>()) 2534 GetterMethod->addAttr(SectionAttr::CreateImplicit( 2535 Context, SA->getName(), Loc, AttributeCommonInfo::AS_GNU, 2536 SectionAttr::GNU_section)); 2537 2538 if (getLangOpts().ObjCAutoRefCount) 2539 CheckARCMethodDecl(GetterMethod); 2540 } else 2541 // A user declared getter will be synthesize when @synthesize of 2542 // the property with the same name is seen in the @implementation 2543 GetterMethod->setPropertyAccessor(true); 2544 2545 GetterMethod->createImplicitParams(Context, 2546 GetterMethod->getClassInterface()); 2547 property->setGetterMethodDecl(GetterMethod); 2548 2549 // Skip setter if property is read-only. 2550 if (!property->isReadOnly()) { 2551 // Find the default setter and if one not found, add one. 2552 if (!SetterMethod) { 2553 // No instance/class method of same name as property setter name was 2554 // found. 2555 // Declare a setter method and add it to the list of methods 2556 // for this class. 2557 SourceLocation Loc = property->getLocation(); 2558 2559 SetterMethod = 2560 ObjCMethodDecl::Create(Context, Loc, Loc, 2561 property->getSetterName(), Context.VoidTy, 2562 nullptr, CD, !IsClassProperty, 2563 /*isVariadic=*/false, 2564 /*isPropertyAccessor=*/true, 2565 /*isSynthesizedAccessorStub=*/false, 2566 /*isImplicitlyDeclared=*/true, 2567 /*isDefined=*/false, 2568 (property->getPropertyImplementation() == 2569 ObjCPropertyDecl::Optional) ? 2570 ObjCMethodDecl::Optional : 2571 ObjCMethodDecl::Required); 2572 2573 // Remove all qualifiers from the setter's parameter type. 2574 QualType paramTy = 2575 property->getType().getUnqualifiedType().getAtomicUnqualifiedType(); 2576 2577 // If the property is null_resettable, the setter accepts a 2578 // nullable value. 2579 if (property->getPropertyAttributes() & 2580 ObjCPropertyDecl::OBJC_PR_null_resettable) { 2581 QualType modifiedTy = paramTy; 2582 if (auto nullability = AttributedType::stripOuterNullability(modifiedTy)){ 2583 if (*nullability == NullabilityKind::Unspecified) 2584 paramTy = Context.getAttributedType(attr::TypeNullable, 2585 modifiedTy, modifiedTy); 2586 } 2587 } 2588 2589 // Invent the arguments for the setter. We don't bother making a 2590 // nice name for the argument. 2591 ParmVarDecl *Argument = ParmVarDecl::Create(Context, SetterMethod, 2592 Loc, Loc, 2593 property->getIdentifier(), 2594 paramTy, 2595 /*TInfo=*/nullptr, 2596 SC_None, 2597 nullptr); 2598 SetterMethod->setMethodParams(Context, Argument, None); 2599 2600 AddPropertyAttrs(*this, SetterMethod, property); 2601 2602 if (property->isDirectProperty()) 2603 SetterMethod->addAttr(ObjCDirectAttr::CreateImplicit(Context, Loc)); 2604 2605 CD->addDecl(SetterMethod); 2606 if (const SectionAttr *SA = property->getAttr<SectionAttr>()) 2607 SetterMethod->addAttr(SectionAttr::CreateImplicit( 2608 Context, SA->getName(), Loc, AttributeCommonInfo::AS_GNU, 2609 SectionAttr::GNU_section)); 2610 // It's possible for the user to have set a very odd custom 2611 // setter selector that causes it to have a method family. 2612 if (getLangOpts().ObjCAutoRefCount) 2613 CheckARCMethodDecl(SetterMethod); 2614 } else 2615 // A user declared setter will be synthesize when @synthesize of 2616 // the property with the same name is seen in the @implementation 2617 SetterMethod->setPropertyAccessor(true); 2618 2619 SetterMethod->createImplicitParams(Context, 2620 SetterMethod->getClassInterface()); 2621 property->setSetterMethodDecl(SetterMethod); 2622 } 2623 // Add any synthesized methods to the global pool. This allows us to 2624 // handle the following, which is supported by GCC (and part of the design). 2625 // 2626 // @interface Foo 2627 // @property double bar; 2628 // @end 2629 // 2630 // void thisIsUnfortunate() { 2631 // id foo; 2632 // double bar = [foo bar]; 2633 // } 2634 // 2635 if (!IsClassProperty) { 2636 if (GetterMethod) 2637 AddInstanceMethodToGlobalPool(GetterMethod); 2638 if (SetterMethod) 2639 AddInstanceMethodToGlobalPool(SetterMethod); 2640 } else { 2641 if (GetterMethod) 2642 AddFactoryMethodToGlobalPool(GetterMethod); 2643 if (SetterMethod) 2644 AddFactoryMethodToGlobalPool(SetterMethod); 2645 } 2646 2647 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(CD); 2648 if (!CurrentClass) { 2649 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(CD)) 2650 CurrentClass = Cat->getClassInterface(); 2651 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(CD)) 2652 CurrentClass = Impl->getClassInterface(); 2653 } 2654 if (GetterMethod) 2655 CheckObjCMethodOverrides(GetterMethod, CurrentClass, Sema::RTC_Unknown); 2656 if (SetterMethod) 2657 CheckObjCMethodOverrides(SetterMethod, CurrentClass, Sema::RTC_Unknown); 2658 } 2659 2660 void Sema::CheckObjCPropertyAttributes(Decl *PDecl, 2661 SourceLocation Loc, 2662 unsigned &Attributes, 2663 bool propertyInPrimaryClass) { 2664 // FIXME: Improve the reported location. 2665 if (!PDecl || PDecl->isInvalidDecl()) 2666 return; 2667 2668 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) && 2669 (Attributes & ObjCDeclSpec::DQ_PR_readwrite)) 2670 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2671 << "readonly" << "readwrite"; 2672 2673 ObjCPropertyDecl *PropertyDecl = cast<ObjCPropertyDecl>(PDecl); 2674 QualType PropertyTy = PropertyDecl->getType(); 2675 2676 // Check for copy or retain on non-object types. 2677 if ((Attributes & (ObjCDeclSpec::DQ_PR_weak | ObjCDeclSpec::DQ_PR_copy | 2678 ObjCDeclSpec::DQ_PR_retain | ObjCDeclSpec::DQ_PR_strong)) && 2679 !PropertyTy->isObjCRetainableType() && 2680 !PropertyDecl->hasAttr<ObjCNSObjectAttr>()) { 2681 Diag(Loc, diag::err_objc_property_requires_object) 2682 << (Attributes & ObjCDeclSpec::DQ_PR_weak ? "weak" : 2683 Attributes & ObjCDeclSpec::DQ_PR_copy ? "copy" : "retain (or strong)"); 2684 Attributes &= ~(ObjCDeclSpec::DQ_PR_weak | ObjCDeclSpec::DQ_PR_copy | 2685 ObjCDeclSpec::DQ_PR_retain | ObjCDeclSpec::DQ_PR_strong); 2686 PropertyDecl->setInvalidDecl(); 2687 } 2688 2689 // Check for assign on object types. 2690 if ((Attributes & ObjCDeclSpec::DQ_PR_assign) && 2691 !(Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained) && 2692 PropertyTy->isObjCRetainableType() && 2693 !PropertyTy->isObjCARCImplicitlyUnretainedType()) { 2694 Diag(Loc, diag::warn_objc_property_assign_on_object); 2695 } 2696 2697 // Check for more than one of { assign, copy, retain }. 2698 if (Attributes & ObjCDeclSpec::DQ_PR_assign) { 2699 if (Attributes & ObjCDeclSpec::DQ_PR_copy) { 2700 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2701 << "assign" << "copy"; 2702 Attributes &= ~ObjCDeclSpec::DQ_PR_copy; 2703 } 2704 if (Attributes & ObjCDeclSpec::DQ_PR_retain) { 2705 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2706 << "assign" << "retain"; 2707 Attributes &= ~ObjCDeclSpec::DQ_PR_retain; 2708 } 2709 if (Attributes & ObjCDeclSpec::DQ_PR_strong) { 2710 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2711 << "assign" << "strong"; 2712 Attributes &= ~ObjCDeclSpec::DQ_PR_strong; 2713 } 2714 if (getLangOpts().ObjCAutoRefCount && 2715 (Attributes & ObjCDeclSpec::DQ_PR_weak)) { 2716 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2717 << "assign" << "weak"; 2718 Attributes &= ~ObjCDeclSpec::DQ_PR_weak; 2719 } 2720 if (PropertyDecl->hasAttr<IBOutletCollectionAttr>()) 2721 Diag(Loc, diag::warn_iboutletcollection_property_assign); 2722 } else if (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained) { 2723 if (Attributes & ObjCDeclSpec::DQ_PR_copy) { 2724 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2725 << "unsafe_unretained" << "copy"; 2726 Attributes &= ~ObjCDeclSpec::DQ_PR_copy; 2727 } 2728 if (Attributes & ObjCDeclSpec::DQ_PR_retain) { 2729 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2730 << "unsafe_unretained" << "retain"; 2731 Attributes &= ~ObjCDeclSpec::DQ_PR_retain; 2732 } 2733 if (Attributes & ObjCDeclSpec::DQ_PR_strong) { 2734 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2735 << "unsafe_unretained" << "strong"; 2736 Attributes &= ~ObjCDeclSpec::DQ_PR_strong; 2737 } 2738 if (getLangOpts().ObjCAutoRefCount && 2739 (Attributes & ObjCDeclSpec::DQ_PR_weak)) { 2740 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2741 << "unsafe_unretained" << "weak"; 2742 Attributes &= ~ObjCDeclSpec::DQ_PR_weak; 2743 } 2744 } else if (Attributes & ObjCDeclSpec::DQ_PR_copy) { 2745 if (Attributes & ObjCDeclSpec::DQ_PR_retain) { 2746 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2747 << "copy" << "retain"; 2748 Attributes &= ~ObjCDeclSpec::DQ_PR_retain; 2749 } 2750 if (Attributes & ObjCDeclSpec::DQ_PR_strong) { 2751 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2752 << "copy" << "strong"; 2753 Attributes &= ~ObjCDeclSpec::DQ_PR_strong; 2754 } 2755 if (Attributes & ObjCDeclSpec::DQ_PR_weak) { 2756 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2757 << "copy" << "weak"; 2758 Attributes &= ~ObjCDeclSpec::DQ_PR_weak; 2759 } 2760 } 2761 else if ((Attributes & ObjCDeclSpec::DQ_PR_retain) && 2762 (Attributes & ObjCDeclSpec::DQ_PR_weak)) { 2763 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2764 << "retain" << "weak"; 2765 Attributes &= ~ObjCDeclSpec::DQ_PR_retain; 2766 } 2767 else if ((Attributes & ObjCDeclSpec::DQ_PR_strong) && 2768 (Attributes & ObjCDeclSpec::DQ_PR_weak)) { 2769 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2770 << "strong" << "weak"; 2771 Attributes &= ~ObjCDeclSpec::DQ_PR_weak; 2772 } 2773 2774 if (Attributes & ObjCDeclSpec::DQ_PR_weak) { 2775 // 'weak' and 'nonnull' are mutually exclusive. 2776 if (auto nullability = PropertyTy->getNullability(Context)) { 2777 if (*nullability == NullabilityKind::NonNull) 2778 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2779 << "nonnull" << "weak"; 2780 } 2781 } 2782 2783 if ((Attributes & ObjCDeclSpec::DQ_PR_atomic) && 2784 (Attributes & ObjCDeclSpec::DQ_PR_nonatomic)) { 2785 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2786 << "atomic" << "nonatomic"; 2787 Attributes &= ~ObjCDeclSpec::DQ_PR_atomic; 2788 } 2789 2790 // Warn if user supplied no assignment attribute, property is 2791 // readwrite, and this is an object type. 2792 if (!getOwnershipRule(Attributes) && PropertyTy->isObjCRetainableType()) { 2793 if (Attributes & ObjCDeclSpec::DQ_PR_readonly) { 2794 // do nothing 2795 } else if (getLangOpts().ObjCAutoRefCount) { 2796 // With arc, @property definitions should default to strong when 2797 // not specified. 2798 PropertyDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong); 2799 } else if (PropertyTy->isObjCObjectPointerType()) { 2800 bool isAnyClassTy = 2801 (PropertyTy->isObjCClassType() || 2802 PropertyTy->isObjCQualifiedClassType()); 2803 // In non-gc, non-arc mode, 'Class' is treated as a 'void *' no need to 2804 // issue any warning. 2805 if (isAnyClassTy && getLangOpts().getGC() == LangOptions::NonGC) 2806 ; 2807 else if (propertyInPrimaryClass) { 2808 // Don't issue warning on property with no life time in class 2809 // extension as it is inherited from property in primary class. 2810 // Skip this warning in gc-only mode. 2811 if (getLangOpts().getGC() != LangOptions::GCOnly) 2812 Diag(Loc, diag::warn_objc_property_no_assignment_attribute); 2813 2814 // If non-gc code warn that this is likely inappropriate. 2815 if (getLangOpts().getGC() == LangOptions::NonGC) 2816 Diag(Loc, diag::warn_objc_property_default_assign_on_object); 2817 } 2818 } 2819 2820 // FIXME: Implement warning dependent on NSCopying being 2821 // implemented. See also: 2822 // <rdar://5168496&4855821&5607453&5096644&4947311&5698469&4947014&5168496> 2823 // (please trim this list while you are at it). 2824 } 2825 2826 if (!(Attributes & ObjCDeclSpec::DQ_PR_copy) 2827 &&!(Attributes & ObjCDeclSpec::DQ_PR_readonly) 2828 && getLangOpts().getGC() == LangOptions::GCOnly 2829 && PropertyTy->isBlockPointerType()) 2830 Diag(Loc, diag::warn_objc_property_copy_missing_on_block); 2831 else if ((Attributes & ObjCDeclSpec::DQ_PR_retain) && 2832 !(Attributes & ObjCDeclSpec::DQ_PR_readonly) && 2833 !(Attributes & ObjCDeclSpec::DQ_PR_strong) && 2834 PropertyTy->isBlockPointerType()) 2835 Diag(Loc, diag::warn_objc_property_retain_of_block); 2836 2837 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) && 2838 (Attributes & ObjCDeclSpec::DQ_PR_setter)) 2839 Diag(Loc, diag::warn_objc_readonly_property_has_setter); 2840 } 2841