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