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