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