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