SemaExprObjC.cpp revision 4e4d08403ca5cfd4d558fa2936215d3a4e5a528d
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/Edit/Rewriters.h"
21#include "clang/Edit/Commit.h"
22#include "clang/AST/ASTContext.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/StmtVisitor.h"
26#include "clang/AST/TypeLoc.h"
27#include "llvm/ADT/SmallString.h"
28#include "clang/Lex/Preprocessor.h"
29
30using namespace clang;
31using namespace sema;
32using llvm::makeArrayRef;
33
34ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
35                                        Expr **strings,
36                                        unsigned NumStrings) {
37  StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
38
39  // Most ObjC strings are formed out of a single piece.  However, we *can*
40  // have strings formed out of multiple @ strings with multiple pptokens in
41  // each one, e.g. @"foo" "bar" @"baz" "qux"   which need to be turned into one
42  // StringLiteral for ObjCStringLiteral to hold onto.
43  StringLiteral *S = Strings[0];
44
45  // If we have a multi-part string, merge it all together.
46  if (NumStrings != 1) {
47    // Concatenate objc strings.
48    SmallString<128> StrBuf;
49    SmallVector<SourceLocation, 8> StrLocs;
50
51    for (unsigned i = 0; i != NumStrings; ++i) {
52      S = Strings[i];
53
54      // ObjC strings can't be wide or UTF.
55      if (!S->isAscii()) {
56        Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
57          << S->getSourceRange();
58        return true;
59      }
60
61      // Append the string.
62      StrBuf += S->getString();
63
64      // Get the locations of the string tokens.
65      StrLocs.append(S->tokloc_begin(), S->tokloc_end());
66    }
67
68    // Create the aggregate string with the appropriate content and location
69    // information.
70    S = StringLiteral::Create(Context, StrBuf,
71                              StringLiteral::Ascii, /*Pascal=*/false,
72                              Context.getPointerType(Context.CharTy),
73                              &StrLocs[0], StrLocs.size());
74  }
75
76  return BuildObjCStringLiteral(AtLocs[0], S);
77}
78
79ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
80  // Verify that this composite string is acceptable for ObjC strings.
81  if (CheckObjCString(S))
82    return true;
83
84  // Initialize the constant string interface lazily. This assumes
85  // the NSString interface is seen in this translation unit. Note: We
86  // don't use NSConstantString, since the runtime team considers this
87  // interface private (even though it appears in the header files).
88  QualType Ty = Context.getObjCConstantStringInterface();
89  if (!Ty.isNull()) {
90    Ty = Context.getObjCObjectPointerType(Ty);
91  } else if (getLangOpts().NoConstantCFStrings) {
92    IdentifierInfo *NSIdent=0;
93    std::string StringClass(getLangOpts().ObjCConstantStringClass);
94
95    if (StringClass.empty())
96      NSIdent = &Context.Idents.get("NSConstantString");
97    else
98      NSIdent = &Context.Idents.get(StringClass);
99
100    NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
101                                     LookupOrdinaryName);
102    if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
103      Context.setObjCConstantStringInterface(StrIF);
104      Ty = Context.getObjCConstantStringInterface();
105      Ty = Context.getObjCObjectPointerType(Ty);
106    } else {
107      // If there is no NSConstantString interface defined then treat this
108      // as error and recover from it.
109      Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
110        << S->getSourceRange();
111      Ty = Context.getObjCIdType();
112    }
113  } else {
114    IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
115    NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
116                                     LookupOrdinaryName);
117    if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
118      Context.setObjCConstantStringInterface(StrIF);
119      Ty = Context.getObjCConstantStringInterface();
120      Ty = Context.getObjCObjectPointerType(Ty);
121    } else {
122      // If there is no NSString interface defined, implicitly declare
123      // a @class NSString; and use that instead. This is to make sure
124      // type of an NSString literal is represented correctly, instead of
125      // being an 'id' type.
126      Ty = Context.getObjCNSStringType();
127      if (Ty.isNull()) {
128        ObjCInterfaceDecl *NSStringIDecl =
129          ObjCInterfaceDecl::Create (Context,
130                                     Context.getTranslationUnitDecl(),
131                                     SourceLocation(), NSIdent,
132                                     0, SourceLocation());
133        Ty = Context.getObjCInterfaceType(NSStringIDecl);
134        Context.setObjCNSStringType(Ty);
135      }
136      Ty = Context.getObjCObjectPointerType(Ty);
137    }
138  }
139
140  return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
141}
142
143/// \brief Retrieve the NSNumber factory method that should be used to create
144/// an Objective-C literal for the given type.
145static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
146                                                QualType T, QualType ReturnType,
147                                                SourceRange Range) {
148  llvm::Optional<NSAPI::NSNumberLiteralMethodKind> Kind
149    = S.NSAPIObj->getNSNumberFactoryMethodKind(T);
150
151  if (!Kind) {
152    S.Diag(Loc, diag::err_invalid_nsnumber_type)
153      << T << Range;
154    return 0;
155  }
156
157  // If we already looked up this method, we're done.
158  if (S.NSNumberLiteralMethods[*Kind])
159    return S.NSNumberLiteralMethods[*Kind];
160
161  Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
162                                                        /*Instance=*/false);
163
164  // Look for the appropriate method within NSNumber.
165  ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);;
166  if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
167    TypeSourceInfo *ResultTInfo = 0;
168    Method = ObjCMethodDecl::Create(S.Context, SourceLocation(), SourceLocation(), Sel,
169                           ReturnType,
170                           ResultTInfo,
171                           S.Context.getTranslationUnitDecl(),
172                           false /*Instance*/, false/*isVariadic*/,
173                           /*isSynthesized=*/false,
174                           /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
175                           ObjCMethodDecl::Required,
176                           false);
177    ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
178                                             SourceLocation(), SourceLocation(),
179                                             &S.Context.Idents.get("value"),
180                                             T, /*TInfo=*/0, SC_None, SC_None, 0);
181    Method->setMethodParams(S.Context, value, ArrayRef<SourceLocation>());
182  }
183
184  if (!Method) {
185    S.Diag(Loc, diag::err_undeclared_nsnumber_method) << Sel;
186    return 0;
187  }
188
189  // Make sure the return type is reasonable.
190  if (!Method->getResultType()->isObjCObjectPointerType()) {
191    S.Diag(Loc, diag::err_objc_literal_method_sig)
192      << Sel;
193    S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
194      << Method->getResultType();
195    return 0;
196  }
197
198  // Note: if the parameter type is out-of-line, we'll catch it later in the
199  // implicit conversion.
200
201  S.NSNumberLiteralMethods[*Kind] = Method;
202  return Method;
203}
204
205/// BuildObjCNumericLiteral - builds an ObjCNumericLiteral AST node for the
206/// numeric literal expression. Type of the expression will be "NSNumber *"
207/// or "id" if NSNumber is unavailable.
208ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
209  // Look up the NSNumber class, if we haven't done so already.
210  if (!NSNumberDecl) {
211    NamedDecl *IF = LookupSingleName(TUScope,
212                                NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber),
213                                AtLoc, LookupOrdinaryName);
214    NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
215
216    if (!NSNumberDecl && getLangOpts().DebuggerObjCLiteral)
217      NSNumberDecl =  ObjCInterfaceDecl::Create (Context,
218                        Context.getTranslationUnitDecl(),
219                        SourceLocation(),
220                        NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber),
221                        0, SourceLocation());
222    if (!NSNumberDecl) {
223      Diag(AtLoc, diag::err_undeclared_nsnumber);
224      return ExprError();
225    }
226  }
227
228  // Determine the type of the literal.
229  QualType NumberType = Number->getType();
230  if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
231    // In C, character literals have type 'int'. That's not the type we want
232    // to use to determine the Objective-c literal kind.
233    switch (Char->getKind()) {
234    case CharacterLiteral::Ascii:
235      NumberType = Context.CharTy;
236      break;
237
238    case CharacterLiteral::Wide:
239      NumberType = Context.getWCharType();
240      break;
241
242    case CharacterLiteral::UTF16:
243      NumberType = Context.Char16Ty;
244      break;
245
246    case CharacterLiteral::UTF32:
247      NumberType = Context.Char32Ty;
248      break;
249    }
250  }
251
252  ObjCMethodDecl *Method = 0;
253  // Look for the appropriate method within NSNumber.
254  // Construct the literal.
255  QualType Ty
256    = Context.getObjCObjectPointerType(
257                                    Context.getObjCInterfaceType(NSNumberDecl));
258  Method  = getNSNumberFactoryMethod(*this, AtLoc,
259                                     NumberType, Ty,
260                                     Number->getSourceRange());
261
262  if (!Method)
263    return ExprError();
264
265  // Convert the number to the type that the parameter expects.
266  QualType ElementT = Method->param_begin()[0]->getType();
267  ExprResult ConvertedNumber = PerformImplicitConversion(Number, ElementT,
268                                                         AA_Sending);
269  if (ConvertedNumber.isInvalid())
270    return ExprError();
271  Number = ConvertedNumber.get();
272
273  return MaybeBindToTemporary(
274           new (Context) ObjCNumericLiteral(Number, Ty, Method, AtLoc));
275}
276
277ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
278                                      SourceLocation ValueLoc,
279                                      bool Value) {
280  ExprResult Inner;
281  if (getLangOpts().CPlusPlus) {
282    Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
283  } else {
284    // C doesn't actually have a way to represent literal values of type
285    // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
286    Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
287    Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
288                              CK_IntegralToBoolean);
289  }
290
291  return BuildObjCNumericLiteral(AtLoc, Inner.get());
292}
293
294/// \brief Check that the given expression is a valid element of an Objective-C
295/// collection literal.
296static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
297                                                    QualType T) {
298  // If the expression is type-dependent, there's nothing for us to do.
299  if (Element->isTypeDependent())
300    return Element;
301
302  ExprResult Result = S.CheckPlaceholderExpr(Element);
303  if (Result.isInvalid())
304    return ExprError();
305  Element = Result.get();
306
307  // In C++, check for an implicit conversion to an Objective-C object pointer
308  // type.
309  if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
310    InitializedEntity Entity
311      = InitializedEntity::InitializeParameter(S.Context, T, /*Consumed=*/false);
312    InitializationKind Kind
313      = InitializationKind::CreateCopy(Element->getLocStart(), SourceLocation());
314    InitializationSequence Seq(S, Entity, Kind, &Element, 1);
315    if (!Seq.Failed())
316      return Seq.Perform(S, Entity, Kind, MultiExprArg(S, &Element, 1));
317  }
318
319  Expr *OrigElement = Element;
320
321  // Perform lvalue-to-rvalue conversion.
322  Result = S.DefaultLvalueConversion(Element);
323  if (Result.isInvalid())
324    return ExprError();
325  Element = Result.get();
326
327  // Make sure that we have an Objective-C pointer type or block.
328  if (!Element->getType()->isObjCObjectPointerType() &&
329      !Element->getType()->isBlockPointerType()) {
330    bool Recovered = false;
331
332    // If this is potentially an Objective-C numeric literal, add the '@'.
333    if (isa<IntegerLiteral>(OrigElement) ||
334        isa<CharacterLiteral>(OrigElement) ||
335        isa<FloatingLiteral>(OrigElement) ||
336        isa<ObjCBoolLiteralExpr>(OrigElement) ||
337        isa<CXXBoolLiteralExpr>(OrigElement)) {
338      if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
339        int Which = isa<CharacterLiteral>(OrigElement) ? 1
340                  : (isa<CXXBoolLiteralExpr>(OrigElement) ||
341                     isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
342                  : 3;
343
344        S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
345          << Which << OrigElement->getSourceRange()
346          << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
347
348        Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
349                                           OrigElement);
350        if (Result.isInvalid())
351          return ExprError();
352
353        Element = Result.get();
354        Recovered = true;
355      }
356    }
357    // If this is potentially an Objective-C string literal, add the '@'.
358    else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
359      if (String->isAscii()) {
360        S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
361          << 0 << OrigElement->getSourceRange()
362          << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
363
364        Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
365        if (Result.isInvalid())
366          return ExprError();
367
368        Element = Result.get();
369        Recovered = true;
370      }
371    }
372
373    if (!Recovered) {
374      S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
375        << Element->getType();
376      return ExprError();
377    }
378  }
379
380  // Make sure that the element has the type that the container factory
381  // function expects.
382  return S.PerformCopyInitialization(
383           InitializedEntity::InitializeParameter(S.Context, T,
384                                                  /*Consumed=*/false),
385           Element->getLocStart(), Element);
386}
387
388ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
389                                        Expr *IndexExpr,
390                                        ObjCMethodDecl *getterMethod,
391                                        ObjCMethodDecl *setterMethod) {
392  // Feature support is for modern abi.
393  if (!LangOpts.ObjCNonFragileABI)
394    return ExprError();
395  // If the expression is type-dependent, there's nothing for us to do.
396  assert ((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
397          "base or index cannot have dependent type here");
398  ExprResult Result = CheckPlaceholderExpr(IndexExpr);
399  if (Result.isInvalid())
400    return ExprError();
401  IndexExpr = Result.get();
402
403  // Perform lvalue-to-rvalue conversion.
404  Result = DefaultLvalueConversion(BaseExpr);
405  if (Result.isInvalid())
406    return ExprError();
407  BaseExpr = Result.get();
408  return Owned(ObjCSubscriptRefExpr::Create(Context,
409                                            BaseExpr,
410                                            IndexExpr,
411                                            Context.PseudoObjectTy,
412                                            getterMethod,
413                                            setterMethod, RB));
414
415}
416
417ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
418  // Look up the NSArray class, if we haven't done so already.
419  if (!NSArrayDecl) {
420    NamedDecl *IF = LookupSingleName(TUScope,
421                                 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
422                                 SR.getBegin(),
423                                 LookupOrdinaryName);
424    NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
425    if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
426      NSArrayDecl =  ObjCInterfaceDecl::Create (Context,
427                            Context.getTranslationUnitDecl(),
428                            SourceLocation(),
429                            NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
430                            0, SourceLocation());
431
432    if (!NSArrayDecl) {
433      Diag(SR.getBegin(), diag::err_undeclared_nsarray);
434      return ExprError();
435    }
436  }
437
438  // Find the arrayWithObjects:count: method, if we haven't done so already.
439  QualType IdT = Context.getObjCIdType();
440  if (!ArrayWithObjectsMethod) {
441    Selector
442      Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
443    ArrayWithObjectsMethod = NSArrayDecl->lookupClassMethod(Sel);
444    if (!ArrayWithObjectsMethod && getLangOpts().DebuggerObjCLiteral) {
445      TypeSourceInfo *ResultTInfo = 0;
446      ArrayWithObjectsMethod =
447                         ObjCMethodDecl::Create(Context,
448                           SourceLocation(), SourceLocation(), Sel,
449                           IdT,
450                           ResultTInfo,
451                           Context.getTranslationUnitDecl(),
452                           false /*Instance*/, false/*isVariadic*/,
453                           /*isSynthesized=*/false,
454                           /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
455                           ObjCMethodDecl::Required,
456                           false);
457      SmallVector<ParmVarDecl *, 2> Params;
458      ParmVarDecl *objects = ParmVarDecl::Create(Context, ArrayWithObjectsMethod,
459                                                SourceLocation(), SourceLocation(),
460                                                &Context.Idents.get("objects"),
461                                                Context.getPointerType(IdT),
462                                                /*TInfo=*/0,
463                                                SC_None,
464                                                SC_None,
465                                                0);
466      Params.push_back(objects);
467      ParmVarDecl *cnt = ParmVarDecl::Create(Context, ArrayWithObjectsMethod,
468                                                SourceLocation(), SourceLocation(),
469                                                &Context.Idents.get("cnt"),
470                                                Context.UnsignedLongTy,
471                                                /*TInfo=*/0,
472                                                SC_None,
473                                                SC_None,
474                                                0);
475      Params.push_back(cnt);
476      ArrayWithObjectsMethod->setMethodParams(Context, Params,
477                                              ArrayRef<SourceLocation>());
478
479
480    }
481
482    if (!ArrayWithObjectsMethod) {
483      Diag(SR.getBegin(), diag::err_undeclared_arraywithobjects) << Sel;
484      return ExprError();
485    }
486  }
487
488  // Make sure the return type is reasonable.
489  if (!ArrayWithObjectsMethod->getResultType()->isObjCObjectPointerType()) {
490    Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
491      << ArrayWithObjectsMethod->getSelector();
492    Diag(ArrayWithObjectsMethod->getLocation(),
493         diag::note_objc_literal_method_return)
494      << ArrayWithObjectsMethod->getResultType();
495    return ExprError();
496  }
497
498  // Dig out the type that all elements should be converted to.
499  QualType T = ArrayWithObjectsMethod->param_begin()[0]->getType();
500  const PointerType *PtrT = T->getAs<PointerType>();
501  if (!PtrT ||
502      !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
503    Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
504      << ArrayWithObjectsMethod->getSelector();
505    Diag(ArrayWithObjectsMethod->param_begin()[0]->getLocation(),
506         diag::note_objc_literal_method_param)
507      << 0 << T
508      << Context.getPointerType(IdT.withConst());
509    return ExprError();
510  }
511  T = PtrT->getPointeeType();
512
513  // Check that the 'count' parameter is integral.
514  if (!ArrayWithObjectsMethod->param_begin()[1]->getType()->isIntegerType()) {
515    Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
516      << ArrayWithObjectsMethod->getSelector();
517    Diag(ArrayWithObjectsMethod->param_begin()[1]->getLocation(),
518         diag::note_objc_literal_method_param)
519      << 1
520      << ArrayWithObjectsMethod->param_begin()[1]->getType()
521      << "integral";
522    return ExprError();
523  }
524
525  // Check that each of the elements provided is valid in a collection literal,
526  // performing conversions as necessary.
527  Expr **ElementsBuffer = Elements.get();
528  for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
529    ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
530                                                             ElementsBuffer[I],
531                                                             T);
532    if (Converted.isInvalid())
533      return ExprError();
534
535    ElementsBuffer[I] = Converted.get();
536  }
537
538  QualType Ty
539    = Context.getObjCObjectPointerType(
540                                    Context.getObjCInterfaceType(NSArrayDecl));
541
542  return MaybeBindToTemporary(
543           ObjCArrayLiteral::Create(Context,
544                                    llvm::makeArrayRef(Elements.get(),
545                                                       Elements.size()),
546                                    Ty, ArrayWithObjectsMethod, SR));
547}
548
549ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
550                                            ObjCDictionaryElement *Elements,
551                                            unsigned NumElements) {
552  // Look up the NSDictionary class, if we haven't done so already.
553  if (!NSDictionaryDecl) {
554    NamedDecl *IF = LookupSingleName(TUScope,
555                            NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
556                            SR.getBegin(), LookupOrdinaryName);
557    NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
558    if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
559      NSDictionaryDecl =  ObjCInterfaceDecl::Create (Context,
560                            Context.getTranslationUnitDecl(),
561                            SourceLocation(),
562                            NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
563                            0, SourceLocation());
564
565    if (!NSDictionaryDecl) {
566      Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
567      return ExprError();
568    }
569  }
570
571  // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
572  // so already.
573  QualType IdT = Context.getObjCIdType();
574  if (!DictionaryWithObjectsMethod) {
575    Selector Sel = NSAPIObj->getNSDictionarySelector(
576                                    NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
577    DictionaryWithObjectsMethod = NSDictionaryDecl->lookupClassMethod(Sel);
578    if (!DictionaryWithObjectsMethod && getLangOpts().DebuggerObjCLiteral) {
579      DictionaryWithObjectsMethod =
580                         ObjCMethodDecl::Create(Context,
581                           SourceLocation(), SourceLocation(), Sel,
582                           IdT,
583                           0 /*TypeSourceInfo */,
584                           Context.getTranslationUnitDecl(),
585                           false /*Instance*/, false/*isVariadic*/,
586                           /*isSynthesized=*/false,
587                           /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
588                           ObjCMethodDecl::Required,
589                           false);
590      SmallVector<ParmVarDecl *, 3> Params;
591      ParmVarDecl *objects = ParmVarDecl::Create(Context, DictionaryWithObjectsMethod,
592                                                SourceLocation(), SourceLocation(),
593                                                &Context.Idents.get("objects"),
594                                                Context.getPointerType(IdT),
595                                                /*TInfo=*/0,
596                                                SC_None,
597                                                SC_None,
598                                                0);
599      Params.push_back(objects);
600      ParmVarDecl *keys = ParmVarDecl::Create(Context, DictionaryWithObjectsMethod,
601                                                SourceLocation(), SourceLocation(),
602                                                &Context.Idents.get("keys"),
603                                                Context.getPointerType(IdT),
604                                                /*TInfo=*/0,
605                                                SC_None,
606                                                SC_None,
607                                                0);
608      Params.push_back(keys);
609      ParmVarDecl *cnt = ParmVarDecl::Create(Context, DictionaryWithObjectsMethod,
610                                                SourceLocation(), SourceLocation(),
611                                                &Context.Idents.get("cnt"),
612                                                Context.UnsignedLongTy,
613                                                /*TInfo=*/0,
614                                                SC_None,
615                                                SC_None,
616                                                0);
617      Params.push_back(cnt);
618      DictionaryWithObjectsMethod->setMethodParams(Context, Params,
619                                                   ArrayRef<SourceLocation>());
620    }
621
622    if (!DictionaryWithObjectsMethod) {
623      Diag(SR.getBegin(), diag::err_undeclared_dictwithobjects) << Sel;
624      return ExprError();
625    }
626  }
627
628  // Make sure the return type is reasonable.
629  if (!DictionaryWithObjectsMethod->getResultType()->isObjCObjectPointerType()){
630    Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
631    << DictionaryWithObjectsMethod->getSelector();
632    Diag(DictionaryWithObjectsMethod->getLocation(),
633         diag::note_objc_literal_method_return)
634    << DictionaryWithObjectsMethod->getResultType();
635    return ExprError();
636  }
637
638  // Dig out the type that all values should be converted to.
639  QualType ValueT =  DictionaryWithObjectsMethod->param_begin()[0]->getType();
640  const PointerType *PtrValue = ValueT->getAs<PointerType>();
641  if (!PtrValue ||
642      !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
643    Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
644      << DictionaryWithObjectsMethod->getSelector();
645    Diag(DictionaryWithObjectsMethod->param_begin()[0]->getLocation(),
646         diag::note_objc_literal_method_param)
647      << 0 << ValueT
648      << Context.getPointerType(IdT.withConst());
649    return ExprError();
650  }
651  ValueT = PtrValue->getPointeeType();
652
653  // Dig out the type that all keys should be converted to.
654  QualType KeyT = DictionaryWithObjectsMethod->param_begin()[1]->getType();
655  const PointerType *PtrKey = KeyT->getAs<PointerType>();
656  if (!PtrKey ||
657      !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
658                                      IdT)) {
659    bool err = true;
660    if (PtrKey) {
661      if (QIDNSCopying.isNull()) {
662        // key argument of selector is id<NSCopying>?
663        if (ObjCProtocolDecl *NSCopyingPDecl =
664            LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
665          ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
666          QIDNSCopying =
667            Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
668                                      (ObjCProtocolDecl**) PQ,1);
669          QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
670        }
671      }
672      if (!QIDNSCopying.isNull())
673        err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
674                                              QIDNSCopying);
675    }
676
677    if (err) {
678      Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
679        << DictionaryWithObjectsMethod->getSelector();
680      Diag(DictionaryWithObjectsMethod->param_begin()[1]->getLocation(),
681           diag::note_objc_literal_method_param)
682        << 1 << KeyT
683        << Context.getPointerType(IdT.withConst());
684      return ExprError();
685    }
686  }
687  KeyT = PtrKey->getPointeeType();
688
689  // Check that the 'count' parameter is integral.
690  if (!DictionaryWithObjectsMethod->param_begin()[2]->getType()
691                                                            ->isIntegerType()) {
692    Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
693      << DictionaryWithObjectsMethod->getSelector();
694    Diag(DictionaryWithObjectsMethod->param_begin()[2]->getLocation(),
695         diag::note_objc_literal_method_param)
696      << 2
697      << DictionaryWithObjectsMethod->param_begin()[2]->getType()
698      << "integral";
699    return ExprError();
700  }
701
702  // Check that each of the keys and values provided is valid in a collection
703  // literal, performing conversions as necessary.
704  bool HasPackExpansions = false;
705  for (unsigned I = 0, N = NumElements; I != N; ++I) {
706    // Check the key.
707    ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
708                                                       KeyT);
709    if (Key.isInvalid())
710      return ExprError();
711
712    // Check the value.
713    ExprResult Value
714      = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
715    if (Value.isInvalid())
716      return ExprError();
717
718    Elements[I].Key = Key.get();
719    Elements[I].Value = Value.get();
720
721    if (Elements[I].EllipsisLoc.isInvalid())
722      continue;
723
724    if (!Elements[I].Key->containsUnexpandedParameterPack() &&
725        !Elements[I].Value->containsUnexpandedParameterPack()) {
726      Diag(Elements[I].EllipsisLoc,
727           diag::err_pack_expansion_without_parameter_packs)
728        << SourceRange(Elements[I].Key->getLocStart(),
729                       Elements[I].Value->getLocEnd());
730      return ExprError();
731    }
732
733    HasPackExpansions = true;
734  }
735
736
737  QualType Ty
738    = Context.getObjCObjectPointerType(
739                                Context.getObjCInterfaceType(NSDictionaryDecl));
740  return MaybeBindToTemporary(
741           ObjCDictionaryLiteral::Create(Context,
742                                         llvm::makeArrayRef(Elements,
743                                                            NumElements),
744                                         HasPackExpansions,
745                                         Ty,
746                                         DictionaryWithObjectsMethod, SR));
747}
748
749ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
750                                      TypeSourceInfo *EncodedTypeInfo,
751                                      SourceLocation RParenLoc) {
752  QualType EncodedType = EncodedTypeInfo->getType();
753  QualType StrTy;
754  if (EncodedType->isDependentType())
755    StrTy = Context.DependentTy;
756  else {
757    if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
758        !EncodedType->isVoidType()) // void is handled too.
759      if (RequireCompleteType(AtLoc, EncodedType,
760                         PDiag(diag::err_incomplete_type_objc_at_encode)
761                             << EncodedTypeInfo->getTypeLoc().getSourceRange()))
762        return ExprError();
763
764    std::string Str;
765    Context.getObjCEncodingForType(EncodedType, Str);
766
767    // The type of @encode is the same as the type of the corresponding string,
768    // which is an array type.
769    StrTy = Context.CharTy;
770    // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
771    if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
772      StrTy.addConst();
773    StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
774                                         ArrayType::Normal, 0);
775  }
776
777  return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
778}
779
780ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
781                                           SourceLocation EncodeLoc,
782                                           SourceLocation LParenLoc,
783                                           ParsedType ty,
784                                           SourceLocation RParenLoc) {
785  // FIXME: Preserve type source info ?
786  TypeSourceInfo *TInfo;
787  QualType EncodedType = GetTypeFromParser(ty, &TInfo);
788  if (!TInfo)
789    TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
790                                             PP.getLocForEndOfToken(LParenLoc));
791
792  return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
793}
794
795ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
796                                             SourceLocation AtLoc,
797                                             SourceLocation SelLoc,
798                                             SourceLocation LParenLoc,
799                                             SourceLocation RParenLoc) {
800  ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
801                             SourceRange(LParenLoc, RParenLoc), false, false);
802  if (!Method)
803    Method = LookupFactoryMethodInGlobalPool(Sel,
804                                          SourceRange(LParenLoc, RParenLoc));
805  if (!Method)
806    Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
807
808  if (!Method ||
809      Method->getImplementationControl() != ObjCMethodDecl::Optional) {
810    llvm::DenseMap<Selector, SourceLocation>::iterator Pos
811      = ReferencedSelectors.find(Sel);
812    if (Pos == ReferencedSelectors.end())
813      ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
814  }
815
816  // In ARC, forbid the user from using @selector for
817  // retain/release/autorelease/dealloc/retainCount.
818  if (getLangOpts().ObjCAutoRefCount) {
819    switch (Sel.getMethodFamily()) {
820    case OMF_retain:
821    case OMF_release:
822    case OMF_autorelease:
823    case OMF_retainCount:
824    case OMF_dealloc:
825      Diag(AtLoc, diag::err_arc_illegal_selector) <<
826        Sel << SourceRange(LParenLoc, RParenLoc);
827      break;
828
829    case OMF_None:
830    case OMF_alloc:
831    case OMF_copy:
832    case OMF_finalize:
833    case OMF_init:
834    case OMF_mutableCopy:
835    case OMF_new:
836    case OMF_self:
837    case OMF_performSelector:
838      break;
839    }
840  }
841  QualType Ty = Context.getObjCSelType();
842  return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
843}
844
845ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
846                                             SourceLocation AtLoc,
847                                             SourceLocation ProtoLoc,
848                                             SourceLocation LParenLoc,
849                                             SourceLocation RParenLoc) {
850  ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
851  if (!PDecl) {
852    Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
853    return true;
854  }
855
856  QualType Ty = Context.getObjCProtoType();
857  if (Ty.isNull())
858    return true;
859  Ty = Context.getObjCObjectPointerType(Ty);
860  return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
861}
862
863/// Try to capture an implicit reference to 'self'.
864ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
865  DeclContext *DC = getFunctionLevelDeclContext();
866
867  // If we're not in an ObjC method, error out.  Note that, unlike the
868  // C++ case, we don't require an instance method --- class methods
869  // still have a 'self', and we really do still need to capture it!
870  ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
871  if (!method)
872    return 0;
873
874  tryCaptureVariable(method->getSelfDecl(), Loc);
875
876  return method;
877}
878
879static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
880  if (T == Context.getObjCInstanceType())
881    return Context.getObjCIdType();
882
883  return T;
884}
885
886QualType Sema::getMessageSendResultType(QualType ReceiverType,
887                                        ObjCMethodDecl *Method,
888                                    bool isClassMessage, bool isSuperMessage) {
889  assert(Method && "Must have a method");
890  if (!Method->hasRelatedResultType())
891    return Method->getSendResultType();
892
893  // If a method has a related return type:
894  //   - if the method found is an instance method, but the message send
895  //     was a class message send, T is the declared return type of the method
896  //     found
897  if (Method->isInstanceMethod() && isClassMessage)
898    return stripObjCInstanceType(Context, Method->getSendResultType());
899
900  //   - if the receiver is super, T is a pointer to the class of the
901  //     enclosing method definition
902  if (isSuperMessage) {
903    if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
904      if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
905        return Context.getObjCObjectPointerType(
906                                        Context.getObjCInterfaceType(Class));
907  }
908
909  //   - if the receiver is the name of a class U, T is a pointer to U
910  if (ReceiverType->getAs<ObjCInterfaceType>() ||
911      ReceiverType->isObjCQualifiedInterfaceType())
912    return Context.getObjCObjectPointerType(ReceiverType);
913  //   - if the receiver is of type Class or qualified Class type,
914  //     T is the declared return type of the method.
915  if (ReceiverType->isObjCClassType() ||
916      ReceiverType->isObjCQualifiedClassType())
917    return stripObjCInstanceType(Context, Method->getSendResultType());
918
919  //   - if the receiver is id, qualified id, Class, or qualified Class, T
920  //     is the receiver type, otherwise
921  //   - T is the type of the receiver expression.
922  return ReceiverType;
923}
924
925void Sema::EmitRelatedResultTypeNote(const Expr *E) {
926  E = E->IgnoreParenImpCasts();
927  const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
928  if (!MsgSend)
929    return;
930
931  const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
932  if (!Method)
933    return;
934
935  if (!Method->hasRelatedResultType())
936    return;
937
938  if (Context.hasSameUnqualifiedType(Method->getResultType()
939                                                        .getNonReferenceType(),
940                                     MsgSend->getType()))
941    return;
942
943  if (!Context.hasSameUnqualifiedType(Method->getResultType(),
944                                      Context.getObjCInstanceType()))
945    return;
946
947  Diag(Method->getLocation(), diag::note_related_result_type_inferred)
948    << Method->isInstanceMethod() << Method->getSelector()
949    << MsgSend->getType();
950}
951
952bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
953                                     Expr **Args, unsigned NumArgs,
954                                     Selector Sel, ObjCMethodDecl *Method,
955                                     bool isClassMessage, bool isSuperMessage,
956                                     SourceLocation lbrac, SourceLocation rbrac,
957                                     QualType &ReturnType, ExprValueKind &VK) {
958  if (!Method) {
959    // Apply default argument promotion as for (C99 6.5.2.2p6).
960    for (unsigned i = 0; i != NumArgs; i++) {
961      if (Args[i]->isTypeDependent())
962        continue;
963
964      ExprResult Result = DefaultArgumentPromotion(Args[i]);
965      if (Result.isInvalid())
966        return true;
967      Args[i] = Result.take();
968    }
969
970    unsigned DiagID;
971    if (getLangOpts().ObjCAutoRefCount)
972      DiagID = diag::err_arc_method_not_found;
973    else
974      DiagID = isClassMessage ? diag::warn_class_method_not_found
975                              : diag::warn_inst_method_not_found;
976    if (!getLangOpts().DebuggerSupport)
977      Diag(lbrac, DiagID)
978        << Sel << isClassMessage << SourceRange(lbrac, rbrac);
979
980    // In debuggers, we want to use __unknown_anytype for these
981    // results so that clients can cast them.
982    if (getLangOpts().DebuggerSupport) {
983      ReturnType = Context.UnknownAnyTy;
984    } else {
985      ReturnType = Context.getObjCIdType();
986    }
987    VK = VK_RValue;
988    return false;
989  }
990
991  ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
992                                        isSuperMessage);
993  VK = Expr::getValueKindForType(Method->getResultType());
994
995  unsigned NumNamedArgs = Sel.getNumArgs();
996  // Method might have more arguments than selector indicates. This is due
997  // to addition of c-style arguments in method.
998  if (Method->param_size() > Sel.getNumArgs())
999    NumNamedArgs = Method->param_size();
1000  // FIXME. This need be cleaned up.
1001  if (NumArgs < NumNamedArgs) {
1002    Diag(lbrac, diag::err_typecheck_call_too_few_args)
1003      << 2 << NumNamedArgs << NumArgs;
1004    return false;
1005  }
1006
1007  bool IsError = false;
1008  for (unsigned i = 0; i < NumNamedArgs; i++) {
1009    // We can't do any type-checking on a type-dependent argument.
1010    if (Args[i]->isTypeDependent())
1011      continue;
1012
1013    Expr *argExpr = Args[i];
1014
1015    ParmVarDecl *param = Method->param_begin()[i];
1016    assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
1017
1018    // Strip the unbridged-cast placeholder expression off unless it's
1019    // a consumed argument.
1020    if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1021        !param->hasAttr<CFConsumedAttr>())
1022      argExpr = stripARCUnbridgedCast(argExpr);
1023
1024    if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
1025                            param->getType(),
1026                            PDiag(diag::err_call_incomplete_argument)
1027                              << argExpr->getSourceRange()))
1028      return true;
1029
1030    InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1031                                                                      param);
1032    ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
1033    if (ArgE.isInvalid())
1034      IsError = true;
1035    else
1036      Args[i] = ArgE.takeAs<Expr>();
1037  }
1038
1039  // Promote additional arguments to variadic methods.
1040  if (Method->isVariadic()) {
1041    for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
1042      if (Args[i]->isTypeDependent())
1043        continue;
1044
1045      ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
1046      IsError |= Arg.isInvalid();
1047      Args[i] = Arg.take();
1048    }
1049  } else {
1050    // Check for extra arguments to non-variadic methods.
1051    if (NumArgs != NumNamedArgs) {
1052      Diag(Args[NumNamedArgs]->getLocStart(),
1053           diag::err_typecheck_call_too_many_args)
1054        << 2 /*method*/ << NumNamedArgs << NumArgs
1055        << Method->getSourceRange()
1056        << SourceRange(Args[NumNamedArgs]->getLocStart(),
1057                       Args[NumArgs-1]->getLocEnd());
1058    }
1059  }
1060
1061  DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
1062
1063  // Do additional checkings on method.
1064  IsError |= CheckObjCMethodCall(Method, lbrac, Args, NumArgs);
1065
1066  return IsError;
1067}
1068
1069bool Sema::isSelfExpr(Expr *receiver) {
1070  // 'self' is objc 'self' in an objc method only.
1071  ObjCMethodDecl *method =
1072    dyn_cast<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1073  if (!method) return false;
1074
1075  receiver = receiver->IgnoreParenLValueCasts();
1076  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
1077    if (DRE->getDecl() == method->getSelfDecl())
1078      return true;
1079  return false;
1080}
1081
1082// Helper method for ActOnClassMethod/ActOnInstanceMethod.
1083// Will search "local" class/category implementations for a method decl.
1084// If failed, then we search in class's root for an instance method.
1085// Returns 0 if no method is found.
1086ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
1087                                          ObjCInterfaceDecl *ClassDecl) {
1088  ObjCMethodDecl *Method = 0;
1089  // lookup in class and all superclasses
1090  while (ClassDecl && !Method) {
1091    if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
1092      Method = ImpDecl->getClassMethod(Sel);
1093
1094    // Look through local category implementations associated with the class.
1095    if (!Method)
1096      Method = ClassDecl->getCategoryClassMethod(Sel);
1097
1098    // Before we give up, check if the selector is an instance method.
1099    // But only in the root. This matches gcc's behaviour and what the
1100    // runtime expects.
1101    if (!Method && !ClassDecl->getSuperClass()) {
1102      Method = ClassDecl->lookupInstanceMethod(Sel);
1103      // Look through local category implementations associated
1104      // with the root class.
1105      if (!Method)
1106        Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1107    }
1108
1109    ClassDecl = ClassDecl->getSuperClass();
1110  }
1111  return Method;
1112}
1113
1114ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
1115                                              ObjCInterfaceDecl *ClassDecl) {
1116  if (!ClassDecl->hasDefinition())
1117    return 0;
1118
1119  ObjCMethodDecl *Method = 0;
1120  while (ClassDecl && !Method) {
1121    // If we have implementations in scope, check "private" methods.
1122    if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
1123      Method = ImpDecl->getInstanceMethod(Sel);
1124
1125    // Look through local category implementations associated with the class.
1126    if (!Method)
1127      Method = ClassDecl->getCategoryInstanceMethod(Sel);
1128    ClassDecl = ClassDecl->getSuperClass();
1129  }
1130  return Method;
1131}
1132
1133/// LookupMethodInType - Look up a method in an ObjCObjectType.
1134ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1135                                               bool isInstance) {
1136  const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1137  if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1138    // Look it up in the main interface (and categories, etc.)
1139    if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1140      return method;
1141
1142    // Okay, look for "private" methods declared in any
1143    // @implementations we've seen.
1144    if (isInstance) {
1145      if (ObjCMethodDecl *method = LookupPrivateInstanceMethod(sel, iface))
1146        return method;
1147    } else {
1148      if (ObjCMethodDecl *method = LookupPrivateClassMethod(sel, iface))
1149        return method;
1150    }
1151  }
1152
1153  // Check qualifiers.
1154  for (ObjCObjectType::qual_iterator
1155         i = objType->qual_begin(), e = objType->qual_end(); i != e; ++i)
1156    if (ObjCMethodDecl *method = (*i)->lookupMethod(sel, isInstance))
1157      return method;
1158
1159  return 0;
1160}
1161
1162/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1163/// list of a qualified objective pointer type.
1164ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1165                                              const ObjCObjectPointerType *OPT,
1166                                              bool Instance)
1167{
1168  ObjCMethodDecl *MD = 0;
1169  for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1170       E = OPT->qual_end(); I != E; ++I) {
1171    ObjCProtocolDecl *PROTO = (*I);
1172    if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1173      return MD;
1174    }
1175  }
1176  return 0;
1177}
1178
1179/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1180/// objective C interface.  This is a property reference expression.
1181ExprResult Sema::
1182HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
1183                          Expr *BaseExpr, SourceLocation OpLoc,
1184                          DeclarationName MemberName,
1185                          SourceLocation MemberLoc,
1186                          SourceLocation SuperLoc, QualType SuperType,
1187                          bool Super) {
1188  const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1189  ObjCInterfaceDecl *IFace = IFaceT->getDecl();
1190
1191  if (MemberName.getNameKind() != DeclarationName::Identifier) {
1192    Diag(MemberLoc, diag::err_invalid_property_name)
1193      << MemberName << QualType(OPT, 0);
1194    return ExprError();
1195  }
1196
1197  IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1198  SourceRange BaseRange = Super? SourceRange(SuperLoc)
1199                               : BaseExpr->getSourceRange();
1200  if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
1201                          PDiag(diag::err_property_not_found_forward_class)
1202                            << MemberName << BaseRange))
1203    return ExprError();
1204
1205  // Search for a declared property first.
1206  if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
1207    // Check whether we can reference this property.
1208    if (DiagnoseUseOfDecl(PD, MemberLoc))
1209      return ExprError();
1210
1211    if (Super)
1212      return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
1213                                                     VK_LValue, OK_ObjCProperty,
1214                                                     MemberLoc,
1215                                                     SuperLoc, SuperType));
1216    else
1217      return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
1218                                                     VK_LValue, OK_ObjCProperty,
1219                                                     MemberLoc, BaseExpr));
1220  }
1221  // Check protocols on qualified interfaces.
1222  for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1223       E = OPT->qual_end(); I != E; ++I)
1224    if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
1225      // Check whether we can reference this property.
1226      if (DiagnoseUseOfDecl(PD, MemberLoc))
1227        return ExprError();
1228
1229      if (Super)
1230        return Owned(new (Context) ObjCPropertyRefExpr(PD,
1231                                                       Context.PseudoObjectTy,
1232                                                       VK_LValue,
1233                                                       OK_ObjCProperty,
1234                                                       MemberLoc,
1235                                                       SuperLoc, SuperType));
1236      else
1237        return Owned(new (Context) ObjCPropertyRefExpr(PD,
1238                                                       Context.PseudoObjectTy,
1239                                                       VK_LValue,
1240                                                       OK_ObjCProperty,
1241                                                       MemberLoc,
1242                                                       BaseExpr));
1243    }
1244  // If that failed, look for an "implicit" property by seeing if the nullary
1245  // selector is implemented.
1246
1247  // FIXME: The logic for looking up nullary and unary selectors should be
1248  // shared with the code in ActOnInstanceMessage.
1249
1250  Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1251  ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1252
1253  // May be founf in property's qualified list.
1254  if (!Getter)
1255    Getter = LookupMethodInQualifiedType(Sel, OPT, true);
1256
1257  // If this reference is in an @implementation, check for 'private' methods.
1258  if (!Getter)
1259    Getter = IFace->lookupPrivateMethod(Sel);
1260
1261  // Look through local category implementations associated with the class.
1262  if (!Getter)
1263    Getter = IFace->getCategoryInstanceMethod(Sel);
1264  if (Getter) {
1265    // Check if we can reference this property.
1266    if (DiagnoseUseOfDecl(Getter, MemberLoc))
1267      return ExprError();
1268  }
1269  // If we found a getter then this may be a valid dot-reference, we
1270  // will look for the matching setter, in case it is needed.
1271  Selector SetterSel =
1272    SelectorTable::constructSetterName(PP.getIdentifierTable(),
1273                                       PP.getSelectorTable(), Member);
1274  ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1275
1276  // May be founf in property's qualified list.
1277  if (!Setter)
1278    Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1279
1280  if (!Setter) {
1281    // If this reference is in an @implementation, also check for 'private'
1282    // methods.
1283    Setter = IFace->lookupPrivateMethod(SetterSel);
1284  }
1285  // Look through local category implementations associated with the class.
1286  if (!Setter)
1287    Setter = IFace->getCategoryInstanceMethod(SetterSel);
1288
1289  if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1290    return ExprError();
1291
1292  if (Getter || Setter) {
1293    if (Super)
1294      return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1295                                                     Context.PseudoObjectTy,
1296                                                     VK_LValue, OK_ObjCProperty,
1297                                                     MemberLoc,
1298                                                     SuperLoc, SuperType));
1299    else
1300      return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1301                                                     Context.PseudoObjectTy,
1302                                                     VK_LValue, OK_ObjCProperty,
1303                                                     MemberLoc, BaseExpr));
1304
1305  }
1306
1307  // Attempt to correct for typos in property names.
1308  DeclFilterCCC<ObjCPropertyDecl> Validator;
1309  if (TypoCorrection Corrected = CorrectTypo(
1310      DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
1311      NULL, Validator, IFace, false, OPT)) {
1312    ObjCPropertyDecl *Property =
1313        Corrected.getCorrectionDeclAs<ObjCPropertyDecl>();
1314    DeclarationName TypoResult = Corrected.getCorrection();
1315    Diag(MemberLoc, diag::err_property_not_found_suggest)
1316      << MemberName << QualType(OPT, 0) << TypoResult
1317      << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
1318    Diag(Property->getLocation(), diag::note_previous_decl)
1319      << Property->getDeclName();
1320    return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1321                                     TypoResult, MemberLoc,
1322                                     SuperLoc, SuperType, Super);
1323  }
1324  ObjCInterfaceDecl *ClassDeclared;
1325  if (ObjCIvarDecl *Ivar =
1326      IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1327    QualType T = Ivar->getType();
1328    if (const ObjCObjectPointerType * OBJPT =
1329        T->getAsObjCInterfacePointerType()) {
1330      if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
1331                              PDiag(diag::err_property_not_as_forward_class)
1332                                << MemberName << BaseExpr->getSourceRange()))
1333        return ExprError();
1334    }
1335    Diag(MemberLoc,
1336         diag::err_ivar_access_using_property_syntax_suggest)
1337    << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1338    << FixItHint::CreateReplacement(OpLoc, "->");
1339    return ExprError();
1340  }
1341
1342  Diag(MemberLoc, diag::err_property_not_found)
1343    << MemberName << QualType(OPT, 0);
1344  if (Setter)
1345    Diag(Setter->getLocation(), diag::note_getter_unavailable)
1346          << MemberName << BaseExpr->getSourceRange();
1347  return ExprError();
1348}
1349
1350
1351
1352ExprResult Sema::
1353ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1354                          IdentifierInfo &propertyName,
1355                          SourceLocation receiverNameLoc,
1356                          SourceLocation propertyNameLoc) {
1357
1358  IdentifierInfo *receiverNamePtr = &receiverName;
1359  ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1360                                                  receiverNameLoc);
1361
1362  bool IsSuper = false;
1363  if (IFace == 0) {
1364    // If the "receiver" is 'super' in a method, handle it as an expression-like
1365    // property reference.
1366    if (receiverNamePtr->isStr("super")) {
1367      IsSuper = true;
1368
1369      if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
1370        if (CurMethod->isInstanceMethod()) {
1371          QualType T =
1372            Context.getObjCInterfaceType(CurMethod->getClassInterface());
1373          T = Context.getObjCObjectPointerType(T);
1374
1375          return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
1376                                           /*BaseExpr*/0,
1377                                           SourceLocation()/*OpLoc*/,
1378                                           &propertyName,
1379                                           propertyNameLoc,
1380                                           receiverNameLoc, T, true);
1381        }
1382
1383        // Otherwise, if this is a class method, try dispatching to our
1384        // superclass.
1385        IFace = CurMethod->getClassInterface()->getSuperClass();
1386      }
1387    }
1388
1389    if (IFace == 0) {
1390      Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
1391      return ExprError();
1392    }
1393  }
1394
1395  // Search for a declared property first.
1396  Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
1397  ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
1398
1399  // If this reference is in an @implementation, check for 'private' methods.
1400  if (!Getter)
1401    if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1402      if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1403        if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
1404          Getter = ImpDecl->getClassMethod(Sel);
1405
1406  if (Getter) {
1407    // FIXME: refactor/share with ActOnMemberReference().
1408    // Check if we can reference this property.
1409    if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1410      return ExprError();
1411  }
1412
1413  // Look for the matching setter, in case it is needed.
1414  Selector SetterSel =
1415    SelectorTable::constructSetterName(PP.getIdentifierTable(),
1416                                       PP.getSelectorTable(), &propertyName);
1417
1418  ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1419  if (!Setter) {
1420    // If this reference is in an @implementation, also check for 'private'
1421    // methods.
1422    if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1423      if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1424        if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
1425          Setter = ImpDecl->getClassMethod(SetterSel);
1426  }
1427  // Look through local category implementations associated with the class.
1428  if (!Setter)
1429    Setter = IFace->getCategoryClassMethod(SetterSel);
1430
1431  if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1432    return ExprError();
1433
1434  if (Getter || Setter) {
1435    if (IsSuper)
1436    return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1437                                                   Context.PseudoObjectTy,
1438                                                   VK_LValue, OK_ObjCProperty,
1439                                                   propertyNameLoc,
1440                                                   receiverNameLoc,
1441                                          Context.getObjCInterfaceType(IFace)));
1442
1443    return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1444                                                   Context.PseudoObjectTy,
1445                                                   VK_LValue, OK_ObjCProperty,
1446                                                   propertyNameLoc,
1447                                                   receiverNameLoc, IFace));
1448  }
1449  return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1450                     << &propertyName << Context.getObjCInterfaceType(IFace));
1451}
1452
1453namespace {
1454
1455class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1456 public:
1457  ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1458    // Determine whether "super" is acceptable in the current context.
1459    if (Method && Method->getClassInterface())
1460      WantObjCSuper = Method->getClassInterface()->getSuperClass();
1461  }
1462
1463  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1464    return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1465        candidate.isKeyword("super");
1466  }
1467};
1468
1469}
1470
1471Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
1472                                               IdentifierInfo *Name,
1473                                               SourceLocation NameLoc,
1474                                               bool IsSuper,
1475                                               bool HasTrailingDot,
1476                                               ParsedType &ReceiverType) {
1477  ReceiverType = ParsedType();
1478
1479  // If the identifier is "super" and there is no trailing dot, we're
1480  // messaging super. If the identifier is "super" and there is a
1481  // trailing dot, it's an instance message.
1482  if (IsSuper && S->isInObjcMethodScope())
1483    return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
1484
1485  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1486  LookupName(Result, S);
1487
1488  switch (Result.getResultKind()) {
1489  case LookupResult::NotFound:
1490    // Normal name lookup didn't find anything. If we're in an
1491    // Objective-C method, look for ivars. If we find one, we're done!
1492    // FIXME: This is a hack. Ivar lookup should be part of normal
1493    // lookup.
1494    if (ObjCMethodDecl *Method = getCurMethodDecl()) {
1495      if (!Method->getClassInterface()) {
1496        // Fall back: let the parser try to parse it as an instance message.
1497        return ObjCInstanceMessage;
1498      }
1499
1500      ObjCInterfaceDecl *ClassDeclared;
1501      if (Method->getClassInterface()->lookupInstanceVariable(Name,
1502                                                              ClassDeclared))
1503        return ObjCInstanceMessage;
1504    }
1505
1506    // Break out; we'll perform typo correction below.
1507    break;
1508
1509  case LookupResult::NotFoundInCurrentInstantiation:
1510  case LookupResult::FoundOverloaded:
1511  case LookupResult::FoundUnresolvedValue:
1512  case LookupResult::Ambiguous:
1513    Result.suppressDiagnostics();
1514    return ObjCInstanceMessage;
1515
1516  case LookupResult::Found: {
1517    // If the identifier is a class or not, and there is a trailing dot,
1518    // it's an instance message.
1519    if (HasTrailingDot)
1520      return ObjCInstanceMessage;
1521    // We found something. If it's a type, then we have a class
1522    // message. Otherwise, it's an instance message.
1523    NamedDecl *ND = Result.getFoundDecl();
1524    QualType T;
1525    if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1526      T = Context.getObjCInterfaceType(Class);
1527    else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
1528      T = Context.getTypeDeclType(Type);
1529    else
1530      return ObjCInstanceMessage;
1531
1532    //  We have a class message, and T is the type we're
1533    //  messaging. Build source-location information for it.
1534    TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1535    ReceiverType = CreateParsedType(T, TSInfo);
1536    return ObjCClassMessage;
1537  }
1538  }
1539
1540  ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
1541  if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
1542                                             Result.getLookupKind(), S, NULL,
1543                                             Validator)) {
1544    if (Corrected.isKeyword()) {
1545      // If we've found the keyword "super" (the only keyword that would be
1546      // returned by CorrectTypo), this is a send to super.
1547      Diag(NameLoc, diag::err_unknown_receiver_suggest)
1548        << Name << Corrected.getCorrection()
1549        << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
1550      return ObjCSuperMessage;
1551    } else if (ObjCInterfaceDecl *Class =
1552               Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1553      // If we found a declaration, correct when it refers to an Objective-C
1554      // class.
1555      Diag(NameLoc, diag::err_unknown_receiver_suggest)
1556        << Name << Corrected.getCorrection()
1557        << FixItHint::CreateReplacement(SourceRange(NameLoc),
1558                                        Class->getNameAsString());
1559      Diag(Class->getLocation(), diag::note_previous_decl)
1560        << Corrected.getCorrection();
1561
1562      QualType T = Context.getObjCInterfaceType(Class);
1563      TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1564      ReceiverType = CreateParsedType(T, TSInfo);
1565      return ObjCClassMessage;
1566    }
1567  }
1568
1569  // Fall back: let the parser try to parse it as an instance message.
1570  return ObjCInstanceMessage;
1571}
1572
1573ExprResult Sema::ActOnSuperMessage(Scope *S,
1574                                   SourceLocation SuperLoc,
1575                                   Selector Sel,
1576                                   SourceLocation LBracLoc,
1577                                   ArrayRef<SourceLocation> SelectorLocs,
1578                                   SourceLocation RBracLoc,
1579                                   MultiExprArg Args) {
1580  // Determine whether we are inside a method or not.
1581  ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
1582  if (!Method) {
1583    Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1584    return ExprError();
1585  }
1586
1587  ObjCInterfaceDecl *Class = Method->getClassInterface();
1588  if (!Class) {
1589    Diag(SuperLoc, diag::error_no_super_class_message)
1590      << Method->getDeclName();
1591    return ExprError();
1592  }
1593
1594  ObjCInterfaceDecl *Super = Class->getSuperClass();
1595  if (!Super) {
1596    // The current class does not have a superclass.
1597    Diag(SuperLoc, diag::error_root_class_cannot_use_super)
1598      << Class->getIdentifier();
1599    return ExprError();
1600  }
1601
1602  // We are in a method whose class has a superclass, so 'super'
1603  // is acting as a keyword.
1604  if (Method->isInstanceMethod()) {
1605    if (Sel.getMethodFamily() == OMF_dealloc)
1606      ObjCShouldCallSuperDealloc = false;
1607    if (Sel.getMethodFamily() == OMF_finalize)
1608      ObjCShouldCallSuperFinalize = false;
1609
1610    // Since we are in an instance method, this is an instance
1611    // message to the superclass instance.
1612    QualType SuperTy = Context.getObjCInterfaceType(Super);
1613    SuperTy = Context.getObjCObjectPointerType(SuperTy);
1614    return BuildInstanceMessage(0, SuperTy, SuperLoc,
1615                                Sel, /*Method=*/0,
1616                                LBracLoc, SelectorLocs, RBracLoc, move(Args));
1617  }
1618
1619  // Since we are in a class method, this is a class message to
1620  // the superclass.
1621  return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1622                           Context.getObjCInterfaceType(Super),
1623                           SuperLoc, Sel, /*Method=*/0,
1624                           LBracLoc, SelectorLocs, RBracLoc, move(Args));
1625}
1626
1627
1628ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
1629                                           bool isSuperReceiver,
1630                                           SourceLocation Loc,
1631                                           Selector Sel,
1632                                           ObjCMethodDecl *Method,
1633                                           MultiExprArg Args) {
1634  TypeSourceInfo *receiverTypeInfo = 0;
1635  if (!ReceiverType.isNull())
1636    receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
1637
1638  return BuildClassMessage(receiverTypeInfo, ReceiverType,
1639                          /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
1640                           Sel, Method, Loc, Loc, Loc, Args,
1641                           /*isImplicit=*/true);
1642
1643}
1644
1645static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
1646                               unsigned DiagID,
1647                               bool (*refactor)(const ObjCMessageExpr *,
1648                                              const NSAPI &, edit::Commit &)) {
1649  SourceLocation MsgLoc = Msg->getExprLoc();
1650  if (S.Diags.getDiagnosticLevel(DiagID, MsgLoc) == DiagnosticsEngine::Ignored)
1651    return;
1652
1653  SourceManager &SM = S.SourceMgr;
1654  edit::Commit ECommit(SM, S.LangOpts);
1655  if (refactor(Msg,*S.NSAPIObj, ECommit)) {
1656    DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
1657                        << Msg->getSelector() << Msg->getSourceRange();
1658    // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
1659    if (!ECommit.isCommitable())
1660      return;
1661    for (edit::Commit::edit_iterator
1662           I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
1663      const edit::Commit::Edit &Edit = *I;
1664      switch (Edit.Kind) {
1665      case edit::Commit::Act_Insert:
1666        Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
1667                                                        Edit.Text,
1668                                                        Edit.BeforePrev));
1669        break;
1670      case edit::Commit::Act_InsertFromRange:
1671        Builder.AddFixItHint(
1672            FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
1673                                                Edit.getInsertFromRange(SM),
1674                                                Edit.BeforePrev));
1675        break;
1676      case edit::Commit::Act_Remove:
1677        Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
1678        break;
1679      }
1680    }
1681  }
1682}
1683
1684static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
1685  applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
1686                     edit::rewriteObjCRedundantCallWithLiteral);
1687}
1688
1689/// \brief Build an Objective-C class message expression.
1690///
1691/// This routine takes care of both normal class messages and
1692/// class messages to the superclass.
1693///
1694/// \param ReceiverTypeInfo Type source information that describes the
1695/// receiver of this message. This may be NULL, in which case we are
1696/// sending to the superclass and \p SuperLoc must be a valid source
1697/// location.
1698
1699/// \param ReceiverType The type of the object receiving the
1700/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
1701/// type as that refers to. For a superclass send, this is the type of
1702/// the superclass.
1703///
1704/// \param SuperLoc The location of the "super" keyword in a
1705/// superclass message.
1706///
1707/// \param Sel The selector to which the message is being sent.
1708///
1709/// \param Method The method that this class message is invoking, if
1710/// already known.
1711///
1712/// \param LBracLoc The location of the opening square bracket ']'.
1713///
1714/// \param RBrac The location of the closing square bracket ']'.
1715///
1716/// \param Args The message arguments.
1717ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
1718                                   QualType ReceiverType,
1719                                   SourceLocation SuperLoc,
1720                                   Selector Sel,
1721                                   ObjCMethodDecl *Method,
1722                                   SourceLocation LBracLoc,
1723                                   ArrayRef<SourceLocation> SelectorLocs,
1724                                   SourceLocation RBracLoc,
1725                                   MultiExprArg ArgsIn,
1726                                   bool isImplicit) {
1727  SourceLocation Loc = SuperLoc.isValid()? SuperLoc
1728    : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
1729  if (LBracLoc.isInvalid()) {
1730    Diag(Loc, diag::err_missing_open_square_message_send)
1731      << FixItHint::CreateInsertion(Loc, "[");
1732    LBracLoc = Loc;
1733  }
1734
1735  if (ReceiverType->isDependentType()) {
1736    // If the receiver type is dependent, we can't type-check anything
1737    // at this point. Build a dependent expression.
1738    unsigned NumArgs = ArgsIn.size();
1739    Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1740    assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1741    return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1742                                         VK_RValue, LBracLoc, ReceiverTypeInfo,
1743                                         Sel, SelectorLocs, /*Method=*/0,
1744                                         makeArrayRef(Args, NumArgs),RBracLoc,
1745                                         isImplicit));
1746  }
1747
1748  // Find the class to which we are sending this message.
1749  ObjCInterfaceDecl *Class = 0;
1750  const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1751  if (!ClassType || !(Class = ClassType->getInterface())) {
1752    Diag(Loc, diag::err_invalid_receiver_class_message)
1753      << ReceiverType;
1754    return ExprError();
1755  }
1756  assert(Class && "We don't know which class we're messaging?");
1757  // objc++ diagnoses during typename annotation.
1758  if (!getLangOpts().CPlusPlus)
1759    (void)DiagnoseUseOfDecl(Class, Loc);
1760  // Find the method we are messaging.
1761  if (!Method) {
1762    SourceRange TypeRange
1763      = SuperLoc.isValid()? SourceRange(SuperLoc)
1764                          : ReceiverTypeInfo->getTypeLoc().getSourceRange();
1765    if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
1766                            (getLangOpts().ObjCAutoRefCount
1767                               ? PDiag(diag::err_arc_receiver_forward_class)
1768                               : PDiag(diag::warn_receiver_forward_class))
1769                                   << TypeRange)) {
1770      // A forward class used in messaging is treated as a 'Class'
1771      Method = LookupFactoryMethodInGlobalPool(Sel,
1772                                               SourceRange(LBracLoc, RBracLoc));
1773      if (Method && !getLangOpts().ObjCAutoRefCount)
1774        Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1775          << Method->getDeclName();
1776    }
1777    if (!Method)
1778      Method = Class->lookupClassMethod(Sel);
1779
1780    // If we have an implementation in scope, check "private" methods.
1781    if (!Method)
1782      Method = LookupPrivateClassMethod(Sel, Class);
1783
1784    if (Method && DiagnoseUseOfDecl(Method, Loc))
1785      return ExprError();
1786  }
1787
1788  // Check the argument types and determine the result type.
1789  QualType ReturnType;
1790  ExprValueKind VK = VK_RValue;
1791
1792  unsigned NumArgs = ArgsIn.size();
1793  Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1794  if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1795                                SuperLoc.isValid(), LBracLoc, RBracLoc,
1796                                ReturnType, VK))
1797    return ExprError();
1798
1799  if (Method && !Method->getResultType()->isVoidType() &&
1800      RequireCompleteType(LBracLoc, Method->getResultType(),
1801                          diag::err_illegal_message_expr_incomplete_type))
1802    return ExprError();
1803
1804  // Construct the appropriate ObjCMessageExpr.
1805  ObjCMessageExpr *Result;
1806  if (SuperLoc.isValid())
1807    Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
1808                                     SuperLoc, /*IsInstanceSuper=*/false,
1809                                     ReceiverType, Sel, SelectorLocs,
1810                                     Method, makeArrayRef(Args, NumArgs),
1811                                     RBracLoc, isImplicit);
1812  else {
1813    Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
1814                                     ReceiverTypeInfo, Sel, SelectorLocs,
1815                                     Method, makeArrayRef(Args, NumArgs),
1816                                     RBracLoc, isImplicit);
1817    if (!isImplicit)
1818      checkCocoaAPI(*this, Result);
1819  }
1820  return MaybeBindToTemporary(Result);
1821}
1822
1823// ActOnClassMessage - used for both unary and keyword messages.
1824// ArgExprs is optional - if it is present, the number of expressions
1825// is obtained from Sel.getNumArgs().
1826ExprResult Sema::ActOnClassMessage(Scope *S,
1827                                   ParsedType Receiver,
1828                                   Selector Sel,
1829                                   SourceLocation LBracLoc,
1830                                   ArrayRef<SourceLocation> SelectorLocs,
1831                                   SourceLocation RBracLoc,
1832                                   MultiExprArg Args) {
1833  TypeSourceInfo *ReceiverTypeInfo;
1834  QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
1835  if (ReceiverType.isNull())
1836    return ExprError();
1837
1838
1839  if (!ReceiverTypeInfo)
1840    ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
1841
1842  return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
1843                           /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
1844                           LBracLoc, SelectorLocs, RBracLoc, move(Args));
1845}
1846
1847ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
1848                                              QualType ReceiverType,
1849                                              SourceLocation Loc,
1850                                              Selector Sel,
1851                                              ObjCMethodDecl *Method,
1852                                              MultiExprArg Args) {
1853  return BuildInstanceMessage(Receiver, ReceiverType,
1854                              /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
1855                              Sel, Method, Loc, Loc, Loc, Args,
1856                              /*isImplicit=*/true);
1857}
1858
1859/// \brief Build an Objective-C instance message expression.
1860///
1861/// This routine takes care of both normal instance messages and
1862/// instance messages to the superclass instance.
1863///
1864/// \param Receiver The expression that computes the object that will
1865/// receive this message. This may be empty, in which case we are
1866/// sending to the superclass instance and \p SuperLoc must be a valid
1867/// source location.
1868///
1869/// \param ReceiverType The (static) type of the object receiving the
1870/// message. When a \p Receiver expression is provided, this is the
1871/// same type as that expression. For a superclass instance send, this
1872/// is a pointer to the type of the superclass.
1873///
1874/// \param SuperLoc The location of the "super" keyword in a
1875/// superclass instance message.
1876///
1877/// \param Sel The selector to which the message is being sent.
1878///
1879/// \param Method The method that this instance message is invoking, if
1880/// already known.
1881///
1882/// \param LBracLoc The location of the opening square bracket ']'.
1883///
1884/// \param RBrac The location of the closing square bracket ']'.
1885///
1886/// \param Args The message arguments.
1887ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
1888                                      QualType ReceiverType,
1889                                      SourceLocation SuperLoc,
1890                                      Selector Sel,
1891                                      ObjCMethodDecl *Method,
1892                                      SourceLocation LBracLoc,
1893                                      ArrayRef<SourceLocation> SelectorLocs,
1894                                      SourceLocation RBracLoc,
1895                                      MultiExprArg ArgsIn,
1896                                      bool isImplicit) {
1897  // The location of the receiver.
1898  SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
1899
1900  if (LBracLoc.isInvalid()) {
1901    Diag(Loc, diag::err_missing_open_square_message_send)
1902      << FixItHint::CreateInsertion(Loc, "[");
1903    LBracLoc = Loc;
1904  }
1905
1906  // If we have a receiver expression, perform appropriate promotions
1907  // and determine receiver type.
1908  if (Receiver) {
1909    if (Receiver->hasPlaceholderType()) {
1910      ExprResult Result;
1911      if (Receiver->getType() == Context.UnknownAnyTy)
1912        Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
1913      else
1914        Result = CheckPlaceholderExpr(Receiver);
1915      if (Result.isInvalid()) return ExprError();
1916      Receiver = Result.take();
1917    }
1918
1919    if (Receiver->isTypeDependent()) {
1920      // If the receiver is type-dependent, we can't type-check anything
1921      // at this point. Build a dependent expression.
1922      unsigned NumArgs = ArgsIn.size();
1923      Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1924      assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1925      return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
1926                                           VK_RValue, LBracLoc, Receiver, Sel,
1927                                           SelectorLocs, /*Method=*/0,
1928                                           makeArrayRef(Args, NumArgs),
1929                                           RBracLoc, isImplicit));
1930    }
1931
1932    // If necessary, apply function/array conversion to the receiver.
1933    // C99 6.7.5.3p[7,8].
1934    ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
1935    if (Result.isInvalid())
1936      return ExprError();
1937    Receiver = Result.take();
1938    ReceiverType = Receiver->getType();
1939  }
1940
1941  if (!Method) {
1942    // Handle messages to id.
1943    bool receiverIsId = ReceiverType->isObjCIdType();
1944    if (receiverIsId || ReceiverType->isBlockPointerType() ||
1945        (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
1946      Method = LookupInstanceMethodInGlobalPool(Sel,
1947                                                SourceRange(LBracLoc, RBracLoc),
1948                                                receiverIsId);
1949      if (!Method)
1950        Method = LookupFactoryMethodInGlobalPool(Sel,
1951                                                 SourceRange(LBracLoc, RBracLoc),
1952                                                 receiverIsId);
1953    } else if (ReceiverType->isObjCClassType() ||
1954               ReceiverType->isObjCQualifiedClassType()) {
1955      // Handle messages to Class.
1956      // We allow sending a message to a qualified Class ("Class<foo>"), which
1957      // is ok as long as one of the protocols implements the selector (if not, warn).
1958      if (const ObjCObjectPointerType *QClassTy
1959            = ReceiverType->getAsObjCQualifiedClassType()) {
1960        // Search protocols for class methods.
1961        Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
1962        if (!Method) {
1963          Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
1964          // warn if instance method found for a Class message.
1965          if (Method) {
1966            Diag(Loc, diag::warn_instance_method_on_class_found)
1967              << Method->getSelector() << Sel;
1968            Diag(Method->getLocation(), diag::note_method_declared_at)
1969              << Method->getDeclName();
1970          }
1971        }
1972      } else {
1973        if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
1974          if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
1975            // First check the public methods in the class interface.
1976            Method = ClassDecl->lookupClassMethod(Sel);
1977
1978            if (!Method)
1979              Method = LookupPrivateClassMethod(Sel, ClassDecl);
1980          }
1981          if (Method && DiagnoseUseOfDecl(Method, Loc))
1982            return ExprError();
1983        }
1984        if (!Method) {
1985          // If not messaging 'self', look for any factory method named 'Sel'.
1986          if (!Receiver || !isSelfExpr(Receiver)) {
1987            Method = LookupFactoryMethodInGlobalPool(Sel,
1988                                                SourceRange(LBracLoc, RBracLoc),
1989                                                     true);
1990            if (!Method) {
1991              // If no class (factory) method was found, check if an _instance_
1992              // method of the same name exists in the root class only.
1993              Method = LookupInstanceMethodInGlobalPool(Sel,
1994                                               SourceRange(LBracLoc, RBracLoc),
1995                                                        true);
1996              if (Method)
1997                  if (const ObjCInterfaceDecl *ID =
1998                      dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
1999                    if (ID->getSuperClass())
2000                      Diag(Loc, diag::warn_root_inst_method_not_found)
2001                      << Sel << SourceRange(LBracLoc, RBracLoc);
2002                  }
2003            }
2004          }
2005        }
2006      }
2007    } else {
2008      ObjCInterfaceDecl* ClassDecl = 0;
2009
2010      // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2011      // long as one of the protocols implements the selector (if not, warn).
2012      if (const ObjCObjectPointerType *QIdTy
2013                                   = ReceiverType->getAsObjCQualifiedIdType()) {
2014        // Search protocols for instance methods.
2015        Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2016        if (!Method)
2017          Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
2018      } else if (const ObjCObjectPointerType *OCIType
2019                   = ReceiverType->getAsObjCInterfacePointerType()) {
2020        // We allow sending a message to a pointer to an interface (an object).
2021        ClassDecl = OCIType->getInterfaceDecl();
2022
2023        // Try to complete the type. Under ARC, this is a hard error from which
2024        // we don't try to recover.
2025        const ObjCInterfaceDecl *forwardClass = 0;
2026        if (RequireCompleteType(Loc, OCIType->getPointeeType(),
2027              getLangOpts().ObjCAutoRefCount
2028                ? PDiag(diag::err_arc_receiver_forward_instance)
2029                    << (Receiver ? Receiver->getSourceRange()
2030                                 : SourceRange(SuperLoc))
2031                : PDiag(diag::warn_receiver_forward_instance)
2032                    << (Receiver ? Receiver->getSourceRange()
2033                                 : SourceRange(SuperLoc)))) {
2034          if (getLangOpts().ObjCAutoRefCount)
2035            return ExprError();
2036
2037          forwardClass = OCIType->getInterfaceDecl();
2038          Diag(Receiver ? Receiver->getLocStart()
2039                        : SuperLoc, diag::note_receiver_is_id);
2040          Method = 0;
2041        } else {
2042          Method = ClassDecl->lookupInstanceMethod(Sel);
2043        }
2044
2045        if (!Method)
2046          // Search protocol qualifiers.
2047          Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2048
2049        if (!Method) {
2050          // If we have implementations in scope, check "private" methods.
2051          Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
2052
2053          if (!Method && getLangOpts().ObjCAutoRefCount) {
2054            Diag(Loc, diag::err_arc_may_not_respond)
2055              << OCIType->getPointeeType() << Sel;
2056            return ExprError();
2057          }
2058
2059          if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
2060            // If we still haven't found a method, look in the global pool. This
2061            // behavior isn't very desirable, however we need it for GCC
2062            // compatibility. FIXME: should we deviate??
2063            if (OCIType->qual_empty()) {
2064              Method = LookupInstanceMethodInGlobalPool(Sel,
2065                                                 SourceRange(LBracLoc, RBracLoc));
2066              if (Method && !forwardClass)
2067                Diag(Loc, diag::warn_maynot_respond)
2068                  << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
2069            }
2070          }
2071        }
2072        if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
2073          return ExprError();
2074      } else if (!getLangOpts().ObjCAutoRefCount &&
2075                 !Context.getObjCIdType().isNull() &&
2076                 (ReceiverType->isPointerType() ||
2077                  ReceiverType->isIntegerType())) {
2078        // Implicitly convert integers and pointers to 'id' but emit a warning.
2079        // But not in ARC.
2080        Diag(Loc, diag::warn_bad_receiver_type)
2081          << ReceiverType
2082          << Receiver->getSourceRange();
2083        if (ReceiverType->isPointerType())
2084          Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2085                            CK_CPointerToObjCPointerCast).take();
2086        else {
2087          // TODO: specialized warning on null receivers?
2088          bool IsNull = Receiver->isNullPointerConstant(Context,
2089                                              Expr::NPC_ValueDependentIsNull);
2090          Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2091                            IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
2092        }
2093        ReceiverType = Receiver->getType();
2094      } else {
2095        ExprResult ReceiverRes;
2096        if (getLangOpts().CPlusPlus)
2097          ReceiverRes = PerformContextuallyConvertToObjCPointer(Receiver);
2098        if (ReceiverRes.isUsable()) {
2099          Receiver = ReceiverRes.take();
2100          return BuildInstanceMessage(Receiver,
2101                                      ReceiverType,
2102                                      SuperLoc,
2103                                      Sel,
2104                                      Method,
2105                                      LBracLoc,
2106                                      SelectorLocs,
2107                                      RBracLoc,
2108                                      move(ArgsIn));
2109        } else {
2110          // Reject other random receiver types (e.g. structs).
2111          Diag(Loc, diag::err_bad_receiver_type)
2112            << ReceiverType << Receiver->getSourceRange();
2113          return ExprError();
2114        }
2115      }
2116    }
2117  }
2118
2119  // Check the message arguments.
2120  unsigned NumArgs = ArgsIn.size();
2121  Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
2122  QualType ReturnType;
2123  ExprValueKind VK = VK_RValue;
2124  bool ClassMessage = (ReceiverType->isObjCClassType() ||
2125                       ReceiverType->isObjCQualifiedClassType());
2126  if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
2127                                ClassMessage, SuperLoc.isValid(),
2128                                LBracLoc, RBracLoc, ReturnType, VK))
2129    return ExprError();
2130
2131  if (Method && !Method->getResultType()->isVoidType() &&
2132      RequireCompleteType(LBracLoc, Method->getResultType(),
2133                          diag::err_illegal_message_expr_incomplete_type))
2134    return ExprError();
2135
2136  SourceLocation SelLoc = SelectorLocs.front();
2137
2138  // In ARC, forbid the user from sending messages to
2139  // retain/release/autorelease/dealloc/retainCount explicitly.
2140  if (getLangOpts().ObjCAutoRefCount) {
2141    ObjCMethodFamily family =
2142      (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2143    switch (family) {
2144    case OMF_init:
2145      if (Method)
2146        checkInitMethod(Method, ReceiverType);
2147
2148    case OMF_None:
2149    case OMF_alloc:
2150    case OMF_copy:
2151    case OMF_finalize:
2152    case OMF_mutableCopy:
2153    case OMF_new:
2154    case OMF_self:
2155      break;
2156
2157    case OMF_dealloc:
2158    case OMF_retain:
2159    case OMF_release:
2160    case OMF_autorelease:
2161    case OMF_retainCount:
2162      Diag(Loc, diag::err_arc_illegal_explicit_message)
2163        << Sel << SelLoc;
2164      break;
2165
2166    case OMF_performSelector:
2167      if (Method && NumArgs >= 1) {
2168        if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2169          Selector ArgSel = SelExp->getSelector();
2170          ObjCMethodDecl *SelMethod =
2171            LookupInstanceMethodInGlobalPool(ArgSel,
2172                                             SelExp->getSourceRange());
2173          if (!SelMethod)
2174            SelMethod =
2175              LookupFactoryMethodInGlobalPool(ArgSel,
2176                                              SelExp->getSourceRange());
2177          if (SelMethod) {
2178            ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2179            switch (SelFamily) {
2180              case OMF_alloc:
2181              case OMF_copy:
2182              case OMF_mutableCopy:
2183              case OMF_new:
2184              case OMF_self:
2185              case OMF_init:
2186                // Issue error, unless ns_returns_not_retained.
2187                if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2188                  // selector names a +1 method
2189                  Diag(SelLoc,
2190                       diag::err_arc_perform_selector_retains);
2191                  Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2192                    << SelMethod->getDeclName();
2193                }
2194                break;
2195              default:
2196                // +0 call. OK. unless ns_returns_retained.
2197                if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2198                  // selector names a +1 method
2199                  Diag(SelLoc,
2200                       diag::err_arc_perform_selector_retains);
2201                  Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2202                    << SelMethod->getDeclName();
2203                }
2204                break;
2205            }
2206          }
2207        } else {
2208          // error (may leak).
2209          Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
2210          Diag(Args[0]->getExprLoc(), diag::note_used_here);
2211        }
2212      }
2213      break;
2214    }
2215  }
2216
2217  // Construct the appropriate ObjCMessageExpr instance.
2218  ObjCMessageExpr *Result;
2219  if (SuperLoc.isValid())
2220    Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2221                                     SuperLoc,  /*IsInstanceSuper=*/true,
2222                                     ReceiverType, Sel, SelectorLocs, Method,
2223                                     makeArrayRef(Args, NumArgs), RBracLoc,
2224                                     isImplicit);
2225  else {
2226    Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2227                                     Receiver, Sel, SelectorLocs, Method,
2228                                     makeArrayRef(Args, NumArgs), RBracLoc,
2229                                     isImplicit);
2230    if (!isImplicit)
2231      checkCocoaAPI(*this, Result);
2232  }
2233
2234  if (getLangOpts().ObjCAutoRefCount) {
2235    // In ARC, annotate delegate init calls.
2236    if (Result->getMethodFamily() == OMF_init &&
2237        (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2238      // Only consider init calls *directly* in init implementations,
2239      // not within blocks.
2240      ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2241      if (method && method->getMethodFamily() == OMF_init) {
2242        // The implicit assignment to self means we also don't want to
2243        // consume the result.
2244        Result->setDelegateInitCall(true);
2245        return Owned(Result);
2246      }
2247    }
2248
2249    // In ARC, check for message sends which are likely to introduce
2250    // retain cycles.
2251    checkRetainCycles(Result);
2252  }
2253
2254  return MaybeBindToTemporary(Result);
2255}
2256
2257// ActOnInstanceMessage - used for both unary and keyword messages.
2258// ArgExprs is optional - if it is present, the number of expressions
2259// is obtained from Sel.getNumArgs().
2260ExprResult Sema::ActOnInstanceMessage(Scope *S,
2261                                      Expr *Receiver,
2262                                      Selector Sel,
2263                                      SourceLocation LBracLoc,
2264                                      ArrayRef<SourceLocation> SelectorLocs,
2265                                      SourceLocation RBracLoc,
2266                                      MultiExprArg Args) {
2267  if (!Receiver)
2268    return ExprError();
2269
2270  return BuildInstanceMessage(Receiver, Receiver->getType(),
2271                              /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
2272                              LBracLoc, SelectorLocs, RBracLoc, move(Args));
2273}
2274
2275enum ARCConversionTypeClass {
2276  /// int, void, struct A
2277  ACTC_none,
2278
2279  /// id, void (^)()
2280  ACTC_retainable,
2281
2282  /// id*, id***, void (^*)(),
2283  ACTC_indirectRetainable,
2284
2285  /// void* might be a normal C type, or it might a CF type.
2286  ACTC_voidPtr,
2287
2288  /// struct A*
2289  ACTC_coreFoundation
2290};
2291static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2292  return (ACTC == ACTC_retainable ||
2293          ACTC == ACTC_coreFoundation ||
2294          ACTC == ACTC_voidPtr);
2295}
2296static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2297  return ACTC == ACTC_none ||
2298         ACTC == ACTC_voidPtr ||
2299         ACTC == ACTC_coreFoundation;
2300}
2301
2302static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
2303  bool isIndirect = false;
2304
2305  // Ignore an outermost reference type.
2306  if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
2307    type = ref->getPointeeType();
2308    isIndirect = true;
2309  }
2310
2311  // Drill through pointers and arrays recursively.
2312  while (true) {
2313    if (const PointerType *ptr = type->getAs<PointerType>()) {
2314      type = ptr->getPointeeType();
2315
2316      // The first level of pointer may be the innermost pointer on a CF type.
2317      if (!isIndirect) {
2318        if (type->isVoidType()) return ACTC_voidPtr;
2319        if (type->isRecordType()) return ACTC_coreFoundation;
2320      }
2321    } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2322      type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2323    } else {
2324      break;
2325    }
2326    isIndirect = true;
2327  }
2328
2329  if (isIndirect) {
2330    if (type->isObjCARCBridgableType())
2331      return ACTC_indirectRetainable;
2332    return ACTC_none;
2333  }
2334
2335  if (type->isObjCARCBridgableType())
2336    return ACTC_retainable;
2337
2338  return ACTC_none;
2339}
2340
2341namespace {
2342  /// A result from the cast checker.
2343  enum ACCResult {
2344    /// Cannot be casted.
2345    ACC_invalid,
2346
2347    /// Can be safely retained or not retained.
2348    ACC_bottom,
2349
2350    /// Can be casted at +0.
2351    ACC_plusZero,
2352
2353    /// Can be casted at +1.
2354    ACC_plusOne
2355  };
2356  ACCResult merge(ACCResult left, ACCResult right) {
2357    if (left == right) return left;
2358    if (left == ACC_bottom) return right;
2359    if (right == ACC_bottom) return left;
2360    return ACC_invalid;
2361  }
2362
2363  /// A checker which white-lists certain expressions whose conversion
2364  /// to or from retainable type would otherwise be forbidden in ARC.
2365  class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2366    typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2367
2368    ASTContext &Context;
2369    ARCConversionTypeClass SourceClass;
2370    ARCConversionTypeClass TargetClass;
2371
2372    static bool isCFType(QualType type) {
2373      // Someday this can use ns_bridged.  For now, it has to do this.
2374      return type->isCARCBridgableType();
2375    }
2376
2377  public:
2378    ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
2379                   ARCConversionTypeClass target)
2380      : Context(Context), SourceClass(source), TargetClass(target) {}
2381
2382    using super::Visit;
2383    ACCResult Visit(Expr *e) {
2384      return super::Visit(e->IgnoreParens());
2385    }
2386
2387    ACCResult VisitStmt(Stmt *s) {
2388      return ACC_invalid;
2389    }
2390
2391    /// Null pointer constants can be casted however you please.
2392    ACCResult VisitExpr(Expr *e) {
2393      if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2394        return ACC_bottom;
2395      return ACC_invalid;
2396    }
2397
2398    /// Objective-C string literals can be safely casted.
2399    ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2400      // If we're casting to any retainable type, go ahead.  Global
2401      // strings are immune to retains, so this is bottom.
2402      if (isAnyRetainable(TargetClass)) return ACC_bottom;
2403
2404      return ACC_invalid;
2405    }
2406
2407    /// Look through certain implicit and explicit casts.
2408    ACCResult VisitCastExpr(CastExpr *e) {
2409      switch (e->getCastKind()) {
2410        case CK_NullToPointer:
2411          return ACC_bottom;
2412
2413        case CK_NoOp:
2414        case CK_LValueToRValue:
2415        case CK_BitCast:
2416        case CK_CPointerToObjCPointerCast:
2417        case CK_BlockPointerToObjCPointerCast:
2418        case CK_AnyPointerToBlockPointerCast:
2419          return Visit(e->getSubExpr());
2420
2421        default:
2422          return ACC_invalid;
2423      }
2424    }
2425
2426    /// Look through unary extension.
2427    ACCResult VisitUnaryExtension(UnaryOperator *e) {
2428      return Visit(e->getSubExpr());
2429    }
2430
2431    /// Ignore the LHS of a comma operator.
2432    ACCResult VisitBinComma(BinaryOperator *e) {
2433      return Visit(e->getRHS());
2434    }
2435
2436    /// Conditional operators are okay if both sides are okay.
2437    ACCResult VisitConditionalOperator(ConditionalOperator *e) {
2438      ACCResult left = Visit(e->getTrueExpr());
2439      if (left == ACC_invalid) return ACC_invalid;
2440      return merge(left, Visit(e->getFalseExpr()));
2441    }
2442
2443    /// Look through pseudo-objects.
2444    ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
2445      // If we're getting here, we should always have a result.
2446      return Visit(e->getResultExpr());
2447    }
2448
2449    /// Statement expressions are okay if their result expression is okay.
2450    ACCResult VisitStmtExpr(StmtExpr *e) {
2451      return Visit(e->getSubStmt()->body_back());
2452    }
2453
2454    /// Some declaration references are okay.
2455    ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
2456      // References to global constants from system headers are okay.
2457      // These are things like 'kCFStringTransformToLatin'.  They are
2458      // can also be assumed to be immune to retains.
2459      VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
2460      if (isAnyRetainable(TargetClass) &&
2461          isAnyRetainable(SourceClass) &&
2462          var &&
2463          var->getStorageClass() == SC_Extern &&
2464          var->getType().isConstQualified() &&
2465          Context.getSourceManager().isInSystemHeader(var->getLocation())) {
2466        return ACC_bottom;
2467      }
2468
2469      // Nothing else.
2470      return ACC_invalid;
2471    }
2472
2473    /// Some calls are okay.
2474    ACCResult VisitCallExpr(CallExpr *e) {
2475      if (FunctionDecl *fn = e->getDirectCallee())
2476        if (ACCResult result = checkCallToFunction(fn))
2477          return result;
2478
2479      return super::VisitCallExpr(e);
2480    }
2481
2482    ACCResult checkCallToFunction(FunctionDecl *fn) {
2483      // Require a CF*Ref return type.
2484      if (!isCFType(fn->getResultType()))
2485        return ACC_invalid;
2486
2487      if (!isAnyRetainable(TargetClass))
2488        return ACC_invalid;
2489
2490      // Honor an explicit 'not retained' attribute.
2491      if (fn->hasAttr<CFReturnsNotRetainedAttr>())
2492        return ACC_plusZero;
2493
2494      // Honor an explicit 'retained' attribute, except that for
2495      // now we're not going to permit implicit handling of +1 results,
2496      // because it's a bit frightening.
2497      if (fn->hasAttr<CFReturnsRetainedAttr>())
2498        return ACC_invalid; // ACC_plusOne if we start accepting this
2499
2500      // Recognize this specific builtin function, which is used by CFSTR.
2501      unsigned builtinID = fn->getBuiltinID();
2502      if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
2503        return ACC_bottom;
2504
2505      // Otherwise, don't do anything implicit with an unaudited function.
2506      if (!fn->hasAttr<CFAuditedTransferAttr>())
2507        return ACC_invalid;
2508
2509      // Otherwise, it's +0 unless it follows the create convention.
2510      if (ento::coreFoundation::followsCreateRule(fn))
2511        return ACC_invalid; // ACC_plusOne if we start accepting this
2512
2513      return ACC_plusZero;
2514    }
2515
2516    ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
2517      return checkCallToMethod(e->getMethodDecl());
2518    }
2519
2520    ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
2521      ObjCMethodDecl *method;
2522      if (e->isExplicitProperty())
2523        method = e->getExplicitProperty()->getGetterMethodDecl();
2524      else
2525        method = e->getImplicitPropertyGetter();
2526      return checkCallToMethod(method);
2527    }
2528
2529    ACCResult checkCallToMethod(ObjCMethodDecl *method) {
2530      if (!method) return ACC_invalid;
2531
2532      // Check for message sends to functions returning CF types.  We
2533      // just obey the Cocoa conventions with these, even though the
2534      // return type is CF.
2535      if (!isAnyRetainable(TargetClass) || !isCFType(method->getResultType()))
2536        return ACC_invalid;
2537
2538      // If the method is explicitly marked not-retained, it's +0.
2539      if (method->hasAttr<CFReturnsNotRetainedAttr>())
2540        return ACC_plusZero;
2541
2542      // If the method is explicitly marked as returning retained, or its
2543      // selector follows a +1 Cocoa convention, treat it as +1.
2544      if (method->hasAttr<CFReturnsRetainedAttr>())
2545        return ACC_plusOne;
2546
2547      switch (method->getSelector().getMethodFamily()) {
2548      case OMF_alloc:
2549      case OMF_copy:
2550      case OMF_mutableCopy:
2551      case OMF_new:
2552        return ACC_plusOne;
2553
2554      default:
2555        // Otherwise, treat it as +0.
2556        return ACC_plusZero;
2557      }
2558    }
2559  };
2560}
2561
2562static bool
2563KnownName(Sema &S, const char *name) {
2564  LookupResult R(S, &S.Context.Idents.get(name), SourceLocation(),
2565                 Sema::LookupOrdinaryName);
2566  return S.LookupName(R, S.TUScope, false);
2567}
2568
2569static void addFixitForObjCARCConversion(Sema &S,
2570                                         DiagnosticBuilder &DiagB,
2571                                         Sema::CheckedConversionKind CCK,
2572                                         SourceLocation afterLParen,
2573                                         QualType castType,
2574                                         Expr *castExpr,
2575                                         const char *bridgeKeyword,
2576                                         const char *CFBridgeName) {
2577  // We handle C-style and implicit casts here.
2578  switch (CCK) {
2579  case Sema::CCK_ImplicitConversion:
2580  case Sema::CCK_CStyleCast:
2581    break;
2582  case Sema::CCK_FunctionalCast:
2583  case Sema::CCK_OtherCast:
2584    return;
2585  }
2586
2587  if (CFBridgeName) {
2588    Expr *castedE = castExpr;
2589    if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
2590      castedE = CCE->getSubExpr();
2591    castedE = castedE->IgnoreImpCasts();
2592    SourceRange range = castedE->getSourceRange();
2593    if (isa<ParenExpr>(castedE)) {
2594      DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2595                         CFBridgeName));
2596    } else {
2597      std::string namePlusParen = CFBridgeName;
2598      namePlusParen += "(";
2599      DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2600                                                    namePlusParen));
2601      DiagB.AddFixItHint(FixItHint::CreateInsertion(
2602                                       S.PP.getLocForEndOfToken(range.getEnd()),
2603                                       ")"));
2604    }
2605    return;
2606  }
2607
2608  if (CCK == Sema::CCK_CStyleCast) {
2609    DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
2610  } else {
2611    std::string castCode = "(";
2612    castCode += bridgeKeyword;
2613    castCode += castType.getAsString();
2614    castCode += ")";
2615    Expr *castedE = castExpr->IgnoreImpCasts();
2616    SourceRange range = castedE->getSourceRange();
2617    if (isa<ParenExpr>(castedE)) {
2618      DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2619                         castCode));
2620    } else {
2621      castCode += "(";
2622      DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2623                                                    castCode));
2624      DiagB.AddFixItHint(FixItHint::CreateInsertion(
2625                                       S.PP.getLocForEndOfToken(range.getEnd()),
2626                                       ")"));
2627    }
2628  }
2629}
2630
2631static void
2632diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
2633                          QualType castType, ARCConversionTypeClass castACTC,
2634                          Expr *castExpr, ARCConversionTypeClass exprACTC,
2635                          Sema::CheckedConversionKind CCK) {
2636  SourceLocation loc =
2637    (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
2638
2639  if (S.makeUnavailableInSystemHeader(loc,
2640                "converts between Objective-C and C pointers in -fobjc-arc"))
2641    return;
2642
2643  QualType castExprType = castExpr->getType();
2644
2645  unsigned srcKind = 0;
2646  switch (exprACTC) {
2647  case ACTC_none:
2648  case ACTC_coreFoundation:
2649  case ACTC_voidPtr:
2650    srcKind = (castExprType->isPointerType() ? 1 : 0);
2651    break;
2652  case ACTC_retainable:
2653    srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
2654    break;
2655  case ACTC_indirectRetainable:
2656    srcKind = 4;
2657    break;
2658  }
2659
2660  // Check whether this could be fixed with a bridge cast.
2661  SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
2662  SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
2663
2664  // Bridge from an ARC type to a CF type.
2665  if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
2666
2667    S.Diag(loc, diag::err_arc_cast_requires_bridge)
2668      << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
2669      << 2 // of C pointer type
2670      << castExprType
2671      << unsigned(castType->isBlockPointerType()) // to ObjC|block type
2672      << castType
2673      << castRange
2674      << castExpr->getSourceRange();
2675    bool br = KnownName(S, "CFBridgingRelease");
2676    {
2677      DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge);
2678      addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2679                                   castType, castExpr, "__bridge ", 0);
2680    }
2681    {
2682      DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge_transfer)
2683        << castExprType << br;
2684      addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2685                                   castType, castExpr, "__bridge_transfer ",
2686                                   br ? "CFBridgingRelease" : 0);
2687    }
2688
2689    return;
2690  }
2691
2692  // Bridge from a CF type to an ARC type.
2693  if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
2694    bool br = KnownName(S, "CFBridgingRetain");
2695    S.Diag(loc, diag::err_arc_cast_requires_bridge)
2696      << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
2697      << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
2698      << castExprType
2699      << 2 // to C pointer type
2700      << castType
2701      << castRange
2702      << castExpr->getSourceRange();
2703
2704    {
2705      DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge);
2706      addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2707                                   castType, castExpr, "__bridge ", 0);
2708    }
2709    {
2710      DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge_retained)
2711        << castType << br;
2712      addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2713                                   castType, castExpr, "__bridge_retained ",
2714                                   br ? "CFBridgingRetain" : 0);
2715    }
2716
2717    return;
2718  }
2719
2720  S.Diag(loc, diag::err_arc_mismatched_cast)
2721    << (CCK != Sema::CCK_ImplicitConversion)
2722    << srcKind << castExprType << castType
2723    << castRange << castExpr->getSourceRange();
2724}
2725
2726Sema::ARCConversionResult
2727Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
2728                             Expr *&castExpr, CheckedConversionKind CCK) {
2729  QualType castExprType = castExpr->getType();
2730
2731  // For the purposes of the classification, we assume reference types
2732  // will bind to temporaries.
2733  QualType effCastType = castType;
2734  if (const ReferenceType *ref = castType->getAs<ReferenceType>())
2735    effCastType = ref->getPointeeType();
2736
2737  ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
2738  ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
2739  if (exprACTC == castACTC) {
2740    // check for viablity and report error if casting an rvalue to a
2741    // life-time qualifier.
2742    if ((castACTC == ACTC_retainable) &&
2743        (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
2744        (castType != castExprType)) {
2745      const Type *DT = castType.getTypePtr();
2746      QualType QDT = castType;
2747      // We desugar some types but not others. We ignore those
2748      // that cannot happen in a cast; i.e. auto, and those which
2749      // should not be de-sugared; i.e typedef.
2750      if (const ParenType *PT = dyn_cast<ParenType>(DT))
2751        QDT = PT->desugar();
2752      else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
2753        QDT = TP->desugar();
2754      else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
2755        QDT = AT->desugar();
2756      if (QDT != castType &&
2757          QDT.getObjCLifetime() !=  Qualifiers::OCL_None) {
2758        SourceLocation loc =
2759          (castRange.isValid() ? castRange.getBegin()
2760                              : castExpr->getExprLoc());
2761        Diag(loc, diag::err_arc_nolifetime_behavior);
2762      }
2763    }
2764    return ACR_okay;
2765  }
2766
2767  if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
2768
2769  // Allow all of these types to be cast to integer types (but not
2770  // vice-versa).
2771  if (castACTC == ACTC_none && castType->isIntegralType(Context))
2772    return ACR_okay;
2773
2774  // Allow casts between pointers to lifetime types (e.g., __strong id*)
2775  // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
2776  // must be explicit.
2777  if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
2778    return ACR_okay;
2779  if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
2780      CCK != CCK_ImplicitConversion)
2781    return ACR_okay;
2782
2783  switch (ARCCastChecker(Context, exprACTC, castACTC).Visit(castExpr)) {
2784  // For invalid casts, fall through.
2785  case ACC_invalid:
2786    break;
2787
2788  // Do nothing for both bottom and +0.
2789  case ACC_bottom:
2790  case ACC_plusZero:
2791    return ACR_okay;
2792
2793  // If the result is +1, consume it here.
2794  case ACC_plusOne:
2795    castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
2796                                        CK_ARCConsumeObject, castExpr,
2797                                        0, VK_RValue);
2798    ExprNeedsCleanups = true;
2799    return ACR_okay;
2800  }
2801
2802  // If this is a non-implicit cast from id or block type to a
2803  // CoreFoundation type, delay complaining in case the cast is used
2804  // in an acceptable context.
2805  if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
2806      CCK != CCK_ImplicitConversion)
2807    return ACR_unbridged;
2808
2809  diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
2810                            castExpr, exprACTC, CCK);
2811  return ACR_okay;
2812}
2813
2814/// Given that we saw an expression with the ARCUnbridgedCastTy
2815/// placeholder type, complain bitterly.
2816void Sema::diagnoseARCUnbridgedCast(Expr *e) {
2817  // We expect the spurious ImplicitCastExpr to already have been stripped.
2818  assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
2819  CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
2820
2821  SourceRange castRange;
2822  QualType castType;
2823  CheckedConversionKind CCK;
2824
2825  if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
2826    castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
2827    castType = cast->getTypeAsWritten();
2828    CCK = CCK_CStyleCast;
2829  } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
2830    castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
2831    castType = cast->getTypeAsWritten();
2832    CCK = CCK_OtherCast;
2833  } else {
2834    castType = cast->getType();
2835    CCK = CCK_ImplicitConversion;
2836  }
2837
2838  ARCConversionTypeClass castACTC =
2839    classifyTypeForARCConversion(castType.getNonReferenceType());
2840
2841  Expr *castExpr = realCast->getSubExpr();
2842  assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
2843
2844  diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
2845                            castExpr, ACTC_retainable, CCK);
2846}
2847
2848/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
2849/// type, remove the placeholder cast.
2850Expr *Sema::stripARCUnbridgedCast(Expr *e) {
2851  assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
2852
2853  if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
2854    Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
2855    return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
2856  } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
2857    assert(uo->getOpcode() == UO_Extension);
2858    Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
2859    return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
2860                                   sub->getValueKind(), sub->getObjectKind(),
2861                                       uo->getOperatorLoc());
2862  } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
2863    assert(!gse->isResultDependent());
2864
2865    unsigned n = gse->getNumAssocs();
2866    SmallVector<Expr*, 4> subExprs(n);
2867    SmallVector<TypeSourceInfo*, 4> subTypes(n);
2868    for (unsigned i = 0; i != n; ++i) {
2869      subTypes[i] = gse->getAssocTypeSourceInfo(i);
2870      Expr *sub = gse->getAssocExpr(i);
2871      if (i == gse->getResultIndex())
2872        sub = stripARCUnbridgedCast(sub);
2873      subExprs[i] = sub;
2874    }
2875
2876    return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
2877                                              gse->getControllingExpr(),
2878                                              subTypes.data(), subExprs.data(),
2879                                              n, gse->getDefaultLoc(),
2880                                              gse->getRParenLoc(),
2881                                       gse->containsUnexpandedParameterPack(),
2882                                              gse->getResultIndex());
2883  } else {
2884    assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
2885    return cast<ImplicitCastExpr>(e)->getSubExpr();
2886  }
2887}
2888
2889bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
2890                                                 QualType exprType) {
2891  QualType canCastType =
2892    Context.getCanonicalType(castType).getUnqualifiedType();
2893  QualType canExprType =
2894    Context.getCanonicalType(exprType).getUnqualifiedType();
2895  if (isa<ObjCObjectPointerType>(canCastType) &&
2896      castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
2897      canExprType->isObjCObjectPointerType()) {
2898    if (const ObjCObjectPointerType *ObjT =
2899        canExprType->getAs<ObjCObjectPointerType>())
2900      if (ObjT->getInterfaceDecl()->isArcWeakrefUnavailable())
2901        return false;
2902  }
2903  return true;
2904}
2905
2906/// Look for an ObjCReclaimReturnedObject cast and destroy it.
2907static Expr *maybeUndoReclaimObject(Expr *e) {
2908  // For now, we just undo operands that are *immediately* reclaim
2909  // expressions, which prevents the vast majority of potential
2910  // problems here.  To catch them all, we'd need to rebuild arbitrary
2911  // value-propagating subexpressions --- we can't reliably rebuild
2912  // in-place because of expression sharing.
2913  if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2914    if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
2915      return ice->getSubExpr();
2916
2917  return e;
2918}
2919
2920ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
2921                                      ObjCBridgeCastKind Kind,
2922                                      SourceLocation BridgeKeywordLoc,
2923                                      TypeSourceInfo *TSInfo,
2924                                      Expr *SubExpr) {
2925  ExprResult SubResult = UsualUnaryConversions(SubExpr);
2926  if (SubResult.isInvalid()) return ExprError();
2927  SubExpr = SubResult.take();
2928
2929  QualType T = TSInfo->getType();
2930  QualType FromType = SubExpr->getType();
2931
2932  CastKind CK;
2933
2934  bool MustConsume = false;
2935  if (T->isDependentType() || SubExpr->isTypeDependent()) {
2936    // Okay: we'll build a dependent expression type.
2937    CK = CK_Dependent;
2938  } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
2939    // Casting CF -> id
2940    CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
2941                                  : CK_CPointerToObjCPointerCast);
2942    switch (Kind) {
2943    case OBC_Bridge:
2944      break;
2945
2946    case OBC_BridgeRetained: {
2947      bool br = KnownName(*this, "CFBridgingRelease");
2948      Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
2949        << 2
2950        << FromType
2951        << (T->isBlockPointerType()? 1 : 0)
2952        << T
2953        << SubExpr->getSourceRange()
2954        << Kind;
2955      Diag(BridgeKeywordLoc, diag::note_arc_bridge)
2956        << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
2957      Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
2958        << FromType << br
2959        << FixItHint::CreateReplacement(BridgeKeywordLoc,
2960                                        br ? "CFBridgingRelease "
2961                                           : "__bridge_transfer ");
2962
2963      Kind = OBC_Bridge;
2964      break;
2965    }
2966
2967    case OBC_BridgeTransfer:
2968      // We must consume the Objective-C object produced by the cast.
2969      MustConsume = true;
2970      break;
2971    }
2972  } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
2973    // Okay: id -> CF
2974    CK = CK_BitCast;
2975    switch (Kind) {
2976    case OBC_Bridge:
2977      // Reclaiming a value that's going to be __bridge-casted to CF
2978      // is very dangerous, so we don't do it.
2979      SubExpr = maybeUndoReclaimObject(SubExpr);
2980      break;
2981
2982    case OBC_BridgeRetained:
2983      // Produce the object before casting it.
2984      SubExpr = ImplicitCastExpr::Create(Context, FromType,
2985                                         CK_ARCProduceObject,
2986                                         SubExpr, 0, VK_RValue);
2987      break;
2988
2989    case OBC_BridgeTransfer: {
2990      bool br = KnownName(*this, "CFBridgingRetain");
2991      Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
2992        << (FromType->isBlockPointerType()? 1 : 0)
2993        << FromType
2994        << 2
2995        << T
2996        << SubExpr->getSourceRange()
2997        << Kind;
2998
2999      Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3000        << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
3001      Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
3002        << T << br
3003        << FixItHint::CreateReplacement(BridgeKeywordLoc,
3004                          br ? "CFBridgingRetain " : "__bridge_retained");
3005
3006      Kind = OBC_Bridge;
3007      break;
3008    }
3009    }
3010  } else {
3011    Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
3012      << FromType << T << Kind
3013      << SubExpr->getSourceRange()
3014      << TSInfo->getTypeLoc().getSourceRange();
3015    return ExprError();
3016  }
3017
3018  Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
3019                                                   BridgeKeywordLoc,
3020                                                   TSInfo, SubExpr);
3021
3022  if (MustConsume) {
3023    ExprNeedsCleanups = true;
3024    Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
3025                                      0, VK_RValue);
3026  }
3027
3028  return Result;
3029}
3030
3031ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
3032                                      SourceLocation LParenLoc,
3033                                      ObjCBridgeCastKind Kind,
3034                                      SourceLocation BridgeKeywordLoc,
3035                                      ParsedType Type,
3036                                      SourceLocation RParenLoc,
3037                                      Expr *SubExpr) {
3038  TypeSourceInfo *TSInfo = 0;
3039  QualType T = GetTypeFromParser(Type, &TSInfo);
3040  if (!TSInfo)
3041    TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
3042  return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
3043                              SubExpr);
3044}
3045