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