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