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