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