]> CyberLeo.Net >> Repos - FreeBSD/releng/9.0.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaExprObjC.cpp
Copy stable/9 to releng/9.0 as part of the FreeBSD 9.0-RELEASE release
[FreeBSD/releng/9.0.git] / contrib / llvm / tools / clang / lib / Sema / SemaExprObjC.cpp
1 //===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
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 expressions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/Lookup.h"
16 #include "clang/Sema/Scope.h"
17 #include "clang/Sema/ScopeInfo.h"
18 #include "clang/Sema/Initialization.h"
19 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/StmtVisitor.h"
24 #include "clang/AST/TypeLoc.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "clang/Lex/Preprocessor.h"
27
28 using namespace clang;
29 using namespace sema;
30 using llvm::makeArrayRef;
31
32 ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
33                                         Expr **strings,
34                                         unsigned NumStrings) {
35   StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
36
37   // Most ObjC strings are formed out of a single piece.  However, we *can*
38   // have strings formed out of multiple @ strings with multiple pptokens in
39   // each one, e.g. @"foo" "bar" @"baz" "qux"   which need to be turned into one
40   // StringLiteral for ObjCStringLiteral to hold onto.
41   StringLiteral *S = Strings[0];
42
43   // If we have a multi-part string, merge it all together.
44   if (NumStrings != 1) {
45     // Concatenate objc strings.
46     llvm::SmallString<128> StrBuf;
47     SmallVector<SourceLocation, 8> StrLocs;
48
49     for (unsigned i = 0; i != NumStrings; ++i) {
50       S = Strings[i];
51
52       // ObjC strings can't be wide or UTF.
53       if (!S->isAscii()) {
54         Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
55           << S->getSourceRange();
56         return true;
57       }
58
59       // Append the string.
60       StrBuf += S->getString();
61
62       // Get the locations of the string tokens.
63       StrLocs.append(S->tokloc_begin(), S->tokloc_end());
64     }
65
66     // Create the aggregate string with the appropriate content and location
67     // information.
68     S = StringLiteral::Create(Context, StrBuf,
69                               StringLiteral::Ascii, /*Pascal=*/false,
70                               Context.getPointerType(Context.CharTy),
71                               &StrLocs[0], StrLocs.size());
72   }
73
74   // Verify that this composite string is acceptable for ObjC strings.
75   if (CheckObjCString(S))
76     return true;
77
78   // Initialize the constant string interface lazily. This assumes
79   // the NSString interface is seen in this translation unit. Note: We
80   // don't use NSConstantString, since the runtime team considers this
81   // interface private (even though it appears in the header files).
82   QualType Ty = Context.getObjCConstantStringInterface();
83   if (!Ty.isNull()) {
84     Ty = Context.getObjCObjectPointerType(Ty);
85   } else if (getLangOptions().NoConstantCFStrings) {
86     IdentifierInfo *NSIdent=0;
87     std::string StringClass(getLangOptions().ObjCConstantStringClass);
88     
89     if (StringClass.empty())
90       NSIdent = &Context.Idents.get("NSConstantString");
91     else
92       NSIdent = &Context.Idents.get(StringClass);
93     
94     NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
95                                      LookupOrdinaryName);
96     if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
97       Context.setObjCConstantStringInterface(StrIF);
98       Ty = Context.getObjCConstantStringInterface();
99       Ty = Context.getObjCObjectPointerType(Ty);
100     } else {
101       // If there is no NSConstantString interface defined then treat this
102       // as error and recover from it.
103       Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
104         << S->getSourceRange();
105       Ty = Context.getObjCIdType();
106     }
107   } else {
108     IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
109     NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
110                                      LookupOrdinaryName);
111     if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
112       Context.setObjCConstantStringInterface(StrIF);
113       Ty = Context.getObjCConstantStringInterface();
114       Ty = Context.getObjCObjectPointerType(Ty);
115     } else {
116       // If there is no NSString interface defined then treat constant
117       // strings as untyped objects and let the runtime figure it out later.
118       Ty = Context.getObjCIdType();
119     }
120   }
121
122   return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]);
123 }
124
125 ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
126                                       TypeSourceInfo *EncodedTypeInfo,
127                                       SourceLocation RParenLoc) {
128   QualType EncodedType = EncodedTypeInfo->getType();
129   QualType StrTy;
130   if (EncodedType->isDependentType())
131     StrTy = Context.DependentTy;
132   else {
133     if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
134         !EncodedType->isVoidType()) // void is handled too.
135       if (RequireCompleteType(AtLoc, EncodedType,
136                          PDiag(diag::err_incomplete_type_objc_at_encode)
137                              << EncodedTypeInfo->getTypeLoc().getSourceRange()))
138         return ExprError();
139
140     std::string Str;
141     Context.getObjCEncodingForType(EncodedType, Str);
142
143     // The type of @encode is the same as the type of the corresponding string,
144     // which is an array type.
145     StrTy = Context.CharTy;
146     // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
147     if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
148       StrTy.addConst();
149     StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
150                                          ArrayType::Normal, 0);
151   }
152
153   return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
154 }
155
156 ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
157                                            SourceLocation EncodeLoc,
158                                            SourceLocation LParenLoc,
159                                            ParsedType ty,
160                                            SourceLocation RParenLoc) {
161   // FIXME: Preserve type source info ?
162   TypeSourceInfo *TInfo;
163   QualType EncodedType = GetTypeFromParser(ty, &TInfo);
164   if (!TInfo)
165     TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
166                                              PP.getLocForEndOfToken(LParenLoc));
167
168   return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
169 }
170
171 ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
172                                              SourceLocation AtLoc,
173                                              SourceLocation SelLoc,
174                                              SourceLocation LParenLoc,
175                                              SourceLocation RParenLoc) {
176   ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
177                              SourceRange(LParenLoc, RParenLoc), false, false);
178   if (!Method)
179     Method = LookupFactoryMethodInGlobalPool(Sel,
180                                           SourceRange(LParenLoc, RParenLoc));
181   if (!Method)
182     Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
183   
184   if (!Method ||
185       Method->getImplementationControl() != ObjCMethodDecl::Optional) {
186     llvm::DenseMap<Selector, SourceLocation>::iterator Pos
187       = ReferencedSelectors.find(Sel);
188     if (Pos == ReferencedSelectors.end())
189       ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
190   }
191
192   // In ARC, forbid the user from using @selector for 
193   // retain/release/autorelease/dealloc/retainCount.
194   if (getLangOptions().ObjCAutoRefCount) {
195     switch (Sel.getMethodFamily()) {
196     case OMF_retain:
197     case OMF_release:
198     case OMF_autorelease:
199     case OMF_retainCount:
200     case OMF_dealloc:
201       Diag(AtLoc, diag::err_arc_illegal_selector) << 
202         Sel << SourceRange(LParenLoc, RParenLoc);
203       break;
204
205     case OMF_None:
206     case OMF_alloc:
207     case OMF_copy:
208     case OMF_finalize:
209     case OMF_init:
210     case OMF_mutableCopy:
211     case OMF_new:
212     case OMF_self:
213     case OMF_performSelector:
214       break;
215     }
216   }
217   QualType Ty = Context.getObjCSelType();
218   return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
219 }
220
221 ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
222                                              SourceLocation AtLoc,
223                                              SourceLocation ProtoLoc,
224                                              SourceLocation LParenLoc,
225                                              SourceLocation RParenLoc) {
226   ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
227   if (!PDecl) {
228     Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
229     return true;
230   }
231
232   QualType Ty = Context.getObjCProtoType();
233   if (Ty.isNull())
234     return true;
235   Ty = Context.getObjCObjectPointerType(Ty);
236   return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
237 }
238
239 /// Try to capture an implicit reference to 'self'.
240 ObjCMethodDecl *Sema::tryCaptureObjCSelf() {
241   // Ignore block scopes: we can capture through them.
242   DeclContext *DC = CurContext;
243   while (true) {
244     if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
245     else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
246     else break;
247   }
248
249   // If we're not in an ObjC method, error out.  Note that, unlike the
250   // C++ case, we don't require an instance method --- class methods
251   // still have a 'self', and we really do still need to capture it!
252   ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
253   if (!method)
254     return 0;
255
256   ImplicitParamDecl *self = method->getSelfDecl();
257   assert(self && "capturing 'self' in non-definition?");
258
259   // Mark that we're closing on 'this' in all the block scopes, if applicable.
260   for (unsigned idx = FunctionScopes.size() - 1;
261        isa<BlockScopeInfo>(FunctionScopes[idx]);
262        --idx) {
263     BlockScopeInfo *blockScope = cast<BlockScopeInfo>(FunctionScopes[idx]);
264     unsigned &captureIndex = blockScope->CaptureMap[self];
265     if (captureIndex) break;
266
267     bool nested = isa<BlockScopeInfo>(FunctionScopes[idx-1]);
268     blockScope->Captures.push_back(
269               BlockDecl::Capture(self, /*byref*/ false, nested, /*copy*/ 0));
270     captureIndex = blockScope->Captures.size(); // +1
271   }
272
273   return method;
274 }
275
276 static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
277   if (T == Context.getObjCInstanceType())
278     return Context.getObjCIdType();
279   
280   return T;
281 }
282
283 QualType Sema::getMessageSendResultType(QualType ReceiverType,
284                                         ObjCMethodDecl *Method,
285                                     bool isClassMessage, bool isSuperMessage) {
286   assert(Method && "Must have a method");
287   if (!Method->hasRelatedResultType())
288     return Method->getSendResultType();
289   
290   // If a method has a related return type:
291   //   - if the method found is an instance method, but the message send
292   //     was a class message send, T is the declared return type of the method
293   //     found
294   if (Method->isInstanceMethod() && isClassMessage)
295     return stripObjCInstanceType(Context, Method->getSendResultType());
296   
297   //   - if the receiver is super, T is a pointer to the class of the 
298   //     enclosing method definition
299   if (isSuperMessage) {
300     if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
301       if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
302         return Context.getObjCObjectPointerType(
303                                         Context.getObjCInterfaceType(Class));
304   }
305     
306   //   - if the receiver is the name of a class U, T is a pointer to U
307   if (ReceiverType->getAs<ObjCInterfaceType>() ||
308       ReceiverType->isObjCQualifiedInterfaceType())
309     return Context.getObjCObjectPointerType(ReceiverType);
310   //   - if the receiver is of type Class or qualified Class type, 
311   //     T is the declared return type of the method.
312   if (ReceiverType->isObjCClassType() ||
313       ReceiverType->isObjCQualifiedClassType())
314     return stripObjCInstanceType(Context, Method->getSendResultType());
315   
316   //   - if the receiver is id, qualified id, Class, or qualified Class, T
317   //     is the receiver type, otherwise
318   //   - T is the type of the receiver expression.
319   return ReceiverType;
320 }
321
322 void Sema::EmitRelatedResultTypeNote(const Expr *E) {
323   E = E->IgnoreParenImpCasts();
324   const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
325   if (!MsgSend)
326     return;
327   
328   const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
329   if (!Method)
330     return;
331   
332   if (!Method->hasRelatedResultType())
333     return;
334   
335   if (Context.hasSameUnqualifiedType(Method->getResultType()
336                                                         .getNonReferenceType(),
337                                      MsgSend->getType()))
338     return;
339   
340   if (!Context.hasSameUnqualifiedType(Method->getResultType(), 
341                                       Context.getObjCInstanceType()))
342     return;
343   
344   Diag(Method->getLocation(), diag::note_related_result_type_inferred)
345     << Method->isInstanceMethod() << Method->getSelector()
346     << MsgSend->getType();
347 }
348
349 bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
350                                      Expr **Args, unsigned NumArgs,
351                                      Selector Sel, ObjCMethodDecl *Method,
352                                      bool isClassMessage, bool isSuperMessage,
353                                      SourceLocation lbrac, SourceLocation rbrac,
354                                      QualType &ReturnType, ExprValueKind &VK) {
355   if (!Method) {
356     // Apply default argument promotion as for (C99 6.5.2.2p6).
357     for (unsigned i = 0; i != NumArgs; i++) {
358       if (Args[i]->isTypeDependent())
359         continue;
360
361       ExprResult Result = DefaultArgumentPromotion(Args[i]);
362       if (Result.isInvalid())
363         return true;
364       Args[i] = Result.take();
365     }
366
367     unsigned DiagID;
368     if (getLangOptions().ObjCAutoRefCount)
369       DiagID = diag::err_arc_method_not_found;
370     else
371       DiagID = isClassMessage ? diag::warn_class_method_not_found
372                               : diag::warn_inst_method_not_found;
373     if (!getLangOptions().DebuggerSupport)
374       Diag(lbrac, DiagID)
375         << Sel << isClassMessage << SourceRange(lbrac, rbrac);
376
377     // In debuggers, we want to use __unknown_anytype for these
378     // results so that clients can cast them.
379     if (getLangOptions().DebuggerSupport) {
380       ReturnType = Context.UnknownAnyTy;
381     } else {
382       ReturnType = Context.getObjCIdType();
383     }
384     VK = VK_RValue;
385     return false;
386   }
387
388   ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage, 
389                                         isSuperMessage);
390   VK = Expr::getValueKindForType(Method->getResultType());
391
392   unsigned NumNamedArgs = Sel.getNumArgs();
393   // Method might have more arguments than selector indicates. This is due
394   // to addition of c-style arguments in method.
395   if (Method->param_size() > Sel.getNumArgs())
396     NumNamedArgs = Method->param_size();
397   // FIXME. This need be cleaned up.
398   if (NumArgs < NumNamedArgs) {
399     Diag(lbrac, diag::err_typecheck_call_too_few_args)
400       << 2 << NumNamedArgs << NumArgs;
401     return false;
402   }
403
404   bool IsError = false;
405   for (unsigned i = 0; i < NumNamedArgs; i++) {
406     // We can't do any type-checking on a type-dependent argument.
407     if (Args[i]->isTypeDependent())
408       continue;
409
410     Expr *argExpr = Args[i];
411
412     ParmVarDecl *Param = Method->param_begin()[i];
413     assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
414
415     if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
416                             Param->getType(),
417                             PDiag(diag::err_call_incomplete_argument)
418                               << argExpr->getSourceRange()))
419       return true;
420
421     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
422                                                                       Param);
423     ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
424     if (ArgE.isInvalid())
425       IsError = true;
426     else
427       Args[i] = ArgE.takeAs<Expr>();
428   }
429
430   // Promote additional arguments to variadic methods.
431   if (Method->isVariadic()) {
432     for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
433       if (Args[i]->isTypeDependent())
434         continue;
435
436       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
437       IsError |= Arg.isInvalid();
438       Args[i] = Arg.take();
439     }
440   } else {
441     // Check for extra arguments to non-variadic methods.
442     if (NumArgs != NumNamedArgs) {
443       Diag(Args[NumNamedArgs]->getLocStart(),
444            diag::err_typecheck_call_too_many_args)
445         << 2 /*method*/ << NumNamedArgs << NumArgs
446         << Method->getSourceRange()
447         << SourceRange(Args[NumNamedArgs]->getLocStart(),
448                        Args[NumArgs-1]->getLocEnd());
449     }
450   }
451   // diagnose nonnull arguments.
452   for (specific_attr_iterator<NonNullAttr>
453        i = Method->specific_attr_begin<NonNullAttr>(),
454        e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
455     CheckNonNullArguments(*i, Args, lbrac);
456   }
457
458   DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
459   return IsError;
460 }
461
462 bool Sema::isSelfExpr(Expr *receiver) {
463   // 'self' is objc 'self' in an objc method only.
464   DeclContext *DC = CurContext;
465   while (isa<BlockDecl>(DC))
466     DC = DC->getParent();
467   if (DC && !isa<ObjCMethodDecl>(DC))
468     return false;
469   receiver = receiver->IgnoreParenLValueCasts();
470   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
471     if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
472       return true;
473   return false;
474 }
475
476 // Helper method for ActOnClassMethod/ActOnInstanceMethod.
477 // Will search "local" class/category implementations for a method decl.
478 // If failed, then we search in class's root for an instance method.
479 // Returns 0 if no method is found.
480 ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
481                                           ObjCInterfaceDecl *ClassDecl) {
482   ObjCMethodDecl *Method = 0;
483   // lookup in class and all superclasses
484   while (ClassDecl && !Method) {
485     if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
486       Method = ImpDecl->getClassMethod(Sel);
487
488     // Look through local category implementations associated with the class.
489     if (!Method)
490       Method = ClassDecl->getCategoryClassMethod(Sel);
491
492     // Before we give up, check if the selector is an instance method.
493     // But only in the root. This matches gcc's behaviour and what the
494     // runtime expects.
495     if (!Method && !ClassDecl->getSuperClass()) {
496       Method = ClassDecl->lookupInstanceMethod(Sel);
497       // Look through local category implementations associated
498       // with the root class.
499       if (!Method)
500         Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
501     }
502
503     ClassDecl = ClassDecl->getSuperClass();
504   }
505   return Method;
506 }
507
508 ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
509                                               ObjCInterfaceDecl *ClassDecl) {
510   ObjCMethodDecl *Method = 0;
511   while (ClassDecl && !Method) {
512     // If we have implementations in scope, check "private" methods.
513     if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
514       Method = ImpDecl->getInstanceMethod(Sel);
515
516     // Look through local category implementations associated with the class.
517     if (!Method)
518       Method = ClassDecl->getCategoryInstanceMethod(Sel);
519     ClassDecl = ClassDecl->getSuperClass();
520   }
521   return Method;
522 }
523
524 /// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier 
525 /// list of a qualified objective pointer type.
526 ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
527                                               const ObjCObjectPointerType *OPT,
528                                               bool Instance)
529 {
530   ObjCMethodDecl *MD = 0;
531   for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
532        E = OPT->qual_end(); I != E; ++I) {
533     ObjCProtocolDecl *PROTO = (*I);
534     if ((MD = PROTO->lookupMethod(Sel, Instance))) {
535       return MD;
536     }
537   }
538   return 0;
539 }
540
541 /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
542 /// objective C interface.  This is a property reference expression.
543 ExprResult Sema::
544 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
545                           Expr *BaseExpr, SourceLocation OpLoc,
546                           DeclarationName MemberName,
547                           SourceLocation MemberLoc,
548                           SourceLocation SuperLoc, QualType SuperType,
549                           bool Super) {
550   const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
551   ObjCInterfaceDecl *IFace = IFaceT->getDecl();
552   
553   if (MemberName.getNameKind() != DeclarationName::Identifier) {
554     Diag(MemberLoc, diag::err_invalid_property_name)
555       << MemberName << QualType(OPT, 0);
556     return ExprError();
557   }
558   
559   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
560
561   if (IFace->isForwardDecl()) {
562     Diag(MemberLoc, diag::err_property_not_found_forward_class)
563          << MemberName << QualType(OPT, 0);
564     Diag(IFace->getLocation(), diag::note_forward_class);
565     return ExprError();
566   }
567   // Search for a declared property first.
568   if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
569     // Check whether we can reference this property.
570     if (DiagnoseUseOfDecl(PD, MemberLoc))
571       return ExprError();
572     QualType ResTy = PD->getType();
573     ResTy = ResTy.getNonLValueExprType(Context);
574     Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
575     ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
576     if (Getter &&
577         (Getter->hasRelatedResultType()
578          || DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc)))
579         ResTy = getMessageSendResultType(QualType(OPT, 0), Getter, false, 
580                                          Super);
581              
582     if (Super)
583       return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
584                                                      VK_LValue, OK_ObjCProperty,
585                                                      MemberLoc, 
586                                                      SuperLoc, SuperType));
587     else
588       return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
589                                                      VK_LValue, OK_ObjCProperty,
590                                                      MemberLoc, BaseExpr));
591   }
592   // Check protocols on qualified interfaces.
593   for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
594        E = OPT->qual_end(); I != E; ++I)
595     if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
596       // Check whether we can reference this property.
597       if (DiagnoseUseOfDecl(PD, MemberLoc))
598         return ExprError();
599       
600       QualType T = PD->getType();
601       if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
602         T = getMessageSendResultType(QualType(OPT, 0), Getter, false, Super);
603       if (Super)
604         return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
605                                                        VK_LValue,
606                                                        OK_ObjCProperty,
607                                                        MemberLoc, 
608                                                        SuperLoc, SuperType));
609       else
610         return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
611                                                        VK_LValue,
612                                                        OK_ObjCProperty,
613                                                        MemberLoc,
614                                                        BaseExpr));
615     }
616   // If that failed, look for an "implicit" property by seeing if the nullary
617   // selector is implemented.
618
619   // FIXME: The logic for looking up nullary and unary selectors should be
620   // shared with the code in ActOnInstanceMessage.
621
622   Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
623   ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
624   
625   // May be founf in property's qualified list.
626   if (!Getter)
627     Getter = LookupMethodInQualifiedType(Sel, OPT, true);
628
629   // If this reference is in an @implementation, check for 'private' methods.
630   if (!Getter)
631     Getter = IFace->lookupPrivateMethod(Sel);
632
633   // Look through local category implementations associated with the class.
634   if (!Getter)
635     Getter = IFace->getCategoryInstanceMethod(Sel);
636   if (Getter) {
637     // Check if we can reference this property.
638     if (DiagnoseUseOfDecl(Getter, MemberLoc))
639       return ExprError();
640   }
641   // If we found a getter then this may be a valid dot-reference, we
642   // will look for the matching setter, in case it is needed.
643   Selector SetterSel =
644     SelectorTable::constructSetterName(PP.getIdentifierTable(),
645                                        PP.getSelectorTable(), Member);
646   ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
647   
648   // May be founf in property's qualified list.
649   if (!Setter)
650     Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
651   
652   if (!Setter) {
653     // If this reference is in an @implementation, also check for 'private'
654     // methods.
655     Setter = IFace->lookupPrivateMethod(SetterSel);
656   }
657   // Look through local category implementations associated with the class.
658   if (!Setter)
659     Setter = IFace->getCategoryInstanceMethod(SetterSel);
660     
661   if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
662     return ExprError();
663
664   if (Getter || Setter) {
665     QualType PType;
666     if (Getter)
667       PType = getMessageSendResultType(QualType(OPT, 0), Getter, false, Super);
668     else {
669       ParmVarDecl *ArgDecl = *Setter->param_begin();
670       PType = ArgDecl->getType();
671     }
672     
673     ExprValueKind VK = VK_LValue;
674     ExprObjectKind OK = OK_ObjCProperty;
675     if (!getLangOptions().CPlusPlus && !PType.hasQualifiers() &&
676         PType->isVoidType())
677       VK = VK_RValue, OK = OK_Ordinary;
678
679     if (Super)
680       return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
681                                                      PType, VK, OK,
682                                                      MemberLoc,
683                                                      SuperLoc, SuperType));
684     else
685       return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
686                                                      PType, VK, OK,
687                                                      MemberLoc, BaseExpr));
688
689   }
690
691   // Attempt to correct for typos in property names.
692   TypoCorrection Corrected = CorrectTypo(
693       DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
694       NULL, IFace, false, CTC_NoKeywords, OPT);
695   if (ObjCPropertyDecl *Property =
696       Corrected.getCorrectionDeclAs<ObjCPropertyDecl>()) {
697     DeclarationName TypoResult = Corrected.getCorrection();
698     Diag(MemberLoc, diag::err_property_not_found_suggest)
699       << MemberName << QualType(OPT, 0) << TypoResult
700       << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
701     Diag(Property->getLocation(), diag::note_previous_decl)
702       << Property->getDeclName();
703     return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
704                                      TypoResult, MemberLoc,
705                                      SuperLoc, SuperType, Super);
706   }
707   ObjCInterfaceDecl *ClassDeclared;
708   if (ObjCIvarDecl *Ivar = 
709       IFace->lookupInstanceVariable(Member, ClassDeclared)) {
710     QualType T = Ivar->getType();
711     if (const ObjCObjectPointerType * OBJPT = 
712         T->getAsObjCInterfacePointerType()) {
713       const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
714       if (ObjCInterfaceDecl *IFace = IFaceT->getDecl())
715         if (IFace->isForwardDecl()) {
716           Diag(MemberLoc, diag::err_property_not_as_forward_class)
717           << MemberName << IFace;
718           Diag(IFace->getLocation(), diag::note_forward_class);
719           return ExprError();
720         }
721     }
722     Diag(MemberLoc, 
723          diag::err_ivar_access_using_property_syntax_suggest)
724     << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
725     << FixItHint::CreateReplacement(OpLoc, "->");
726     return ExprError();
727   }
728   
729   Diag(MemberLoc, diag::err_property_not_found)
730     << MemberName << QualType(OPT, 0);
731   if (Setter)
732     Diag(Setter->getLocation(), diag::note_getter_unavailable)
733           << MemberName << BaseExpr->getSourceRange();
734   return ExprError();
735 }
736
737
738
739 ExprResult Sema::
740 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
741                           IdentifierInfo &propertyName,
742                           SourceLocation receiverNameLoc,
743                           SourceLocation propertyNameLoc) {
744
745   IdentifierInfo *receiverNamePtr = &receiverName;
746   ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
747                                                   receiverNameLoc);
748
749   bool IsSuper = false;
750   if (IFace == 0) {
751     // If the "receiver" is 'super' in a method, handle it as an expression-like
752     // property reference.
753     if (receiverNamePtr->isStr("super")) {
754       IsSuper = true;
755
756       if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf()) {
757         if (CurMethod->isInstanceMethod()) {
758           QualType T = 
759             Context.getObjCInterfaceType(CurMethod->getClassInterface());
760           T = Context.getObjCObjectPointerType(T);
761         
762           return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
763                                            /*BaseExpr*/0, 
764                                            SourceLocation()/*OpLoc*/, 
765                                            &propertyName,
766                                            propertyNameLoc,
767                                            receiverNameLoc, T, true);
768         }
769
770         // Otherwise, if this is a class method, try dispatching to our
771         // superclass.
772         IFace = CurMethod->getClassInterface()->getSuperClass();
773       }
774     }
775     
776     if (IFace == 0) {
777       Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
778       return ExprError();
779     }
780   }
781
782   // Search for a declared property first.
783   Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
784   ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
785
786   // If this reference is in an @implementation, check for 'private' methods.
787   if (!Getter)
788     if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
789       if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
790         if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
791           Getter = ImpDecl->getClassMethod(Sel);
792
793   if (Getter) {
794     // FIXME: refactor/share with ActOnMemberReference().
795     // Check if we can reference this property.
796     if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
797       return ExprError();
798   }
799
800   // Look for the matching setter, in case it is needed.
801   Selector SetterSel =
802     SelectorTable::constructSetterName(PP.getIdentifierTable(),
803                                        PP.getSelectorTable(), &propertyName);
804
805   ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
806   if (!Setter) {
807     // If this reference is in an @implementation, also check for 'private'
808     // methods.
809     if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
810       if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
811         if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
812           Setter = ImpDecl->getClassMethod(SetterSel);
813   }
814   // Look through local category implementations associated with the class.
815   if (!Setter)
816     Setter = IFace->getCategoryClassMethod(SetterSel);
817
818   if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
819     return ExprError();
820
821   if (Getter || Setter) {
822     QualType PType;
823
824     ExprValueKind VK = VK_LValue;
825     if (Getter) {
826       PType = getMessageSendResultType(Context.getObjCInterfaceType(IFace),
827                                        Getter, true, 
828                                        receiverNamePtr->isStr("super"));
829       if (!getLangOptions().CPlusPlus &&
830           !PType.hasQualifiers() && PType->isVoidType())
831         VK = VK_RValue;
832     } else {
833       for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
834            E = Setter->param_end(); PI != E; ++PI)
835         PType = (*PI)->getType();
836       VK = VK_LValue;
837     }
838
839     ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
840
841     if (IsSuper)
842     return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
843                                                    PType, VK, OK,
844                                                    propertyNameLoc,
845                                                    receiverNameLoc, 
846                                           Context.getObjCInterfaceType(IFace)));
847
848     return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
849                                                    PType, VK, OK,
850                                                    propertyNameLoc,
851                                                    receiverNameLoc, IFace));
852   }
853   return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
854                      << &propertyName << Context.getObjCInterfaceType(IFace));
855 }
856
857 Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
858                                                IdentifierInfo *Name,
859                                                SourceLocation NameLoc,
860                                                bool IsSuper,
861                                                bool HasTrailingDot,
862                                                ParsedType &ReceiverType) {
863   ReceiverType = ParsedType();
864
865   // If the identifier is "super" and there is no trailing dot, we're
866   // messaging super. If the identifier is "super" and there is a
867   // trailing dot, it's an instance message.
868   if (IsSuper && S->isInObjcMethodScope())
869     return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
870   
871   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
872   LookupName(Result, S);
873   
874   switch (Result.getResultKind()) {
875   case LookupResult::NotFound:
876     // Normal name lookup didn't find anything. If we're in an
877     // Objective-C method, look for ivars. If we find one, we're done!
878     // FIXME: This is a hack. Ivar lookup should be part of normal
879     // lookup.
880     if (ObjCMethodDecl *Method = getCurMethodDecl()) {
881       ObjCInterfaceDecl *ClassDeclared;
882       if (Method->getClassInterface()->lookupInstanceVariable(Name, 
883                                                               ClassDeclared))
884         return ObjCInstanceMessage;
885     }
886   
887     // Break out; we'll perform typo correction below.
888     break;
889
890   case LookupResult::NotFoundInCurrentInstantiation:
891   case LookupResult::FoundOverloaded:
892   case LookupResult::FoundUnresolvedValue:
893   case LookupResult::Ambiguous:
894     Result.suppressDiagnostics();
895     return ObjCInstanceMessage;
896
897   case LookupResult::Found: {
898     // If the identifier is a class or not, and there is a trailing dot,
899     // it's an instance message.
900     if (HasTrailingDot)
901       return ObjCInstanceMessage;
902     // We found something. If it's a type, then we have a class
903     // message. Otherwise, it's an instance message.
904     NamedDecl *ND = Result.getFoundDecl();
905     QualType T;
906     if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
907       T = Context.getObjCInterfaceType(Class);
908     else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
909       T = Context.getTypeDeclType(Type);
910     else 
911       return ObjCInstanceMessage;
912
913     //  We have a class message, and T is the type we're
914     //  messaging. Build source-location information for it.
915     TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
916     ReceiverType = CreateParsedType(T, TSInfo);
917     return ObjCClassMessage;
918   }
919   }
920
921   // Determine our typo-correction context.
922   CorrectTypoContext CTC = CTC_Expression;
923   if (ObjCMethodDecl *Method = getCurMethodDecl())
924     if (Method->getClassInterface() &&
925         Method->getClassInterface()->getSuperClass())
926       CTC = CTC_ObjCMessageReceiver;
927       
928   if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
929                                              Result.getLookupKind(), S, NULL,
930                                              NULL, false, CTC)) {
931     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
932       // If we found a declaration, correct when it refers to an Objective-C
933       // class.
934       if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
935         Diag(NameLoc, diag::err_unknown_receiver_suggest)
936           << Name << Corrected.getCorrection()
937           << FixItHint::CreateReplacement(SourceRange(NameLoc),
938                                           ND->getNameAsString());
939         Diag(ND->getLocation(), diag::note_previous_decl)
940           << Corrected.getCorrection();
941
942         QualType T = Context.getObjCInterfaceType(Class);
943         TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
944         ReceiverType = CreateParsedType(T, TSInfo);
945         return ObjCClassMessage;
946       }
947     } else if (Corrected.isKeyword() &&
948                Corrected.getCorrectionAsIdentifierInfo()->isStr("super")) {
949       // If we've found the keyword "super", this is a send to super.
950       Diag(NameLoc, diag::err_unknown_receiver_suggest)
951         << Name << Corrected.getCorrection()
952         << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
953       return ObjCSuperMessage;
954     }
955   }
956   
957   // Fall back: let the parser try to parse it as an instance message.
958   return ObjCInstanceMessage;
959 }
960
961 ExprResult Sema::ActOnSuperMessage(Scope *S, 
962                                    SourceLocation SuperLoc,
963                                    Selector Sel,
964                                    SourceLocation LBracLoc,
965                                    ArrayRef<SourceLocation> SelectorLocs,
966                                    SourceLocation RBracLoc,
967                                    MultiExprArg Args) {
968   // Determine whether we are inside a method or not.
969   ObjCMethodDecl *Method = tryCaptureObjCSelf();
970   if (!Method) {
971     Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
972     return ExprError();
973   }
974
975   ObjCInterfaceDecl *Class = Method->getClassInterface();
976   if (!Class) {
977     Diag(SuperLoc, diag::error_no_super_class_message)
978       << Method->getDeclName();
979     return ExprError();
980   }
981
982   ObjCInterfaceDecl *Super = Class->getSuperClass();
983   if (!Super) {
984     // The current class does not have a superclass.
985     Diag(SuperLoc, diag::error_root_class_cannot_use_super)
986       << Class->getIdentifier();
987     return ExprError();
988   }
989
990   // We are in a method whose class has a superclass, so 'super'
991   // is acting as a keyword.
992   if (Method->isInstanceMethod()) {
993     if (Sel.getMethodFamily() == OMF_dealloc)
994       ObjCShouldCallSuperDealloc = false;
995     if (Sel.getMethodFamily() == OMF_finalize)
996       ObjCShouldCallSuperFinalize = false;
997
998     // Since we are in an instance method, this is an instance
999     // message to the superclass instance.
1000     QualType SuperTy = Context.getObjCInterfaceType(Super);
1001     SuperTy = Context.getObjCObjectPointerType(SuperTy);
1002     return BuildInstanceMessage(0, SuperTy, SuperLoc,
1003                                 Sel, /*Method=*/0,
1004                                 LBracLoc, SelectorLocs, RBracLoc, move(Args));
1005   }
1006   
1007   // Since we are in a class method, this is a class message to
1008   // the superclass.
1009   return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1010                            Context.getObjCInterfaceType(Super),
1011                            SuperLoc, Sel, /*Method=*/0,
1012                            LBracLoc, SelectorLocs, RBracLoc, move(Args));
1013 }
1014
1015 /// \brief Build an Objective-C class message expression.
1016 ///
1017 /// This routine takes care of both normal class messages and
1018 /// class messages to the superclass.
1019 ///
1020 /// \param ReceiverTypeInfo Type source information that describes the
1021 /// receiver of this message. This may be NULL, in which case we are
1022 /// sending to the superclass and \p SuperLoc must be a valid source
1023 /// location.
1024
1025 /// \param ReceiverType The type of the object receiving the
1026 /// message. When \p ReceiverTypeInfo is non-NULL, this is the same
1027 /// type as that refers to. For a superclass send, this is the type of
1028 /// the superclass.
1029 ///
1030 /// \param SuperLoc The location of the "super" keyword in a
1031 /// superclass message.
1032 ///
1033 /// \param Sel The selector to which the message is being sent.
1034 ///
1035 /// \param Method The method that this class message is invoking, if
1036 /// already known.
1037 ///
1038 /// \param LBracLoc The location of the opening square bracket ']'.
1039 ///
1040 /// \param RBrac The location of the closing square bracket ']'.
1041 ///
1042 /// \param Args The message arguments.
1043 ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
1044                                    QualType ReceiverType,
1045                                    SourceLocation SuperLoc,
1046                                    Selector Sel,
1047                                    ObjCMethodDecl *Method,
1048                                    SourceLocation LBracLoc, 
1049                                    ArrayRef<SourceLocation> SelectorLocs,
1050                                    SourceLocation RBracLoc,
1051                                    MultiExprArg ArgsIn) {
1052   SourceLocation Loc = SuperLoc.isValid()? SuperLoc
1053     : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
1054   if (LBracLoc.isInvalid()) {
1055     Diag(Loc, diag::err_missing_open_square_message_send)
1056       << FixItHint::CreateInsertion(Loc, "[");
1057     LBracLoc = Loc;
1058   }
1059   
1060   if (ReceiverType->isDependentType()) {
1061     // If the receiver type is dependent, we can't type-check anything
1062     // at this point. Build a dependent expression.
1063     unsigned NumArgs = ArgsIn.size();
1064     Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1065     assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1066     return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1067                                          VK_RValue, LBracLoc, ReceiverTypeInfo,
1068                                          Sel, SelectorLocs, /*Method=*/0,
1069                                          makeArrayRef(Args, NumArgs),RBracLoc));
1070   }
1071   
1072   // Find the class to which we are sending this message.
1073   ObjCInterfaceDecl *Class = 0;
1074   const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1075   if (!ClassType || !(Class = ClassType->getInterface())) {
1076     Diag(Loc, diag::err_invalid_receiver_class_message)
1077       << ReceiverType;
1078     return ExprError();
1079   }
1080   assert(Class && "We don't know which class we're messaging?");
1081   (void)DiagnoseUseOfDecl(Class, Loc);
1082   // Find the method we are messaging.
1083   if (!Method) {
1084     if (Class->isForwardDecl()) {
1085       if (getLangOptions().ObjCAutoRefCount) {
1086         Diag(Loc, diag::err_arc_receiver_forward_class) << ReceiverType;
1087       } else {
1088         Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
1089       }
1090
1091       // A forward class used in messaging is treated as a 'Class'
1092       Method = LookupFactoryMethodInGlobalPool(Sel, 
1093                                                SourceRange(LBracLoc, RBracLoc));
1094       if (Method && !getLangOptions().ObjCAutoRefCount)
1095         Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1096           << Method->getDeclName();
1097     }
1098     if (!Method)
1099       Method = Class->lookupClassMethod(Sel);
1100
1101     // If we have an implementation in scope, check "private" methods.
1102     if (!Method)
1103       Method = LookupPrivateClassMethod(Sel, Class);
1104
1105     if (Method && DiagnoseUseOfDecl(Method, Loc))
1106       return ExprError();
1107   }
1108
1109   // Check the argument types and determine the result type.
1110   QualType ReturnType;
1111   ExprValueKind VK = VK_RValue;
1112
1113   unsigned NumArgs = ArgsIn.size();
1114   Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1115   if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1116                                 SuperLoc.isValid(), LBracLoc, RBracLoc, 
1117                                 ReturnType, VK))
1118     return ExprError();
1119
1120   if (Method && !Method->getResultType()->isVoidType() &&
1121       RequireCompleteType(LBracLoc, Method->getResultType(), 
1122                           diag::err_illegal_message_expr_incomplete_type))
1123     return ExprError();
1124
1125   // Construct the appropriate ObjCMessageExpr.
1126   Expr *Result;
1127   if (SuperLoc.isValid())
1128     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, 
1129                                      SuperLoc, /*IsInstanceSuper=*/false, 
1130                                      ReceiverType, Sel, SelectorLocs,
1131                                      Method, makeArrayRef(Args, NumArgs),
1132                                      RBracLoc);
1133   else
1134     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, 
1135                                      ReceiverTypeInfo, Sel, SelectorLocs,
1136                                      Method, makeArrayRef(Args, NumArgs),
1137                                      RBracLoc);
1138   return MaybeBindToTemporary(Result);
1139 }
1140
1141 // ActOnClassMessage - used for both unary and keyword messages.
1142 // ArgExprs is optional - if it is present, the number of expressions
1143 // is obtained from Sel.getNumArgs().
1144 ExprResult Sema::ActOnClassMessage(Scope *S, 
1145                                    ParsedType Receiver,
1146                                    Selector Sel,
1147                                    SourceLocation LBracLoc,
1148                                    ArrayRef<SourceLocation> SelectorLocs,
1149                                    SourceLocation RBracLoc,
1150                                    MultiExprArg Args) {
1151   TypeSourceInfo *ReceiverTypeInfo;
1152   QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
1153   if (ReceiverType.isNull())
1154     return ExprError();
1155
1156
1157   if (!ReceiverTypeInfo)
1158     ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
1159
1160   return BuildClassMessage(ReceiverTypeInfo, ReceiverType, 
1161                            /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
1162                            LBracLoc, SelectorLocs, RBracLoc, move(Args));
1163 }
1164
1165 /// \brief Build an Objective-C instance message expression.
1166 ///
1167 /// This routine takes care of both normal instance messages and
1168 /// instance messages to the superclass instance.
1169 ///
1170 /// \param Receiver The expression that computes the object that will
1171 /// receive this message. This may be empty, in which case we are
1172 /// sending to the superclass instance and \p SuperLoc must be a valid
1173 /// source location.
1174 ///
1175 /// \param ReceiverType The (static) type of the object receiving the
1176 /// message. When a \p Receiver expression is provided, this is the
1177 /// same type as that expression. For a superclass instance send, this
1178 /// is a pointer to the type of the superclass.
1179 ///
1180 /// \param SuperLoc The location of the "super" keyword in a
1181 /// superclass instance message.
1182 ///
1183 /// \param Sel The selector to which the message is being sent.
1184 ///
1185 /// \param Method The method that this instance message is invoking, if
1186 /// already known.
1187 ///
1188 /// \param LBracLoc The location of the opening square bracket ']'.
1189 ///
1190 /// \param RBrac The location of the closing square bracket ']'.
1191 ///
1192 /// \param Args The message arguments.
1193 ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
1194                                       QualType ReceiverType,
1195                                       SourceLocation SuperLoc,
1196                                       Selector Sel,
1197                                       ObjCMethodDecl *Method,
1198                                       SourceLocation LBracLoc, 
1199                                       ArrayRef<SourceLocation> SelectorLocs,
1200                                       SourceLocation RBracLoc,
1201                                       MultiExprArg ArgsIn) {
1202   // The location of the receiver.
1203   SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
1204   
1205   if (LBracLoc.isInvalid()) {
1206     Diag(Loc, diag::err_missing_open_square_message_send)
1207       << FixItHint::CreateInsertion(Loc, "[");
1208     LBracLoc = Loc;
1209   }
1210
1211   // If we have a receiver expression, perform appropriate promotions
1212   // and determine receiver type.
1213   if (Receiver) {
1214     if (Receiver->isTypeDependent()) {
1215       // If the receiver is type-dependent, we can't type-check anything
1216       // at this point. Build a dependent expression.
1217       unsigned NumArgs = ArgsIn.size();
1218       Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1219       assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1220       return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
1221                                            VK_RValue, LBracLoc, Receiver, Sel, 
1222                                            SelectorLocs, /*Method=*/0,
1223                                            makeArrayRef(Args, NumArgs),
1224                                            RBracLoc));
1225     }
1226
1227     // If necessary, apply function/array conversion to the receiver.
1228     // C99 6.7.5.3p[7,8].
1229     ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
1230     if (Result.isInvalid())
1231       return ExprError();
1232     Receiver = Result.take();
1233     ReceiverType = Receiver->getType();
1234   }
1235
1236   if (!Method) {
1237     // Handle messages to id.
1238     bool receiverIsId = ReceiverType->isObjCIdType();
1239     if (receiverIsId || ReceiverType->isBlockPointerType() ||
1240         (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
1241       Method = LookupInstanceMethodInGlobalPool(Sel, 
1242                                                 SourceRange(LBracLoc, RBracLoc),
1243                                                 receiverIsId);
1244       if (!Method)
1245         Method = LookupFactoryMethodInGlobalPool(Sel, 
1246                                                  SourceRange(LBracLoc, RBracLoc),
1247                                                  receiverIsId);
1248     } else if (ReceiverType->isObjCClassType() ||
1249                ReceiverType->isObjCQualifiedClassType()) {
1250       // Handle messages to Class.
1251       // We allow sending a message to a qualified Class ("Class<foo>"), which 
1252       // is ok as long as one of the protocols implements the selector (if not, warn).
1253       if (const ObjCObjectPointerType *QClassTy 
1254             = ReceiverType->getAsObjCQualifiedClassType()) {
1255         // Search protocols for class methods.
1256         Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
1257         if (!Method) {
1258           Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
1259           // warn if instance method found for a Class message.
1260           if (Method) {
1261             Diag(Loc, diag::warn_instance_method_on_class_found)
1262               << Method->getSelector() << Sel;
1263             Diag(Method->getLocation(), diag::note_method_declared_at);
1264           }
1265         }
1266       } else {
1267         if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
1268           if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
1269             // First check the public methods in the class interface.
1270             Method = ClassDecl->lookupClassMethod(Sel);
1271
1272             if (!Method)
1273               Method = LookupPrivateClassMethod(Sel, ClassDecl);
1274           }
1275           if (Method && DiagnoseUseOfDecl(Method, Loc))
1276             return ExprError();
1277         }
1278         if (!Method) {
1279           // If not messaging 'self', look for any factory method named 'Sel'.
1280           if (!Receiver || !isSelfExpr(Receiver)) {
1281             Method = LookupFactoryMethodInGlobalPool(Sel, 
1282                                                 SourceRange(LBracLoc, RBracLoc),
1283                                                      true);
1284             if (!Method) {
1285               // If no class (factory) method was found, check if an _instance_
1286               // method of the same name exists in the root class only.
1287               Method = LookupInstanceMethodInGlobalPool(Sel,
1288                                                SourceRange(LBracLoc, RBracLoc),
1289                                                         true);
1290               if (Method)
1291                   if (const ObjCInterfaceDecl *ID =
1292                       dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
1293                     if (ID->getSuperClass())
1294                       Diag(Loc, diag::warn_root_inst_method_not_found)
1295                       << Sel << SourceRange(LBracLoc, RBracLoc);
1296                   }
1297             }
1298           }
1299         }
1300       }
1301     } else {
1302       ObjCInterfaceDecl* ClassDecl = 0;
1303
1304       // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
1305       // long as one of the protocols implements the selector (if not, warn).
1306       if (const ObjCObjectPointerType *QIdTy 
1307                                    = ReceiverType->getAsObjCQualifiedIdType()) {
1308         // Search protocols for instance methods.
1309         Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
1310         if (!Method)
1311           Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
1312       } else if (const ObjCObjectPointerType *OCIType
1313                    = ReceiverType->getAsObjCInterfacePointerType()) {
1314         // We allow sending a message to a pointer to an interface (an object).
1315         ClassDecl = OCIType->getInterfaceDecl();
1316
1317         if (ClassDecl->isForwardDecl() && getLangOptions().ObjCAutoRefCount) {
1318           Diag(Loc, diag::err_arc_receiver_forward_instance)
1319             << OCIType->getPointeeType()
1320             << (Receiver ? Receiver->getSourceRange() : SourceRange(SuperLoc));
1321           return ExprError();
1322         }
1323
1324         // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
1325         // faster than the following method (which can do *many* linear searches).
1326         // The idea is to add class info to MethodPool.
1327         Method = ClassDecl->lookupInstanceMethod(Sel);
1328
1329         if (!Method)
1330           // Search protocol qualifiers.
1331           Method = LookupMethodInQualifiedType(Sel, OCIType, true);
1332         
1333         const ObjCInterfaceDecl *forwardClass = 0;
1334         if (!Method) {
1335           // If we have implementations in scope, check "private" methods.
1336           Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1337
1338           if (!Method && getLangOptions().ObjCAutoRefCount) {
1339             Diag(Loc, diag::err_arc_may_not_respond)
1340               << OCIType->getPointeeType() << Sel;
1341             return ExprError();
1342           }
1343
1344           if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
1345             // If we still haven't found a method, look in the global pool. This
1346             // behavior isn't very desirable, however we need it for GCC
1347             // compatibility. FIXME: should we deviate??
1348             if (OCIType->qual_empty()) {
1349               Method = LookupInstanceMethodInGlobalPool(Sel,
1350                                                  SourceRange(LBracLoc, RBracLoc));
1351               if (OCIType->getInterfaceDecl()->isForwardDecl())
1352                 forwardClass = OCIType->getInterfaceDecl();
1353               if (Method && !forwardClass)
1354                 Diag(Loc, diag::warn_maynot_respond)
1355                   << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
1356             }
1357           }
1358         }
1359         if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
1360           return ExprError();
1361       } else if (!getLangOptions().ObjCAutoRefCount &&
1362                  !Context.getObjCIdType().isNull() &&
1363                  (ReceiverType->isPointerType() || 
1364                   ReceiverType->isIntegerType())) {
1365         // Implicitly convert integers and pointers to 'id' but emit a warning.
1366         // But not in ARC.
1367         Diag(Loc, diag::warn_bad_receiver_type)
1368           << ReceiverType 
1369           << Receiver->getSourceRange();
1370         if (ReceiverType->isPointerType())
1371           Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(), 
1372                             CK_CPointerToObjCPointerCast).take();
1373         else {
1374           // TODO: specialized warning on null receivers?
1375           bool IsNull = Receiver->isNullPointerConstant(Context,
1376                                               Expr::NPC_ValueDependentIsNull);
1377           Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1378                             IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
1379         }
1380         ReceiverType = Receiver->getType();
1381       } else {
1382         ExprResult ReceiverRes;
1383         if (getLangOptions().CPlusPlus)
1384           ReceiverRes = PerformContextuallyConvertToObjCPointer(Receiver);
1385         if (ReceiverRes.isUsable()) {
1386           Receiver = ReceiverRes.take();
1387           return BuildInstanceMessage(Receiver,
1388                                       ReceiverType,
1389                                       SuperLoc,
1390                                       Sel,
1391                                       Method,
1392                                       LBracLoc,
1393                                       SelectorLocs,
1394                                       RBracLoc,
1395                                       move(ArgsIn));
1396         } else {
1397           // Reject other random receiver types (e.g. structs).
1398           Diag(Loc, diag::err_bad_receiver_type)
1399             << ReceiverType << Receiver->getSourceRange();
1400           return ExprError();
1401         }
1402       }
1403     }
1404   }
1405
1406   // Check the message arguments.
1407   unsigned NumArgs = ArgsIn.size();
1408   Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1409   QualType ReturnType;
1410   ExprValueKind VK = VK_RValue;
1411   bool ClassMessage = (ReceiverType->isObjCClassType() ||
1412                        ReceiverType->isObjCQualifiedClassType());
1413   if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, 
1414                                 ClassMessage, SuperLoc.isValid(), 
1415                                 LBracLoc, RBracLoc, ReturnType, VK))
1416     return ExprError();
1417   
1418   if (Method && !Method->getResultType()->isVoidType() &&
1419       RequireCompleteType(LBracLoc, Method->getResultType(), 
1420                           diag::err_illegal_message_expr_incomplete_type))
1421     return ExprError();
1422
1423   SourceLocation SelLoc = SelectorLocs.front();
1424
1425   // In ARC, forbid the user from sending messages to 
1426   // retain/release/autorelease/dealloc/retainCount explicitly.
1427   if (getLangOptions().ObjCAutoRefCount) {
1428     ObjCMethodFamily family =
1429       (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
1430     switch (family) {
1431     case OMF_init:
1432       if (Method)
1433         checkInitMethod(Method, ReceiverType);
1434
1435     case OMF_None:
1436     case OMF_alloc:
1437     case OMF_copy:
1438     case OMF_finalize:
1439     case OMF_mutableCopy:
1440     case OMF_new:
1441     case OMF_self:
1442       break;
1443
1444     case OMF_dealloc:
1445     case OMF_retain:
1446     case OMF_release:
1447     case OMF_autorelease:
1448     case OMF_retainCount:
1449       Diag(Loc, diag::err_arc_illegal_explicit_message)
1450         << Sel << SelLoc;
1451       break;
1452     
1453     case OMF_performSelector:
1454       if (Method && NumArgs >= 1) {
1455         if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
1456           Selector ArgSel = SelExp->getSelector();
1457           ObjCMethodDecl *SelMethod = 
1458             LookupInstanceMethodInGlobalPool(ArgSel,
1459                                              SelExp->getSourceRange());
1460           if (!SelMethod)
1461             SelMethod =
1462               LookupFactoryMethodInGlobalPool(ArgSel,
1463                                               SelExp->getSourceRange());
1464           if (SelMethod) {
1465             ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
1466             switch (SelFamily) {
1467               case OMF_alloc:
1468               case OMF_copy:
1469               case OMF_mutableCopy:
1470               case OMF_new:
1471               case OMF_self:
1472               case OMF_init:
1473                 // Issue error, unless ns_returns_not_retained.
1474                 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
1475                   // selector names a +1 method 
1476                   Diag(SelLoc, 
1477                        diag::err_arc_perform_selector_retains);
1478                   Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1479                 }
1480                 break;
1481               default:
1482                 // +0 call. OK. unless ns_returns_retained.
1483                 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
1484                   // selector names a +1 method
1485                   Diag(SelLoc, 
1486                        diag::err_arc_perform_selector_retains);
1487                   Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1488                 }
1489                 break;
1490             }
1491           }
1492         } else {
1493           // error (may leak).
1494           Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
1495           Diag(Args[0]->getExprLoc(), diag::note_used_here);
1496         }
1497       }
1498       break;
1499     }
1500   }
1501
1502   // Construct the appropriate ObjCMessageExpr instance.
1503   ObjCMessageExpr *Result;
1504   if (SuperLoc.isValid())
1505     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
1506                                      SuperLoc,  /*IsInstanceSuper=*/true,
1507                                      ReceiverType, Sel, SelectorLocs, Method, 
1508                                      makeArrayRef(Args, NumArgs), RBracLoc);
1509   else
1510     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
1511                                      Receiver, Sel, SelectorLocs, Method,
1512                                      makeArrayRef(Args, NumArgs), RBracLoc);
1513
1514   if (getLangOptions().ObjCAutoRefCount) {
1515     // In ARC, annotate delegate init calls.
1516     if (Result->getMethodFamily() == OMF_init &&
1517         (SuperLoc.isValid() || isSelfExpr(Receiver))) {
1518       // Only consider init calls *directly* in init implementations,
1519       // not within blocks.
1520       ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
1521       if (method && method->getMethodFamily() == OMF_init) {
1522         // The implicit assignment to self means we also don't want to
1523         // consume the result.
1524         Result->setDelegateInitCall(true);
1525         return Owned(Result);
1526       }
1527     }
1528
1529     // In ARC, check for message sends which are likely to introduce
1530     // retain cycles.
1531     checkRetainCycles(Result);
1532   }
1533       
1534   return MaybeBindToTemporary(Result);
1535 }
1536
1537 // ActOnInstanceMessage - used for both unary and keyword messages.
1538 // ArgExprs is optional - if it is present, the number of expressions
1539 // is obtained from Sel.getNumArgs().
1540 ExprResult Sema::ActOnInstanceMessage(Scope *S,
1541                                       Expr *Receiver, 
1542                                       Selector Sel,
1543                                       SourceLocation LBracLoc,
1544                                       ArrayRef<SourceLocation> SelectorLocs,
1545                                       SourceLocation RBracLoc,
1546                                       MultiExprArg Args) {
1547   if (!Receiver)
1548     return ExprError();
1549
1550   return BuildInstanceMessage(Receiver, Receiver->getType(),
1551                               /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0, 
1552                               LBracLoc, SelectorLocs, RBracLoc, move(Args));
1553 }
1554
1555 enum ARCConversionTypeClass {
1556   /// int, void, struct A
1557   ACTC_none,
1558
1559   /// id, void (^)()
1560   ACTC_retainable,
1561
1562   /// id*, id***, void (^*)(),
1563   ACTC_indirectRetainable,
1564
1565   /// void* might be a normal C type, or it might a CF type.
1566   ACTC_voidPtr,
1567
1568   /// struct A*
1569   ACTC_coreFoundation
1570 };
1571 static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
1572   return (ACTC == ACTC_retainable ||
1573           ACTC == ACTC_coreFoundation ||
1574           ACTC == ACTC_voidPtr);
1575 }
1576 static bool isAnyCLike(ARCConversionTypeClass ACTC) {
1577   return ACTC == ACTC_none ||
1578          ACTC == ACTC_voidPtr ||
1579          ACTC == ACTC_coreFoundation;
1580 }
1581
1582 static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
1583   bool isIndirect = false;
1584   
1585   // Ignore an outermost reference type.
1586   if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
1587     type = ref->getPointeeType();
1588     isIndirect = true;
1589   }
1590   
1591   // Drill through pointers and arrays recursively.
1592   while (true) {
1593     if (const PointerType *ptr = type->getAs<PointerType>()) {
1594       type = ptr->getPointeeType();
1595
1596       // The first level of pointer may be the innermost pointer on a CF type.
1597       if (!isIndirect) {
1598         if (type->isVoidType()) return ACTC_voidPtr;
1599         if (type->isRecordType()) return ACTC_coreFoundation;
1600       }
1601     } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
1602       type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
1603     } else {
1604       break;
1605     }
1606     isIndirect = true;
1607   }
1608   
1609   if (isIndirect) {
1610     if (type->isObjCARCBridgableType())
1611       return ACTC_indirectRetainable;
1612     return ACTC_none;
1613   }
1614
1615   if (type->isObjCARCBridgableType())
1616     return ACTC_retainable;
1617
1618   return ACTC_none;
1619 }
1620
1621 namespace {
1622   /// A result from the cast checker.
1623   enum ACCResult {
1624     /// Cannot be casted.
1625     ACC_invalid,
1626
1627     /// Can be safely retained or not retained.
1628     ACC_bottom,
1629
1630     /// Can be casted at +0.
1631     ACC_plusZero,
1632
1633     /// Can be casted at +1.
1634     ACC_plusOne
1635   };
1636   ACCResult merge(ACCResult left, ACCResult right) {
1637     if (left == right) return left;
1638     if (left == ACC_bottom) return right;
1639     if (right == ACC_bottom) return left;
1640     return ACC_invalid;
1641   }
1642
1643   /// A checker which white-lists certain expressions whose conversion
1644   /// to or from retainable type would otherwise be forbidden in ARC.
1645   class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
1646     typedef StmtVisitor<ARCCastChecker, ACCResult> super;
1647
1648     ASTContext &Context;
1649     ARCConversionTypeClass SourceClass;
1650     ARCConversionTypeClass TargetClass;
1651
1652     static bool isCFType(QualType type) {
1653       // Someday this can use ns_bridged.  For now, it has to do this.
1654       return type->isCARCBridgableType();
1655     }
1656
1657   public:
1658     ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
1659                    ARCConversionTypeClass target)
1660       : Context(Context), SourceClass(source), TargetClass(target) {}
1661
1662     using super::Visit;
1663     ACCResult Visit(Expr *e) {
1664       return super::Visit(e->IgnoreParens());
1665     }
1666
1667     ACCResult VisitStmt(Stmt *s) {
1668       return ACC_invalid;
1669     }
1670
1671     /// Null pointer constants can be casted however you please.
1672     ACCResult VisitExpr(Expr *e) {
1673       if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1674         return ACC_bottom;
1675       return ACC_invalid;
1676     }
1677
1678     /// Objective-C string literals can be safely casted.
1679     ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
1680       // If we're casting to any retainable type, go ahead.  Global
1681       // strings are immune to retains, so this is bottom.
1682       if (isAnyRetainable(TargetClass)) return ACC_bottom;
1683
1684       return ACC_invalid;
1685     }
1686     
1687     /// Look through certain implicit and explicit casts.
1688     ACCResult VisitCastExpr(CastExpr *e) {
1689       switch (e->getCastKind()) {
1690         case CK_NullToPointer:
1691           return ACC_bottom;
1692
1693         case CK_NoOp:
1694         case CK_LValueToRValue:
1695         case CK_BitCast:
1696         case CK_GetObjCProperty:
1697         case CK_CPointerToObjCPointerCast:
1698         case CK_BlockPointerToObjCPointerCast:
1699         case CK_AnyPointerToBlockPointerCast:
1700           return Visit(e->getSubExpr());
1701
1702         default:
1703           return ACC_invalid;
1704       }
1705     }
1706
1707     /// Look through unary extension.
1708     ACCResult VisitUnaryExtension(UnaryOperator *e) {
1709       return Visit(e->getSubExpr());
1710     }
1711
1712     /// Ignore the LHS of a comma operator.
1713     ACCResult VisitBinComma(BinaryOperator *e) {
1714       return Visit(e->getRHS());
1715     }
1716
1717     /// Conditional operators are okay if both sides are okay.
1718     ACCResult VisitConditionalOperator(ConditionalOperator *e) {
1719       ACCResult left = Visit(e->getTrueExpr());
1720       if (left == ACC_invalid) return ACC_invalid;
1721       return merge(left, Visit(e->getFalseExpr()));
1722     }
1723
1724     /// Statement expressions are okay if their result expression is okay.
1725     ACCResult VisitStmtExpr(StmtExpr *e) {
1726       return Visit(e->getSubStmt()->body_back());
1727     }
1728
1729     /// Some declaration references are okay.
1730     ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
1731       // References to global constants from system headers are okay.
1732       // These are things like 'kCFStringTransformToLatin'.  They are
1733       // can also be assumed to be immune to retains.
1734       VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
1735       if (isAnyRetainable(TargetClass) &&
1736           isAnyRetainable(SourceClass) &&
1737           var &&
1738           var->getStorageClass() == SC_Extern &&
1739           var->getType().isConstQualified() &&
1740           Context.getSourceManager().isInSystemHeader(var->getLocation())) {
1741         return ACC_bottom;
1742       }
1743
1744       // Nothing else.
1745       return ACC_invalid;
1746     }
1747
1748     /// Some calls are okay.
1749     ACCResult VisitCallExpr(CallExpr *e) {
1750       if (FunctionDecl *fn = e->getDirectCallee())
1751         if (ACCResult result = checkCallToFunction(fn))
1752           return result;
1753
1754       return super::VisitCallExpr(e);
1755     }
1756
1757     ACCResult checkCallToFunction(FunctionDecl *fn) {
1758       // Require a CF*Ref return type.
1759       if (!isCFType(fn->getResultType()))
1760         return ACC_invalid;
1761
1762       if (!isAnyRetainable(TargetClass))
1763         return ACC_invalid;
1764
1765       // Honor an explicit 'not retained' attribute.
1766       if (fn->hasAttr<CFReturnsNotRetainedAttr>())
1767         return ACC_plusZero;
1768
1769       // Honor an explicit 'retained' attribute, except that for
1770       // now we're not going to permit implicit handling of +1 results,
1771       // because it's a bit frightening.
1772       if (fn->hasAttr<CFReturnsRetainedAttr>())
1773         return ACC_invalid; // ACC_plusOne if we start accepting this
1774
1775       // Recognize this specific builtin function, which is used by CFSTR.
1776       unsigned builtinID = fn->getBuiltinID();
1777       if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
1778         return ACC_bottom;
1779
1780       // Otherwise, don't do anything implicit with an unaudited function.
1781       if (!fn->hasAttr<CFAuditedTransferAttr>())
1782         return ACC_invalid;
1783
1784       // Otherwise, it's +0 unless it follows the create convention.
1785       if (ento::coreFoundation::followsCreateRule(fn))
1786         return ACC_invalid; // ACC_plusOne if we start accepting this
1787
1788       return ACC_plusZero;
1789     }
1790
1791     ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
1792       return checkCallToMethod(e->getMethodDecl());
1793     }
1794
1795     ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
1796       ObjCMethodDecl *method;
1797       if (e->isExplicitProperty())
1798         method = e->getExplicitProperty()->getGetterMethodDecl();
1799       else
1800         method = e->getImplicitPropertyGetter();
1801       return checkCallToMethod(method);
1802     }
1803
1804     ACCResult checkCallToMethod(ObjCMethodDecl *method) {
1805       if (!method) return ACC_invalid;
1806
1807       // Check for message sends to functions returning CF types.  We
1808       // just obey the Cocoa conventions with these, even though the
1809       // return type is CF.
1810       if (!isAnyRetainable(TargetClass) || !isCFType(method->getResultType()))
1811         return ACC_invalid;
1812       
1813       // If the method is explicitly marked not-retained, it's +0.
1814       if (method->hasAttr<CFReturnsNotRetainedAttr>())
1815         return ACC_plusZero;
1816
1817       // If the method is explicitly marked as returning retained, or its
1818       // selector follows a +1 Cocoa convention, treat it as +1.
1819       if (method->hasAttr<CFReturnsRetainedAttr>())
1820         return ACC_plusOne;
1821
1822       switch (method->getSelector().getMethodFamily()) {
1823       case OMF_alloc:
1824       case OMF_copy:
1825       case OMF_mutableCopy:
1826       case OMF_new:
1827         return ACC_plusOne;
1828
1829       default:
1830         // Otherwise, treat it as +0.
1831         return ACC_plusZero;
1832       }
1833     }
1834   };
1835 }
1836
1837 void 
1838 Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
1839                              Expr *&castExpr, CheckedConversionKind CCK) {
1840   QualType castExprType = castExpr->getType();
1841
1842   // For the purposes of the classification, we assume reference types
1843   // will bind to temporaries.
1844   QualType effCastType = castType;
1845   if (const ReferenceType *ref = castType->getAs<ReferenceType>())
1846     effCastType = ref->getPointeeType();
1847   
1848   ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
1849   ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
1850   if (exprACTC == castACTC) return;
1851   if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return;
1852
1853   // Allow all of these types to be cast to integer types (but not
1854   // vice-versa).
1855   if (castACTC == ACTC_none && castType->isIntegralType(Context))
1856     return;
1857   
1858   // Allow casts between pointers to lifetime types (e.g., __strong id*)
1859   // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
1860   // must be explicit.
1861   if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
1862     return;
1863   if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
1864       CCK != CCK_ImplicitConversion)
1865     return;
1866
1867   switch (ARCCastChecker(Context, exprACTC, castACTC).Visit(castExpr)) {
1868   // For invalid casts, fall through.
1869   case ACC_invalid:
1870     break;
1871
1872   // Do nothing for both bottom and +0.
1873   case ACC_bottom:
1874   case ACC_plusZero:
1875     return;
1876
1877   // If the result is +1, consume it here.
1878   case ACC_plusOne:
1879     castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
1880                                         CK_ARCConsumeObject, castExpr,
1881                                         0, VK_RValue);
1882     ExprNeedsCleanups = true;
1883     return;
1884   }
1885   
1886   SourceLocation loc =
1887     (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
1888   
1889   if (makeUnavailableInSystemHeader(loc,
1890                 "converts between Objective-C and C pointers in -fobjc-arc"))
1891     return;
1892   
1893   unsigned srcKind = 0;
1894   switch (exprACTC) {
1895   case ACTC_none:
1896   case ACTC_coreFoundation:
1897   case ACTC_voidPtr:
1898     srcKind = (castExprType->isPointerType() ? 1 : 0);
1899     break;
1900   case ACTC_retainable:
1901     srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
1902     break;
1903   case ACTC_indirectRetainable:
1904     srcKind = 4;
1905     break;
1906   }
1907   
1908   if (CCK == CCK_CStyleCast) {
1909     // Check whether this could be fixed with a bridge cast.
1910     SourceLocation AfterLParen = PP.getLocForEndOfToken(castRange.getBegin());
1911     SourceLocation NoteLoc = AfterLParen.isValid()? AfterLParen : loc;
1912     
1913     if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
1914       Diag(loc, diag::err_arc_cast_requires_bridge)
1915         << 2
1916         << castExprType
1917         << (castType->isBlockPointerType()? 1 : 0)
1918         << castType
1919         << castRange
1920         << castExpr->getSourceRange();
1921       Diag(NoteLoc, diag::note_arc_bridge)
1922         << FixItHint::CreateInsertion(AfterLParen, "__bridge ");
1923       Diag(NoteLoc, diag::note_arc_bridge_transfer)
1924         << castExprType
1925         << FixItHint::CreateInsertion(AfterLParen, "__bridge_transfer ");
1926       
1927       return;
1928     }
1929     
1930     if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
1931       Diag(loc, diag::err_arc_cast_requires_bridge)
1932         << (castExprType->isBlockPointerType()? 1 : 0)
1933         << castExprType
1934         << 2
1935         << castType
1936         << castRange
1937         << castExpr->getSourceRange();
1938
1939       Diag(NoteLoc, diag::note_arc_bridge)
1940         << FixItHint::CreateInsertion(AfterLParen, "__bridge ");
1941       Diag(NoteLoc, diag::note_arc_bridge_retained)
1942         << castType
1943         << FixItHint::CreateInsertion(AfterLParen, "__bridge_retained ");
1944       return;
1945     }
1946   }
1947   
1948   Diag(loc, diag::err_arc_mismatched_cast)
1949     << (CCK != CCK_ImplicitConversion) << srcKind << castExprType << castType
1950     << castRange << castExpr->getSourceRange();
1951 }
1952
1953 bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
1954                                                  QualType exprType) {
1955   QualType canCastType = 
1956     Context.getCanonicalType(castType).getUnqualifiedType();
1957   QualType canExprType = 
1958     Context.getCanonicalType(exprType).getUnqualifiedType();
1959   if (isa<ObjCObjectPointerType>(canCastType) &&
1960       castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
1961       canExprType->isObjCObjectPointerType()) {
1962     if (const ObjCObjectPointerType *ObjT =
1963         canExprType->getAs<ObjCObjectPointerType>())
1964       if (ObjT->getInterfaceDecl()->isArcWeakrefUnavailable())
1965         return false;
1966   }
1967   return true;
1968 }
1969
1970 /// Look for an ObjCReclaimReturnedObject cast and destroy it.
1971 static Expr *maybeUndoReclaimObject(Expr *e) {
1972   // For now, we just undo operands that are *immediately* reclaim
1973   // expressions, which prevents the vast majority of potential
1974   // problems here.  To catch them all, we'd need to rebuild arbitrary
1975   // value-propagating subexpressions --- we can't reliably rebuild
1976   // in-place because of expression sharing.
1977   if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
1978     if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
1979       return ice->getSubExpr();
1980
1981   return e;
1982 }
1983
1984 ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
1985                                       ObjCBridgeCastKind Kind,
1986                                       SourceLocation BridgeKeywordLoc,
1987                                       TypeSourceInfo *TSInfo,
1988                                       Expr *SubExpr) {
1989   ExprResult SubResult = UsualUnaryConversions(SubExpr);
1990   if (SubResult.isInvalid()) return ExprError();
1991   SubExpr = SubResult.take();
1992
1993   QualType T = TSInfo->getType();
1994   QualType FromType = SubExpr->getType();
1995
1996   CastKind CK;
1997
1998   bool MustConsume = false;
1999   if (T->isDependentType() || SubExpr->isTypeDependent()) {
2000     // Okay: we'll build a dependent expression type.
2001     CK = CK_Dependent;
2002   } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
2003     // Casting CF -> id
2004     CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
2005                                   : CK_CPointerToObjCPointerCast);
2006     switch (Kind) {
2007     case OBC_Bridge:
2008       break;
2009       
2010     case OBC_BridgeRetained:
2011       Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
2012         << 2
2013         << FromType
2014         << (T->isBlockPointerType()? 1 : 0)
2015         << T
2016         << SubExpr->getSourceRange()
2017         << Kind;
2018       Diag(BridgeKeywordLoc, diag::note_arc_bridge)
2019         << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
2020       Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
2021         << FromType
2022         << FixItHint::CreateReplacement(BridgeKeywordLoc, 
2023                                         "__bridge_transfer ");
2024
2025       Kind = OBC_Bridge;
2026       break;
2027       
2028     case OBC_BridgeTransfer:
2029       // We must consume the Objective-C object produced by the cast.
2030       MustConsume = true;
2031       break;
2032     }
2033   } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
2034     // Okay: id -> CF
2035     CK = CK_BitCast;
2036     switch (Kind) {
2037     case OBC_Bridge:
2038       // Reclaiming a value that's going to be __bridge-casted to CF
2039       // is very dangerous, so we don't do it.
2040       SubExpr = maybeUndoReclaimObject(SubExpr);
2041       break;
2042       
2043     case OBC_BridgeRetained:        
2044       // Produce the object before casting it.
2045       SubExpr = ImplicitCastExpr::Create(Context, FromType,
2046                                          CK_ARCProduceObject,
2047                                          SubExpr, 0, VK_RValue);
2048       break;
2049       
2050     case OBC_BridgeTransfer:
2051       Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
2052         << (FromType->isBlockPointerType()? 1 : 0)
2053         << FromType
2054         << 2
2055         << T
2056         << SubExpr->getSourceRange()
2057         << Kind;
2058         
2059       Diag(BridgeKeywordLoc, diag::note_arc_bridge)
2060         << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
2061       Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
2062         << T
2063         << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge_retained ");
2064         
2065       Kind = OBC_Bridge;
2066       break;
2067     }
2068   } else {
2069     Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
2070       << FromType << T << Kind
2071       << SubExpr->getSourceRange()
2072       << TSInfo->getTypeLoc().getSourceRange();
2073     return ExprError();
2074   }
2075
2076   Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
2077                                                    BridgeKeywordLoc,
2078                                                    TSInfo, SubExpr);
2079   
2080   if (MustConsume) {
2081     ExprNeedsCleanups = true;
2082     Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result, 
2083                                       0, VK_RValue);    
2084   }
2085   
2086   return Result;
2087 }
2088
2089 ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
2090                                       SourceLocation LParenLoc,
2091                                       ObjCBridgeCastKind Kind,
2092                                       SourceLocation BridgeKeywordLoc,
2093                                       ParsedType Type,
2094                                       SourceLocation RParenLoc,
2095                                       Expr *SubExpr) {
2096   TypeSourceInfo *TSInfo = 0;
2097   QualType T = GetTypeFromParser(Type, &TSInfo);
2098   if (!TSInfo)
2099     TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
2100   return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo, 
2101                               SubExpr);
2102 }