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