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