clang API Documentation

SemaExprObjC.cpp
Go to the documentation of this file.
00001 //===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file implements semantic analysis for Objective-C expressions.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/Sema/SemaInternal.h"
00015 #include "clang/Sema/Lookup.h"
00016 #include "clang/Sema/Scope.h"
00017 #include "clang/Sema/ScopeInfo.h"
00018 #include "clang/Sema/Initialization.h"
00019 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
00020 #include "clang/Edit/Rewriters.h"
00021 #include "clang/Edit/Commit.h"
00022 #include "clang/AST/ASTContext.h"
00023 #include "clang/AST/DeclObjC.h"
00024 #include "clang/AST/ExprObjC.h"
00025 #include "clang/AST/StmtVisitor.h"
00026 #include "clang/AST/TypeLoc.h"
00027 #include "llvm/ADT/SmallString.h"
00028 #include "clang/Lex/Preprocessor.h"
00029 
00030 using namespace clang;
00031 using namespace sema;
00032 using llvm::makeArrayRef;
00033 
00034 ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
00035                                         Expr **strings,
00036                                         unsigned NumStrings) {
00037   StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
00038 
00039   // Most ObjC strings are formed out of a single piece.  However, we *can*
00040   // have strings formed out of multiple @ strings with multiple pptokens in
00041   // each one, e.g. @"foo" "bar" @"baz" "qux"   which need to be turned into one
00042   // StringLiteral for ObjCStringLiteral to hold onto.
00043   StringLiteral *S = Strings[0];
00044 
00045   // If we have a multi-part string, merge it all together.
00046   if (NumStrings != 1) {
00047     // Concatenate objc strings.
00048     SmallString<128> StrBuf;
00049     SmallVector<SourceLocation, 8> StrLocs;
00050 
00051     for (unsigned i = 0; i != NumStrings; ++i) {
00052       S = Strings[i];
00053 
00054       // ObjC strings can't be wide or UTF.
00055       if (!S->isAscii()) {
00056         Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
00057           << S->getSourceRange();
00058         return true;
00059       }
00060 
00061       // Append the string.
00062       StrBuf += S->getString();
00063 
00064       // Get the locations of the string tokens.
00065       StrLocs.append(S->tokloc_begin(), S->tokloc_end());
00066     }
00067 
00068     // Create the aggregate string with the appropriate content and location
00069     // information.
00070     S = StringLiteral::Create(Context, StrBuf,
00071                               StringLiteral::Ascii, /*Pascal=*/false,
00072                               Context.getPointerType(Context.CharTy),
00073                               &StrLocs[0], StrLocs.size());
00074   }
00075   
00076   return BuildObjCStringLiteral(AtLocs[0], S);
00077 }
00078 
00079 ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
00080   // Verify that this composite string is acceptable for ObjC strings.
00081   if (CheckObjCString(S))
00082     return true;
00083 
00084   // Initialize the constant string interface lazily. This assumes
00085   // the NSString interface is seen in this translation unit. Note: We
00086   // don't use NSConstantString, since the runtime team considers this
00087   // interface private (even though it appears in the header files).
00088   QualType Ty = Context.getObjCConstantStringInterface();
00089   if (!Ty.isNull()) {
00090     Ty = Context.getObjCObjectPointerType(Ty);
00091   } else if (getLangOpts().NoConstantCFStrings) {
00092     IdentifierInfo *NSIdent=0;
00093     std::string StringClass(getLangOpts().ObjCConstantStringClass);
00094     
00095     if (StringClass.empty())
00096       NSIdent = &Context.Idents.get("NSConstantString");
00097     else
00098       NSIdent = &Context.Idents.get(StringClass);
00099     
00100     NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
00101                                      LookupOrdinaryName);
00102     if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
00103       Context.setObjCConstantStringInterface(StrIF);
00104       Ty = Context.getObjCConstantStringInterface();
00105       Ty = Context.getObjCObjectPointerType(Ty);
00106     } else {
00107       // If there is no NSConstantString interface defined then treat this
00108       // as error and recover from it.
00109       Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
00110         << S->getSourceRange();
00111       Ty = Context.getObjCIdType();
00112     }
00113   } else {
00114     IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
00115     NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
00116                                      LookupOrdinaryName);
00117     if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
00118       Context.setObjCConstantStringInterface(StrIF);
00119       Ty = Context.getObjCConstantStringInterface();
00120       Ty = Context.getObjCObjectPointerType(Ty);
00121     } else {
00122       // If there is no NSString interface defined, implicitly declare
00123       // a @class NSString; and use that instead. This is to make sure
00124       // type of an NSString literal is represented correctly, instead of
00125       // being an 'id' type.
00126       Ty = Context.getObjCNSStringType();
00127       if (Ty.isNull()) {
00128         ObjCInterfaceDecl *NSStringIDecl = 
00129           ObjCInterfaceDecl::Create (Context, 
00130                                      Context.getTranslationUnitDecl(), 
00131                                      SourceLocation(), NSIdent, 
00132                                      0, SourceLocation());
00133         Ty = Context.getObjCInterfaceType(NSStringIDecl);
00134         Context.setObjCNSStringType(Ty);
00135       }
00136       Ty = Context.getObjCObjectPointerType(Ty);
00137     }
00138   }
00139 
00140   return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
00141 }
00142 
00143 /// \brief Emits an error if the given method does not exist, or if the return
00144 /// type is not an Objective-C object.
00145 static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
00146                                  const ObjCInterfaceDecl *Class,
00147                                  Selector Sel, const ObjCMethodDecl *Method) {
00148   if (!Method) {
00149     // FIXME: Is there a better way to avoid quotes than using getName()?
00150     S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
00151     return false;
00152   }
00153 
00154   // Make sure the return type is reasonable.
00155   QualType ReturnType = Method->getResultType();
00156   if (!ReturnType->isObjCObjectPointerType()) {
00157     S.Diag(Loc, diag::err_objc_literal_method_sig)
00158       << Sel;
00159     S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
00160       << ReturnType;
00161     return false;
00162   }
00163 
00164   return true;
00165 }
00166 
00167 /// \brief Retrieve the NSNumber factory method that should be used to create
00168 /// an Objective-C literal for the given type.
00169 static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
00170                                                 QualType NumberType,
00171                                                 bool isLiteral = false,
00172                                                 SourceRange R = SourceRange()) {
00173   llvm::Optional<NSAPI::NSNumberLiteralMethodKind> Kind 
00174     = S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
00175   
00176   if (!Kind) {
00177     if (isLiteral) {
00178       S.Diag(Loc, diag::err_invalid_nsnumber_type)
00179         << NumberType << R;
00180     }
00181     return 0;
00182   }
00183   
00184   // If we already looked up this method, we're done.
00185   if (S.NSNumberLiteralMethods[*Kind])
00186     return S.NSNumberLiteralMethods[*Kind];
00187   
00188   Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
00189                                                         /*Instance=*/false);
00190   
00191   ASTContext &CX = S.Context;
00192   
00193   // Look up the NSNumber class, if we haven't done so already. It's cached
00194   // in the Sema instance.
00195   if (!S.NSNumberDecl) {
00196     IdentifierInfo *NSNumberId =
00197       S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber);
00198     NamedDecl *IF = S.LookupSingleName(S.TUScope, NSNumberId,
00199                                        Loc, Sema::LookupOrdinaryName);
00200     S.NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
00201     if (!S.NSNumberDecl) {
00202       if (S.getLangOpts().DebuggerObjCLiteral) {
00203         // Create a stub definition of NSNumber.
00204         S.NSNumberDecl = ObjCInterfaceDecl::Create(CX,
00205                                                    CX.getTranslationUnitDecl(),
00206                                                    SourceLocation(), NSNumberId,
00207                                                    0, SourceLocation());
00208       } else {
00209         // Otherwise, require a declaration of NSNumber.
00210         S.Diag(Loc, diag::err_undeclared_nsnumber);
00211         return 0;
00212       }
00213     } else if (!S.NSNumberDecl->hasDefinition()) {
00214       S.Diag(Loc, diag::err_undeclared_nsnumber);
00215       return 0;
00216     }
00217     
00218     // generate the pointer to NSNumber type.
00219     QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
00220     S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
00221   }
00222   
00223   // Look for the appropriate method within NSNumber.
00224   ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
00225   if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
00226     // create a stub definition this NSNumber factory method.
00227     TypeSourceInfo *ResultTInfo = 0;
00228     Method = ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
00229                                     S.NSNumberPointer, ResultTInfo,
00230                                     S.NSNumberDecl,
00231                                     /*isInstance=*/false, /*isVariadic=*/false,
00232                                     /*isSynthesized=*/false,
00233                                     /*isImplicitlyDeclared=*/true,
00234                                     /*isDefined=*/false,
00235                                     ObjCMethodDecl::Required,
00236                                     /*HasRelatedResultType=*/false);
00237     ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
00238                                              SourceLocation(), SourceLocation(),
00239                                              &CX.Idents.get("value"),
00240                                              NumberType, /*TInfo=*/0, SC_None,
00241                                              SC_None, 0);
00242     Method->setMethodParams(S.Context, value, ArrayRef<SourceLocation>());
00243   }
00244 
00245   if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
00246     return 0;
00247 
00248   // Note: if the parameter type is out-of-line, we'll catch it later in the
00249   // implicit conversion.
00250   
00251   S.NSNumberLiteralMethods[*Kind] = Method;
00252   return Method;
00253 }
00254 
00255 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
00256 /// numeric literal expression. Type of the expression will be "NSNumber *".
00257 ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
00258   // Determine the type of the literal.
00259   QualType NumberType = Number->getType();
00260   if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
00261     // In C, character literals have type 'int'. That's not the type we want
00262     // to use to determine the Objective-c literal kind.
00263     switch (Char->getKind()) {
00264     case CharacterLiteral::Ascii:
00265       NumberType = Context.CharTy;
00266       break;
00267       
00268     case CharacterLiteral::Wide:
00269       NumberType = Context.getWCharType();
00270       break;
00271       
00272     case CharacterLiteral::UTF16:
00273       NumberType = Context.Char16Ty;
00274       break;
00275       
00276     case CharacterLiteral::UTF32:
00277       NumberType = Context.Char32Ty;
00278       break;
00279     }
00280   }
00281   
00282   // Look for the appropriate method within NSNumber.
00283   // Construct the literal.
00284   SourceRange NR(Number->getSourceRange());
00285   ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
00286                                                     true, NR);
00287   if (!Method)
00288     return ExprError();
00289 
00290   // Convert the number to the type that the parameter expects.
00291   ParmVarDecl *ParamDecl = Method->param_begin()[0];
00292   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
00293                                                                     ParamDecl);
00294   ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
00295                                                          SourceLocation(),
00296                                                          Owned(Number));
00297   if (ConvertedNumber.isInvalid())
00298     return ExprError();
00299   Number = ConvertedNumber.get();
00300   
00301   // Use the effective source range of the literal, including the leading '@'.
00302   return MaybeBindToTemporary(
00303            new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
00304                                        SourceRange(AtLoc, NR.getEnd())));
00305 }
00306 
00307 ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc, 
00308                                       SourceLocation ValueLoc,
00309                                       bool Value) {
00310   ExprResult Inner;
00311   if (getLangOpts().CPlusPlus) {
00312     Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
00313   } else {
00314     // C doesn't actually have a way to represent literal values of type 
00315     // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
00316     Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
00317     Inner = ImpCastExprToType(Inner.get(), Context.BoolTy, 
00318                               CK_IntegralToBoolean);
00319   }
00320   
00321   return BuildObjCNumericLiteral(AtLoc, Inner.get());
00322 }
00323 
00324 /// \brief Check that the given expression is a valid element of an Objective-C
00325 /// collection literal.
00326 static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element, 
00327                                                     QualType T) {  
00328   // If the expression is type-dependent, there's nothing for us to do.
00329   if (Element->isTypeDependent())
00330     return Element;
00331 
00332   ExprResult Result = S.CheckPlaceholderExpr(Element);
00333   if (Result.isInvalid())
00334     return ExprError();
00335   Element = Result.get();
00336 
00337   // In C++, check for an implicit conversion to an Objective-C object pointer 
00338   // type.
00339   if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
00340     InitializedEntity Entity
00341       = InitializedEntity::InitializeParameter(S.Context, T,
00342                                                /*Consumed=*/false);
00343     InitializationKind Kind
00344       = InitializationKind::CreateCopy(Element->getLocStart(),
00345                                        SourceLocation());
00346     InitializationSequence Seq(S, Entity, Kind, &Element, 1);
00347     if (!Seq.Failed())
00348       return Seq.Perform(S, Entity, Kind, MultiExprArg(S, &Element, 1));
00349   }
00350 
00351   Expr *OrigElement = Element;
00352 
00353   // Perform lvalue-to-rvalue conversion.
00354   Result = S.DefaultLvalueConversion(Element);
00355   if (Result.isInvalid())
00356     return ExprError();
00357   Element = Result.get();  
00358 
00359   // Make sure that we have an Objective-C pointer type or block.
00360   if (!Element->getType()->isObjCObjectPointerType() &&
00361       !Element->getType()->isBlockPointerType()) {
00362     bool Recovered = false;
00363     
00364     // If this is potentially an Objective-C numeric literal, add the '@'.
00365     if (isa<IntegerLiteral>(OrigElement) || 
00366         isa<CharacterLiteral>(OrigElement) ||
00367         isa<FloatingLiteral>(OrigElement) ||
00368         isa<ObjCBoolLiteralExpr>(OrigElement) ||
00369         isa<CXXBoolLiteralExpr>(OrigElement)) {
00370       if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
00371         int Which = isa<CharacterLiteral>(OrigElement) ? 1
00372                   : (isa<CXXBoolLiteralExpr>(OrigElement) ||
00373                      isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
00374                   : 3;
00375         
00376         S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
00377           << Which << OrigElement->getSourceRange()
00378           << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
00379         
00380         Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
00381                                            OrigElement);
00382         if (Result.isInvalid())
00383           return ExprError();
00384         
00385         Element = Result.get();
00386         Recovered = true;
00387       }
00388     }
00389     // If this is potentially an Objective-C string literal, add the '@'.
00390     else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
00391       if (String->isAscii()) {
00392         S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
00393           << 0 << OrigElement->getSourceRange()
00394           << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
00395 
00396         Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
00397         if (Result.isInvalid())
00398           return ExprError();
00399         
00400         Element = Result.get();
00401         Recovered = true;
00402       }
00403     }
00404     
00405     if (!Recovered) {
00406       S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
00407         << Element->getType();
00408       return ExprError();
00409     }
00410   }
00411   
00412   // Make sure that the element has the type that the container factory 
00413   // function expects. 
00414   return S.PerformCopyInitialization(
00415            InitializedEntity::InitializeParameter(S.Context, T, 
00416                                                   /*Consumed=*/false),
00417            Element->getLocStart(), Element);
00418 }
00419 
00420 ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
00421   if (ValueExpr->isTypeDependent()) {
00422     ObjCBoxedExpr *BoxedExpr = 
00423       new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, NULL, SR);
00424     return Owned(BoxedExpr);
00425   }
00426   ObjCMethodDecl *BoxingMethod = NULL;
00427   QualType BoxedType;
00428   // Convert the expression to an RValue, so we can check for pointer types...
00429   ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
00430   if (RValue.isInvalid()) {
00431     return ExprError();
00432   }
00433   ValueExpr = RValue.get();
00434   QualType ValueType(ValueExpr->getType());
00435   if (const PointerType *PT = ValueType->getAs<PointerType>()) {
00436     QualType PointeeType = PT->getPointeeType();
00437     if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
00438 
00439       if (!NSStringDecl) {
00440         IdentifierInfo *NSStringId =
00441           NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
00442         NamedDecl *Decl = LookupSingleName(TUScope, NSStringId,
00443                                            SR.getBegin(), LookupOrdinaryName);
00444         NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl);
00445         if (!NSStringDecl) {
00446           if (getLangOpts().DebuggerObjCLiteral) {
00447             // Support boxed expressions in the debugger w/o NSString declaration.
00448             DeclContext *TU = Context.getTranslationUnitDecl();
00449             NSStringDecl = ObjCInterfaceDecl::Create(Context, TU,
00450                                                      SourceLocation(),
00451                                                      NSStringId,
00452                                                      0, SourceLocation());
00453           } else {
00454             Diag(SR.getBegin(), diag::err_undeclared_nsstring);
00455             return ExprError();
00456           }
00457         } else if (!NSStringDecl->hasDefinition()) {
00458           Diag(SR.getBegin(), diag::err_undeclared_nsstring);
00459           return ExprError();
00460         }
00461         assert(NSStringDecl && "NSStringDecl should not be NULL");
00462         QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
00463         NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
00464       }
00465       
00466       if (!StringWithUTF8StringMethod) {
00467         IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
00468         Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
00469 
00470         // Look for the appropriate method within NSString.
00471         BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
00472         if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
00473           // Debugger needs to work even if NSString hasn't been defined.
00474           TypeSourceInfo *ResultTInfo = 0;
00475           ObjCMethodDecl *M =
00476             ObjCMethodDecl::Create(Context, SourceLocation(), SourceLocation(),
00477                                    stringWithUTF8String, NSStringPointer,
00478                                    ResultTInfo, NSStringDecl,
00479                                    /*isInstance=*/false, /*isVariadic=*/false,
00480                                    /*isSynthesized=*/false,
00481                                    /*isImplicitlyDeclared=*/true,
00482                                    /*isDefined=*/false,
00483                                    ObjCMethodDecl::Required,
00484                                    /*HasRelatedResultType=*/false);
00485           QualType ConstCharType = Context.CharTy.withConst();
00486           ParmVarDecl *value =
00487             ParmVarDecl::Create(Context, M,
00488                                 SourceLocation(), SourceLocation(),
00489                                 &Context.Idents.get("value"),
00490                                 Context.getPointerType(ConstCharType),
00491                                 /*TInfo=*/0,
00492                                 SC_None, SC_None, 0);
00493           M->setMethodParams(Context, value, ArrayRef<SourceLocation>());
00494           BoxingMethod = M;
00495         }
00496 
00497         if (!validateBoxingMethod(*this, SR.getBegin(), NSStringDecl,
00498                                   stringWithUTF8String, BoxingMethod))
00499            return ExprError();
00500 
00501         StringWithUTF8StringMethod = BoxingMethod;
00502       }
00503       
00504       BoxingMethod = StringWithUTF8StringMethod;
00505       BoxedType = NSStringPointer;
00506     }
00507   } else if (ValueType->isBuiltinType()) {
00508     // The other types we support are numeric, char and BOOL/bool. We could also
00509     // provide limited support for structure types, such as NSRange, NSRect, and
00510     // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
00511     // for more details.
00512 
00513     // Check for a top-level character literal.
00514     if (const CharacterLiteral *Char =
00515         dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
00516       // In C, character literals have type 'int'. That's not the type we want
00517       // to use to determine the Objective-c literal kind.
00518       switch (Char->getKind()) {
00519       case CharacterLiteral::Ascii:
00520         ValueType = Context.CharTy;
00521         break;
00522         
00523       case CharacterLiteral::Wide:
00524         ValueType = Context.getWCharType();
00525         break;
00526         
00527       case CharacterLiteral::UTF16:
00528         ValueType = Context.Char16Ty;
00529         break;
00530         
00531       case CharacterLiteral::UTF32:
00532         ValueType = Context.Char32Ty;
00533         break;
00534       }
00535     }
00536     
00537     // FIXME:  Do I need to do anything special with BoolTy expressions?
00538     
00539     // Look for the appropriate method within NSNumber.
00540     BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType);
00541     BoxedType = NSNumberPointer;
00542 
00543   } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
00544     if (!ET->getDecl()->isComplete()) {
00545       Diag(SR.getBegin(), diag::err_objc_incomplete_boxed_expression_type)
00546         << ValueType << ValueExpr->getSourceRange();
00547       return ExprError();
00548     }
00549 
00550     BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(),
00551                                             ET->getDecl()->getIntegerType());
00552     BoxedType = NSNumberPointer;
00553   }
00554 
00555   if (!BoxingMethod) {
00556     Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type)
00557       << ValueType << ValueExpr->getSourceRange();
00558     return ExprError();
00559   }
00560   
00561   // Convert the expression to the type that the parameter requires.
00562   ParmVarDecl *ParamDecl = BoxingMethod->param_begin()[0];
00563   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
00564                                                                     ParamDecl);
00565   ExprResult ConvertedValueExpr = PerformCopyInitialization(Entity,
00566                                                             SourceLocation(),
00567                                                             Owned(ValueExpr));
00568   if (ConvertedValueExpr.isInvalid())
00569     return ExprError();
00570   ValueExpr = ConvertedValueExpr.get();
00571   
00572   ObjCBoxedExpr *BoxedExpr = 
00573     new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
00574                                       BoxingMethod, SR);
00575   return MaybeBindToTemporary(BoxedExpr);
00576 }
00577 
00578 ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
00579                                         Expr *IndexExpr,
00580                                         ObjCMethodDecl *getterMethod,
00581                                         ObjCMethodDecl *setterMethod) {
00582   // Feature support is for modern abi.
00583   if (!LangOpts.ObjCNonFragileABI)
00584     return ExprError();
00585   // If the expression is type-dependent, there's nothing for us to do.
00586   assert ((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
00587           "base or index cannot have dependent type here");
00588   ExprResult Result = CheckPlaceholderExpr(IndexExpr);
00589   if (Result.isInvalid())
00590     return ExprError();
00591   IndexExpr = Result.get();
00592   
00593   // Perform lvalue-to-rvalue conversion.
00594   Result = DefaultLvalueConversion(BaseExpr);
00595   if (Result.isInvalid())
00596     return ExprError();
00597   BaseExpr = Result.get();
00598   return Owned(ObjCSubscriptRefExpr::Create(Context, 
00599                                             BaseExpr,
00600                                             IndexExpr,
00601                                             Context.PseudoObjectTy,
00602                                             getterMethod,
00603                                             setterMethod, RB));
00604   
00605 }
00606 
00607 ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
00608   // Look up the NSArray class, if we haven't done so already.
00609   if (!NSArrayDecl) {
00610     NamedDecl *IF = LookupSingleName(TUScope,
00611                                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
00612                                  SR.getBegin(),
00613                                  LookupOrdinaryName);
00614     NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
00615     if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
00616       NSArrayDecl =  ObjCInterfaceDecl::Create (Context,
00617                             Context.getTranslationUnitDecl(),
00618                             SourceLocation(),
00619                             NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
00620                             0, SourceLocation());
00621 
00622     if (!NSArrayDecl) {
00623       Diag(SR.getBegin(), diag::err_undeclared_nsarray);
00624       return ExprError();
00625     }
00626   }
00627   
00628   // Find the arrayWithObjects:count: method, if we haven't done so already.
00629   QualType IdT = Context.getObjCIdType();
00630   if (!ArrayWithObjectsMethod) {
00631     Selector
00632       Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
00633     ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
00634     if (!Method && getLangOpts().DebuggerObjCLiteral) {
00635       TypeSourceInfo *ResultTInfo = 0;
00636       Method = ObjCMethodDecl::Create(Context,
00637                            SourceLocation(), SourceLocation(), Sel,
00638                            IdT,
00639                            ResultTInfo,
00640                            Context.getTranslationUnitDecl(),
00641                            false /*Instance*/, false/*isVariadic*/,
00642                            /*isSynthesized=*/false,
00643                            /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
00644                            ObjCMethodDecl::Required,
00645                            false);
00646       SmallVector<ParmVarDecl *, 2> Params;
00647       ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
00648                                                  SourceLocation(),
00649                                                  SourceLocation(),
00650                                                  &Context.Idents.get("objects"),
00651                                                  Context.getPointerType(IdT),
00652                                                  /*TInfo=*/0, SC_None, SC_None,
00653                                                  0);
00654       Params.push_back(objects);
00655       ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
00656                                              SourceLocation(),
00657                                              SourceLocation(),
00658                                              &Context.Idents.get("cnt"),
00659                                              Context.UnsignedLongTy,
00660                                              /*TInfo=*/0, SC_None, SC_None,
00661                                              0);
00662       Params.push_back(cnt);
00663       Method->setMethodParams(Context, Params, ArrayRef<SourceLocation>());
00664     }
00665 
00666     if (!validateBoxingMethod(*this, SR.getBegin(), NSArrayDecl, Sel, Method))
00667       return ExprError();
00668 
00669     // Dig out the type that all elements should be converted to.
00670     QualType T = Method->param_begin()[0]->getType();
00671     const PointerType *PtrT = T->getAs<PointerType>();
00672     if (!PtrT || 
00673         !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
00674       Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
00675         << Sel;
00676       Diag(Method->param_begin()[0]->getLocation(),
00677            diag::note_objc_literal_method_param)
00678         << 0 << T 
00679         << Context.getPointerType(IdT.withConst());
00680       return ExprError();
00681     }
00682   
00683     // Check that the 'count' parameter is integral.
00684     if (!Method->param_begin()[1]->getType()->isIntegerType()) {
00685       Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
00686         << Sel;
00687       Diag(Method->param_begin()[1]->getLocation(),
00688            diag::note_objc_literal_method_param)
00689         << 1 
00690         << Method->param_begin()[1]->getType()
00691         << "integral";
00692       return ExprError();
00693     }
00694 
00695     // We've found a good +arrayWithObjects:count: method. Save it!
00696     ArrayWithObjectsMethod = Method;
00697   }
00698 
00699   QualType ObjectsType = ArrayWithObjectsMethod->param_begin()[0]->getType();
00700   QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
00701 
00702   // Check that each of the elements provided is valid in a collection literal,
00703   // performing conversions as necessary.
00704   Expr **ElementsBuffer = Elements.get();
00705   for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
00706     ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
00707                                                              ElementsBuffer[I],
00708                                                              RequiredType);
00709     if (Converted.isInvalid())
00710       return ExprError();
00711     
00712     ElementsBuffer[I] = Converted.get();
00713   }
00714     
00715   QualType Ty 
00716     = Context.getObjCObjectPointerType(
00717                                     Context.getObjCInterfaceType(NSArrayDecl));
00718 
00719   return MaybeBindToTemporary(
00720            ObjCArrayLiteral::Create(Context, 
00721                                     llvm::makeArrayRef(Elements.get(), 
00722                                                        Elements.size()), 
00723                                     Ty, ArrayWithObjectsMethod, SR));
00724 }
00725 
00726 ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR, 
00727                                             ObjCDictionaryElement *Elements,
00728                                             unsigned NumElements) {
00729   // Look up the NSDictionary class, if we haven't done so already.
00730   if (!NSDictionaryDecl) {
00731     NamedDecl *IF = LookupSingleName(TUScope,
00732                             NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
00733                             SR.getBegin(), LookupOrdinaryName);
00734     NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
00735     if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
00736       NSDictionaryDecl =  ObjCInterfaceDecl::Create (Context,
00737                             Context.getTranslationUnitDecl(),
00738                             SourceLocation(),
00739                             NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
00740                             0, SourceLocation());
00741 
00742     if (!NSDictionaryDecl) {
00743       Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
00744       return ExprError();    
00745     }
00746   }
00747   
00748   // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
00749   // so already.
00750   QualType IdT = Context.getObjCIdType();
00751   if (!DictionaryWithObjectsMethod) {
00752     Selector Sel = NSAPIObj->getNSDictionarySelector(
00753                                NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
00754     ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
00755     if (!Method && getLangOpts().DebuggerObjCLiteral) {
00756       Method = ObjCMethodDecl::Create(Context,  
00757                            SourceLocation(), SourceLocation(), Sel,
00758                            IdT,
00759                            0 /*TypeSourceInfo */,
00760                            Context.getTranslationUnitDecl(),
00761                            false /*Instance*/, false/*isVariadic*/,
00762                            /*isSynthesized=*/false,
00763                            /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
00764                            ObjCMethodDecl::Required,
00765                            false);
00766       SmallVector<ParmVarDecl *, 3> Params;
00767       ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
00768                                                  SourceLocation(),
00769                                                  SourceLocation(),
00770                                                  &Context.Idents.get("objects"),
00771                                                  Context.getPointerType(IdT),
00772                                                  /*TInfo=*/0, SC_None, SC_None,
00773                                                  0);
00774       Params.push_back(objects);
00775       ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
00776                                               SourceLocation(),
00777                                               SourceLocation(),
00778                                               &Context.Idents.get("keys"),
00779                                               Context.getPointerType(IdT),
00780                                               /*TInfo=*/0, SC_None, SC_None,
00781                                               0);
00782       Params.push_back(keys);
00783       ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
00784                                              SourceLocation(),
00785                                              SourceLocation(),
00786                                              &Context.Idents.get("cnt"),
00787                                              Context.UnsignedLongTy,
00788                                              /*TInfo=*/0, SC_None, SC_None,
00789                                              0);
00790       Params.push_back(cnt);
00791       Method->setMethodParams(Context, Params, ArrayRef<SourceLocation>());
00792     }
00793 
00794     if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
00795                               Method))
00796        return ExprError();
00797 
00798     // Dig out the type that all values should be converted to.
00799     QualType ValueT = Method->param_begin()[0]->getType();
00800     const PointerType *PtrValue = ValueT->getAs<PointerType>();
00801     if (!PtrValue || 
00802         !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
00803       Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
00804         << Sel;
00805       Diag(Method->param_begin()[0]->getLocation(),
00806            diag::note_objc_literal_method_param)
00807         << 0 << ValueT
00808         << Context.getPointerType(IdT.withConst());
00809       return ExprError();
00810     }
00811 
00812     // Dig out the type that all keys should be converted to.
00813     QualType KeyT = Method->param_begin()[1]->getType();
00814     const PointerType *PtrKey = KeyT->getAs<PointerType>();
00815     if (!PtrKey || 
00816         !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
00817                                         IdT)) {
00818       bool err = true;
00819       if (PtrKey) {
00820         if (QIDNSCopying.isNull()) {
00821           // key argument of selector is id<NSCopying>?
00822           if (ObjCProtocolDecl *NSCopyingPDecl =
00823               LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
00824             ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
00825             QIDNSCopying = 
00826               Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
00827                                         (ObjCProtocolDecl**) PQ,1);
00828             QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
00829           }
00830         }
00831         if (!QIDNSCopying.isNull())
00832           err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
00833                                                 QIDNSCopying);
00834       }
00835     
00836       if (err) {
00837         Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
00838           << Sel;
00839         Diag(Method->param_begin()[1]->getLocation(),
00840              diag::note_objc_literal_method_param)
00841           << 1 << KeyT
00842           << Context.getPointerType(IdT.withConst());
00843         return ExprError();
00844       }
00845     }
00846 
00847     // Check that the 'count' parameter is integral.
00848     QualType CountType = Method->param_begin()[2]->getType();
00849     if (!CountType->isIntegerType()) {
00850       Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
00851         << Sel;
00852       Diag(Method->param_begin()[2]->getLocation(),
00853            diag::note_objc_literal_method_param)
00854         << 2 << CountType
00855         << "integral";
00856       return ExprError();
00857     }
00858 
00859     // We've found a good +dictionaryWithObjects:keys:count: method; save it!
00860     DictionaryWithObjectsMethod = Method;
00861   }
00862 
00863   QualType ValuesT = DictionaryWithObjectsMethod->param_begin()[0]->getType();
00864   QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
00865   QualType KeysT = DictionaryWithObjectsMethod->param_begin()[1]->getType();
00866   QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
00867 
00868   // Check that each of the keys and values provided is valid in a collection 
00869   // literal, performing conversions as necessary.
00870   bool HasPackExpansions = false;
00871   for (unsigned I = 0, N = NumElements; I != N; ++I) {
00872     // Check the key.
00873     ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key, 
00874                                                        KeyT);
00875     if (Key.isInvalid())
00876       return ExprError();
00877     
00878     // Check the value.
00879     ExprResult Value
00880       = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
00881     if (Value.isInvalid())
00882       return ExprError();
00883     
00884     Elements[I].Key = Key.get();
00885     Elements[I].Value = Value.get();
00886     
00887     if (Elements[I].EllipsisLoc.isInvalid())
00888       continue;
00889     
00890     if (!Elements[I].Key->containsUnexpandedParameterPack() &&
00891         !Elements[I].Value->containsUnexpandedParameterPack()) {
00892       Diag(Elements[I].EllipsisLoc, 
00893            diag::err_pack_expansion_without_parameter_packs)
00894         << SourceRange(Elements[I].Key->getLocStart(),
00895                        Elements[I].Value->getLocEnd());
00896       return ExprError();
00897     }
00898     
00899     HasPackExpansions = true;
00900   }
00901 
00902   
00903   QualType Ty
00904     = Context.getObjCObjectPointerType(
00905                                 Context.getObjCInterfaceType(NSDictionaryDecl));  
00906   return MaybeBindToTemporary(
00907            ObjCDictionaryLiteral::Create(Context, 
00908                                          llvm::makeArrayRef(Elements, 
00909                                                             NumElements),
00910                                          HasPackExpansions,
00911                                          Ty, 
00912                                          DictionaryWithObjectsMethod, SR));
00913 }
00914 
00915 ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
00916                                       TypeSourceInfo *EncodedTypeInfo,
00917                                       SourceLocation RParenLoc) {
00918   QualType EncodedType = EncodedTypeInfo->getType();
00919   QualType StrTy;
00920   if (EncodedType->isDependentType())
00921     StrTy = Context.DependentTy;
00922   else {
00923     if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
00924         !EncodedType->isVoidType()) // void is handled too.
00925       if (RequireCompleteType(AtLoc, EncodedType,
00926                               diag::err_incomplete_type_objc_at_encode,
00927                               EncodedTypeInfo->getTypeLoc()))
00928         return ExprError();
00929 
00930     std::string Str;
00931     Context.getObjCEncodingForType(EncodedType, Str);
00932 
00933     // The type of @encode is the same as the type of the corresponding string,
00934     // which is an array type.
00935     StrTy = Context.CharTy;
00936     // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
00937     if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
00938       StrTy.addConst();
00939     StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
00940                                          ArrayType::Normal, 0);
00941   }
00942 
00943   return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
00944 }
00945 
00946 ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
00947                                            SourceLocation EncodeLoc,
00948                                            SourceLocation LParenLoc,
00949                                            ParsedType ty,
00950                                            SourceLocation RParenLoc) {
00951   // FIXME: Preserve type source info ?
00952   TypeSourceInfo *TInfo;
00953   QualType EncodedType = GetTypeFromParser(ty, &TInfo);
00954   if (!TInfo)
00955     TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
00956                                              PP.getLocForEndOfToken(LParenLoc));
00957 
00958   return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
00959 }
00960 
00961 ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
00962                                              SourceLocation AtLoc,
00963                                              SourceLocation SelLoc,
00964                                              SourceLocation LParenLoc,
00965                                              SourceLocation RParenLoc) {
00966   ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
00967                              SourceRange(LParenLoc, RParenLoc), false, false);
00968   if (!Method)
00969     Method = LookupFactoryMethodInGlobalPool(Sel,
00970                                           SourceRange(LParenLoc, RParenLoc));
00971   if (!Method)
00972     Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
00973   
00974   if (!Method ||
00975       Method->getImplementationControl() != ObjCMethodDecl::Optional) {
00976     llvm::DenseMap<Selector, SourceLocation>::iterator Pos
00977       = ReferencedSelectors.find(Sel);
00978     if (Pos == ReferencedSelectors.end())
00979       ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
00980   }
00981 
00982   // In ARC, forbid the user from using @selector for 
00983   // retain/release/autorelease/dealloc/retainCount.
00984   if (getLangOpts().ObjCAutoRefCount) {
00985     switch (Sel.getMethodFamily()) {
00986     case OMF_retain:
00987     case OMF_release:
00988     case OMF_autorelease:
00989     case OMF_retainCount:
00990     case OMF_dealloc:
00991       Diag(AtLoc, diag::err_arc_illegal_selector) << 
00992         Sel << SourceRange(LParenLoc, RParenLoc);
00993       break;
00994 
00995     case OMF_None:
00996     case OMF_alloc:
00997     case OMF_copy:
00998     case OMF_finalize:
00999     case OMF_init:
01000     case OMF_mutableCopy:
01001     case OMF_new:
01002     case OMF_self:
01003     case OMF_performSelector:
01004       break;
01005     }
01006   }
01007   QualType Ty = Context.getObjCSelType();
01008   return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
01009 }
01010 
01011 ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
01012                                              SourceLocation AtLoc,
01013                                              SourceLocation ProtoLoc,
01014                                              SourceLocation LParenLoc,
01015                                              SourceLocation ProtoIdLoc,
01016                                              SourceLocation RParenLoc) {
01017   ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
01018   if (!PDecl) {
01019     Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
01020     return true;
01021   }
01022 
01023   QualType Ty = Context.getObjCProtoType();
01024   if (Ty.isNull())
01025     return true;
01026   Ty = Context.getObjCObjectPointerType(Ty);
01027   return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
01028 }
01029 
01030 /// Try to capture an implicit reference to 'self'.
01031 ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
01032   DeclContext *DC = getFunctionLevelDeclContext();
01033 
01034   // If we're not in an ObjC method, error out.  Note that, unlike the
01035   // C++ case, we don't require an instance method --- class methods
01036   // still have a 'self', and we really do still need to capture it!
01037   ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
01038   if (!method)
01039     return 0;
01040 
01041   tryCaptureVariable(method->getSelfDecl(), Loc);
01042 
01043   return method;
01044 }
01045 
01046 static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
01047   if (T == Context.getObjCInstanceType())
01048     return Context.getObjCIdType();
01049   
01050   return T;
01051 }
01052 
01053 QualType Sema::getMessageSendResultType(QualType ReceiverType,
01054                                         ObjCMethodDecl *Method,
01055                                     bool isClassMessage, bool isSuperMessage) {
01056   assert(Method && "Must have a method");
01057   if (!Method->hasRelatedResultType())
01058     return Method->getSendResultType();
01059   
01060   // If a method has a related return type:
01061   //   - if the method found is an instance method, but the message send
01062   //     was a class message send, T is the declared return type of the method
01063   //     found
01064   if (Method->isInstanceMethod() && isClassMessage)
01065     return stripObjCInstanceType(Context, Method->getSendResultType());
01066   
01067   //   - if the receiver is super, T is a pointer to the class of the 
01068   //     enclosing method definition
01069   if (isSuperMessage) {
01070     if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
01071       if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
01072         return Context.getObjCObjectPointerType(
01073                                         Context.getObjCInterfaceType(Class));
01074   }
01075     
01076   //   - if the receiver is the name of a class U, T is a pointer to U
01077   if (ReceiverType->getAs<ObjCInterfaceType>() ||
01078       ReceiverType->isObjCQualifiedInterfaceType())
01079     return Context.getObjCObjectPointerType(ReceiverType);
01080   //   - if the receiver is of type Class or qualified Class type, 
01081   //     T is the declared return type of the method.
01082   if (ReceiverType->isObjCClassType() ||
01083       ReceiverType->isObjCQualifiedClassType())
01084     return stripObjCInstanceType(Context, Method->getSendResultType());
01085   
01086   //   - if the receiver is id, qualified id, Class, or qualified Class, T
01087   //     is the receiver type, otherwise
01088   //   - T is the type of the receiver expression.
01089   return ReceiverType;
01090 }
01091 
01092 void Sema::EmitRelatedResultTypeNote(const Expr *E) {
01093   E = E->IgnoreParenImpCasts();
01094   const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
01095   if (!MsgSend)
01096     return;
01097   
01098   const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
01099   if (!Method)
01100     return;
01101   
01102   if (!Method->hasRelatedResultType())
01103     return;
01104   
01105   if (Context.hasSameUnqualifiedType(Method->getResultType()
01106                                                         .getNonReferenceType(),
01107                                      MsgSend->getType()))
01108     return;
01109   
01110   if (!Context.hasSameUnqualifiedType(Method->getResultType(), 
01111                                       Context.getObjCInstanceType()))
01112     return;
01113   
01114   Diag(Method->getLocation(), diag::note_related_result_type_inferred)
01115     << Method->isInstanceMethod() << Method->getSelector()
01116     << MsgSend->getType();
01117 }
01118 
01119 bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
01120                                      Expr **Args, unsigned NumArgs,
01121                                      Selector Sel, ObjCMethodDecl *Method,
01122                                      bool isClassMessage, bool isSuperMessage,
01123                                      SourceLocation lbrac, SourceLocation rbrac,
01124                                      QualType &ReturnType, ExprValueKind &VK) {
01125   if (!Method) {
01126     // Apply default argument promotion as for (C99 6.5.2.2p6).
01127     for (unsigned i = 0; i != NumArgs; i++) {
01128       if (Args[i]->isTypeDependent())
01129         continue;
01130 
01131       ExprResult Result = DefaultArgumentPromotion(Args[i]);
01132       if (Result.isInvalid())
01133         return true;
01134       Args[i] = Result.take();
01135     }
01136 
01137     unsigned DiagID;
01138     if (getLangOpts().ObjCAutoRefCount)
01139       DiagID = diag::err_arc_method_not_found;
01140     else
01141       DiagID = isClassMessage ? diag::warn_class_method_not_found
01142                               : diag::warn_inst_method_not_found;
01143     if (!getLangOpts().DebuggerSupport)
01144       Diag(lbrac, DiagID)
01145         << Sel << isClassMessage << SourceRange(lbrac, rbrac);
01146 
01147     // In debuggers, we want to use __unknown_anytype for these
01148     // results so that clients can cast them.
01149     if (getLangOpts().DebuggerSupport) {
01150       ReturnType = Context.UnknownAnyTy;
01151     } else {
01152       ReturnType = Context.getObjCIdType();
01153     }
01154     VK = VK_RValue;
01155     return false;
01156   }
01157 
01158   ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage, 
01159                                         isSuperMessage);
01160   VK = Expr::getValueKindForType(Method->getResultType());
01161 
01162   unsigned NumNamedArgs = Sel.getNumArgs();
01163   // Method might have more arguments than selector indicates. This is due
01164   // to addition of c-style arguments in method.
01165   if (Method->param_size() > Sel.getNumArgs())
01166     NumNamedArgs = Method->param_size();
01167   // FIXME. This need be cleaned up.
01168   if (NumArgs < NumNamedArgs) {
01169     Diag(lbrac, diag::err_typecheck_call_too_few_args)
01170       << 2 << NumNamedArgs << NumArgs;
01171     return false;
01172   }
01173 
01174   bool IsError = false;
01175   for (unsigned i = 0; i < NumNamedArgs; i++) {
01176     // We can't do any type-checking on a type-dependent argument.
01177     if (Args[i]->isTypeDependent())
01178       continue;
01179 
01180     Expr *argExpr = Args[i];
01181 
01182     ParmVarDecl *param = Method->param_begin()[i];
01183     assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
01184 
01185     // Strip the unbridged-cast placeholder expression off unless it's
01186     // a consumed argument.
01187     if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
01188         !param->hasAttr<CFConsumedAttr>())
01189       argExpr = stripARCUnbridgedCast(argExpr);
01190 
01191     if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
01192                             param->getType(),
01193                             diag::err_call_incomplete_argument, argExpr))
01194       return true;
01195 
01196     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
01197                                                                       param);
01198     ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
01199     if (ArgE.isInvalid())
01200       IsError = true;
01201     else
01202       Args[i] = ArgE.takeAs<Expr>();
01203   }
01204 
01205   // Promote additional arguments to variadic methods.
01206   if (Method->isVariadic()) {
01207     for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
01208       if (Args[i]->isTypeDependent())
01209         continue;
01210 
01211       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
01212                                                         0);
01213       IsError |= Arg.isInvalid();
01214       Args[i] = Arg.take();
01215     }
01216   } else {
01217     // Check for extra arguments to non-variadic methods.
01218     if (NumArgs != NumNamedArgs) {
01219       Diag(Args[NumNamedArgs]->getLocStart(),
01220            diag::err_typecheck_call_too_many_args)
01221         << 2 /*method*/ << NumNamedArgs << NumArgs
01222         << Method->getSourceRange()
01223         << SourceRange(Args[NumNamedArgs]->getLocStart(),
01224                        Args[NumArgs-1]->getLocEnd());
01225     }
01226   }
01227 
01228   DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
01229 
01230   // Do additional checkings on method.
01231   IsError |= CheckObjCMethodCall(Method, lbrac, Args, NumArgs);
01232 
01233   return IsError;
01234 }
01235 
01236 bool Sema::isSelfExpr(Expr *receiver) {
01237   // 'self' is objc 'self' in an objc method only.
01238   ObjCMethodDecl *method =
01239     dyn_cast<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
01240   if (!method) return false;
01241 
01242   receiver = receiver->IgnoreParenLValueCasts();
01243   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
01244     if (DRE->getDecl() == method->getSelfDecl())
01245       return true;
01246   return false;
01247 }
01248 
01249 // Helper method for ActOnClassMethod/ActOnInstanceMethod.
01250 // Will search "local" class/category implementations for a method decl.
01251 // If failed, then we search in class's root for an instance method.
01252 // Returns 0 if no method is found.
01253 ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
01254                                           ObjCInterfaceDecl *ClassDecl) {
01255   ObjCMethodDecl *Method = 0;
01256   // lookup in class and all superclasses
01257   while (ClassDecl && !Method) {
01258     if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
01259       Method = ImpDecl->getClassMethod(Sel);
01260 
01261     // Look through local category implementations associated with the class.
01262     if (!Method)
01263       Method = ClassDecl->getCategoryClassMethod(Sel);
01264 
01265     // Before we give up, check if the selector is an instance method.
01266     // But only in the root. This matches gcc's behaviour and what the
01267     // runtime expects.
01268     if (!Method && !ClassDecl->getSuperClass()) {
01269       Method = ClassDecl->lookupInstanceMethod(Sel);
01270       // Look through local category implementations associated
01271       // with the root class.
01272       if (!Method)
01273         Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
01274     }
01275 
01276     ClassDecl = ClassDecl->getSuperClass();
01277   }
01278   return Method;
01279 }
01280 
01281 ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
01282                                               ObjCInterfaceDecl *ClassDecl) {
01283   if (!ClassDecl->hasDefinition())
01284     return 0;
01285 
01286   ObjCMethodDecl *Method = 0;
01287   while (ClassDecl && !Method) {
01288     // If we have implementations in scope, check "private" methods.
01289     if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
01290       Method = ImpDecl->getInstanceMethod(Sel);
01291 
01292     // Look through local category implementations associated with the class.
01293     if (!Method)
01294       Method = ClassDecl->getCategoryInstanceMethod(Sel);
01295     ClassDecl = ClassDecl->getSuperClass();
01296   }
01297   return Method;
01298 }
01299 
01300 /// LookupMethodInType - Look up a method in an ObjCObjectType.
01301 ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
01302                                                bool isInstance) {
01303   const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
01304   if (ObjCInterfaceDecl *iface = objType->getInterface()) {
01305     // Look it up in the main interface (and categories, etc.)
01306     if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
01307       return method;
01308 
01309     // Okay, look for "private" methods declared in any
01310     // @implementations we've seen.
01311     if (isInstance) {
01312       if (ObjCMethodDecl *method = LookupPrivateInstanceMethod(sel, iface))
01313         return method;
01314     } else {
01315       if (ObjCMethodDecl *method = LookupPrivateClassMethod(sel, iface))
01316         return method;
01317     }
01318   }
01319 
01320   // Check qualifiers.
01321   for (ObjCObjectType::qual_iterator
01322          i = objType->qual_begin(), e = objType->qual_end(); i != e; ++i)
01323     if (ObjCMethodDecl *method = (*i)->lookupMethod(sel, isInstance))
01324       return method;
01325 
01326   return 0;
01327 }
01328 
01329 /// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier 
01330 /// list of a qualified objective pointer type.
01331 ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
01332                                               const ObjCObjectPointerType *OPT,
01333                                               bool Instance)
01334 {
01335   ObjCMethodDecl *MD = 0;
01336   for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
01337        E = OPT->qual_end(); I != E; ++I) {
01338     ObjCProtocolDecl *PROTO = (*I);
01339     if ((MD = PROTO->lookupMethod(Sel, Instance))) {
01340       return MD;
01341     }
01342   }
01343   return 0;
01344 }
01345 
01346 static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) {
01347   if (!Receiver)
01348     return;
01349   
01350   Expr *RExpr = Receiver->IgnoreParenImpCasts();
01351   SourceLocation Loc = RExpr->getLocStart();
01352   QualType T = RExpr->getType();
01353   ObjCPropertyDecl *PDecl = 0;
01354   ObjCMethodDecl *GDecl = 0;
01355   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) {
01356     RExpr = POE->getSyntacticForm();
01357     if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) {
01358       if (PRE->isImplicitProperty()) {
01359         GDecl = PRE->getImplicitPropertyGetter();
01360         if (GDecl) {
01361           T = GDecl->getResultType();
01362         }
01363       }
01364       else {
01365         PDecl = PRE->getExplicitProperty();
01366         if (PDecl) {
01367           T = PDecl->getType();
01368         }
01369       }
01370     }
01371   }
01372   
01373   if (T.getObjCLifetime() == Qualifiers::OCL_Weak) {
01374     S.Diag(Loc, diag::warn_receiver_is_weak) 
01375       << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2));
01376     if (PDecl)
01377       S.Diag(PDecl->getLocation(), diag::note_property_declare);
01378     else if (GDecl)
01379       S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl;
01380     return;
01381   }
01382   
01383   if (PDecl && 
01384       (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)) {
01385     S.Diag(Loc, diag::warn_receiver_is_weak) << 1;
01386     S.Diag(PDecl->getLocation(), diag::note_property_declare);
01387   }
01388 }
01389 
01390 /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
01391 /// objective C interface.  This is a property reference expression.
01392 ExprResult Sema::
01393 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
01394                           Expr *BaseExpr, SourceLocation OpLoc,
01395                           DeclarationName MemberName,
01396                           SourceLocation MemberLoc,
01397                           SourceLocation SuperLoc, QualType SuperType,
01398                           bool Super) {
01399   const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
01400   ObjCInterfaceDecl *IFace = IFaceT->getDecl();
01401 
01402   if (!MemberName.isIdentifier()) {
01403     Diag(MemberLoc, diag::err_invalid_property_name)
01404       << MemberName << QualType(OPT, 0);
01405     return ExprError();
01406   }
01407 
01408   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
01409   
01410   SourceRange BaseRange = Super? SourceRange(SuperLoc)
01411                                : BaseExpr->getSourceRange();
01412   if (RequireCompleteType(MemberLoc, OPT->getPointeeType(), 
01413                           diag::err_property_not_found_forward_class,
01414                           MemberName, BaseRange))
01415     return ExprError();
01416   
01417   // Search for a declared property first.
01418   if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
01419     // Check whether we can reference this property.
01420     if (DiagnoseUseOfDecl(PD, MemberLoc))
01421       return ExprError();
01422     if (Super)
01423       return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
01424                                                      VK_LValue, OK_ObjCProperty,
01425                                                      MemberLoc, 
01426                                                      SuperLoc, SuperType));
01427     else
01428       return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
01429                                                      VK_LValue, OK_ObjCProperty,
01430                                                      MemberLoc, BaseExpr));
01431   }
01432   // Check protocols on qualified interfaces.
01433   for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
01434        E = OPT->qual_end(); I != E; ++I)
01435     if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
01436       // Check whether we can reference this property.
01437       if (DiagnoseUseOfDecl(PD, MemberLoc))
01438         return ExprError();
01439 
01440       if (Super)
01441         return Owned(new (Context) ObjCPropertyRefExpr(PD,
01442                                                        Context.PseudoObjectTy,
01443                                                        VK_LValue,
01444                                                        OK_ObjCProperty,
01445                                                        MemberLoc, 
01446                                                        SuperLoc, SuperType));
01447       else
01448         return Owned(new (Context) ObjCPropertyRefExpr(PD,
01449                                                        Context.PseudoObjectTy,
01450                                                        VK_LValue,
01451                                                        OK_ObjCProperty,
01452                                                        MemberLoc,
01453                                                        BaseExpr));
01454     }
01455   // If that failed, look for an "implicit" property by seeing if the nullary
01456   // selector is implemented.
01457 
01458   // FIXME: The logic for looking up nullary and unary selectors should be
01459   // shared with the code in ActOnInstanceMessage.
01460 
01461   Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
01462   ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
01463   
01464   // May be founf in property's qualified list.
01465   if (!Getter)
01466     Getter = LookupMethodInQualifiedType(Sel, OPT, true);
01467 
01468   // If this reference is in an @implementation, check for 'private' methods.
01469   if (!Getter)
01470     Getter = IFace->lookupPrivateMethod(Sel);
01471 
01472   // Look through local category implementations associated with the class.
01473   if (!Getter)
01474     Getter = IFace->getCategoryInstanceMethod(Sel);
01475   if (Getter) {
01476     // Check if we can reference this property.
01477     if (DiagnoseUseOfDecl(Getter, MemberLoc))
01478       return ExprError();
01479   }
01480   // If we found a getter then this may be a valid dot-reference, we
01481   // will look for the matching setter, in case it is needed.
01482   Selector SetterSel =
01483     SelectorTable::constructSetterName(PP.getIdentifierTable(),
01484                                        PP.getSelectorTable(), Member);
01485   ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
01486   
01487   // May be founf in property's qualified list.
01488   if (!Setter)
01489     Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
01490   
01491   if (!Setter) {
01492     // If this reference is in an @implementation, also check for 'private'
01493     // methods.
01494     Setter = IFace->lookupPrivateMethod(SetterSel);
01495   }
01496   // Look through local category implementations associated with the class.
01497   if (!Setter)
01498     Setter = IFace->getCategoryInstanceMethod(SetterSel);
01499     
01500   if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
01501     return ExprError();
01502 
01503   if (Getter || Setter) {
01504     if (Super)
01505       return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
01506                                                      Context.PseudoObjectTy,
01507                                                      VK_LValue, OK_ObjCProperty,
01508                                                      MemberLoc,
01509                                                      SuperLoc, SuperType));
01510     else
01511       return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
01512                                                      Context.PseudoObjectTy,
01513                                                      VK_LValue, OK_ObjCProperty,
01514                                                      MemberLoc, BaseExpr));
01515 
01516   }
01517 
01518   // Attempt to correct for typos in property names.
01519   DeclFilterCCC<ObjCPropertyDecl> Validator;
01520   if (TypoCorrection Corrected = CorrectTypo(
01521       DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
01522       NULL, Validator, IFace, false, OPT)) {
01523     ObjCPropertyDecl *Property =
01524         Corrected.getCorrectionDeclAs<ObjCPropertyDecl>();
01525     DeclarationName TypoResult = Corrected.getCorrection();
01526     Diag(MemberLoc, diag::err_property_not_found_suggest)
01527       << MemberName << QualType(OPT, 0) << TypoResult
01528       << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
01529     Diag(Property->getLocation(), diag::note_previous_decl)
01530       << Property->getDeclName();
01531     return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
01532                                      TypoResult, MemberLoc,
01533                                      SuperLoc, SuperType, Super);
01534   }
01535   ObjCInterfaceDecl *ClassDeclared;
01536   if (ObjCIvarDecl *Ivar = 
01537       IFace->lookupInstanceVariable(Member, ClassDeclared)) {
01538     QualType T = Ivar->getType();
01539     if (const ObjCObjectPointerType * OBJPT = 
01540         T->getAsObjCInterfacePointerType()) {
01541       if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(), 
01542                               diag::err_property_not_as_forward_class,
01543                               MemberName, BaseExpr))
01544         return ExprError();
01545     }
01546     Diag(MemberLoc, 
01547          diag::err_ivar_access_using_property_syntax_suggest)
01548     << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
01549     << FixItHint::CreateReplacement(OpLoc, "->");
01550     return ExprError();
01551   }
01552   
01553   Diag(MemberLoc, diag::err_property_not_found)
01554     << MemberName << QualType(OPT, 0);
01555   if (Setter)
01556     Diag(Setter->getLocation(), diag::note_getter_unavailable)
01557           << MemberName << BaseExpr->getSourceRange();
01558   return ExprError();
01559 }
01560 
01561 
01562 
01563 ExprResult Sema::
01564 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
01565                           IdentifierInfo &propertyName,
01566                           SourceLocation receiverNameLoc,
01567                           SourceLocation propertyNameLoc) {
01568 
01569   IdentifierInfo *receiverNamePtr = &receiverName;
01570   ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
01571                                                   receiverNameLoc);
01572 
01573   bool IsSuper = false;
01574   if (IFace == 0) {
01575     // If the "receiver" is 'super' in a method, handle it as an expression-like
01576     // property reference.
01577     if (receiverNamePtr->isStr("super")) {
01578       IsSuper = true;
01579 
01580       if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
01581         if (CurMethod->isInstanceMethod()) {
01582           QualType T = 
01583             Context.getObjCInterfaceType(CurMethod->getClassInterface());
01584           T = Context.getObjCObjectPointerType(T);
01585         
01586           return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
01587                                            /*BaseExpr*/0, 
01588                                            SourceLocation()/*OpLoc*/, 
01589                                            &propertyName,
01590                                            propertyNameLoc,
01591                                            receiverNameLoc, T, true);
01592         }
01593 
01594         // Otherwise, if this is a class method, try dispatching to our
01595         // superclass.
01596         IFace = CurMethod->getClassInterface()->getSuperClass();
01597       }
01598     }
01599     
01600     if (IFace == 0) {
01601       Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
01602       return ExprError();
01603     }
01604   }
01605 
01606   // Search for a declared property first.
01607   Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
01608   ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
01609 
01610   // If this reference is in an @implementation, check for 'private' methods.
01611   if (!Getter)
01612     if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
01613       if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
01614         if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
01615           Getter = ImpDecl->getClassMethod(Sel);
01616 
01617   if (Getter) {
01618     // FIXME: refactor/share with ActOnMemberReference().
01619     // Check if we can reference this property.
01620     if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
01621       return ExprError();
01622   }
01623 
01624   // Look for the matching setter, in case it is needed.
01625   Selector SetterSel =
01626     SelectorTable::constructSetterName(PP.getIdentifierTable(),
01627                                        PP.getSelectorTable(), &propertyName);
01628 
01629   ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
01630   if (!Setter) {
01631     // If this reference is in an @implementation, also check for 'private'
01632     // methods.
01633     if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
01634       if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
01635         if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
01636           Setter = ImpDecl->getClassMethod(SetterSel);
01637   }
01638   // Look through local category implementations associated with the class.
01639   if (!Setter)
01640     Setter = IFace->getCategoryClassMethod(SetterSel);
01641 
01642   if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
01643     return ExprError();
01644 
01645   if (Getter || Setter) {
01646     if (IsSuper)
01647     return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
01648                                                    Context.PseudoObjectTy,
01649                                                    VK_LValue, OK_ObjCProperty,
01650                                                    propertyNameLoc,
01651                                                    receiverNameLoc, 
01652                                           Context.getObjCInterfaceType(IFace)));
01653 
01654     return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
01655                                                    Context.PseudoObjectTy,
01656                                                    VK_LValue, OK_ObjCProperty,
01657                                                    propertyNameLoc,
01658                                                    receiverNameLoc, IFace));
01659   }
01660   return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
01661                      << &propertyName << Context.getObjCInterfaceType(IFace));
01662 }
01663 
01664 namespace {
01665 
01666 class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
01667  public:
01668   ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
01669     // Determine whether "super" is acceptable in the current context.
01670     if (Method && Method->getClassInterface())
01671       WantObjCSuper = Method->getClassInterface()->getSuperClass();
01672   }
01673 
01674   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
01675     return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
01676         candidate.isKeyword("super");
01677   }
01678 };
01679 
01680 }
01681 
01682 Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
01683                                                IdentifierInfo *Name,
01684                                                SourceLocation NameLoc,
01685                                                bool IsSuper,
01686                                                bool HasTrailingDot,
01687                                                ParsedType &ReceiverType) {
01688   ReceiverType = ParsedType();
01689 
01690   // If the identifier is "super" and there is no trailing dot, we're
01691   // messaging super. If the identifier is "super" and there is a
01692   // trailing dot, it's an instance message.
01693   if (IsSuper && S->isInObjcMethodScope())
01694     return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
01695   
01696   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
01697   LookupName(Result, S);
01698   
01699   switch (Result.getResultKind()) {
01700   case LookupResult::NotFound:
01701     // Normal name lookup didn't find anything. If we're in an
01702     // Objective-C method, look for ivars. If we find one, we're done!
01703     // FIXME: This is a hack. Ivar lookup should be part of normal
01704     // lookup.
01705     if (ObjCMethodDecl *Method = getCurMethodDecl()) {
01706       if (!Method->getClassInterface()) {
01707         // Fall back: let the parser try to parse it as an instance message.
01708         return ObjCInstanceMessage;
01709       }
01710 
01711       ObjCInterfaceDecl *ClassDeclared;
01712       if (Method->getClassInterface()->lookupInstanceVariable(Name, 
01713                                                               ClassDeclared))
01714         return ObjCInstanceMessage;
01715     }
01716   
01717     // Break out; we'll perform typo correction below.
01718     break;
01719 
01720   case LookupResult::NotFoundInCurrentInstantiation:
01721   case LookupResult::FoundOverloaded:
01722   case LookupResult::FoundUnresolvedValue:
01723   case LookupResult::Ambiguous:
01724     Result.suppressDiagnostics();
01725     return ObjCInstanceMessage;
01726 
01727   case LookupResult::Found: {
01728     // If the identifier is a class or not, and there is a trailing dot,
01729     // it's an instance message.
01730     if (HasTrailingDot)
01731       return ObjCInstanceMessage;
01732     // We found something. If it's a type, then we have a class
01733     // message. Otherwise, it's an instance message.
01734     NamedDecl *ND = Result.getFoundDecl();
01735     QualType T;
01736     if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
01737       T = Context.getObjCInterfaceType(Class);
01738     else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
01739       T = Context.getTypeDeclType(Type);
01740     else 
01741       return ObjCInstanceMessage;
01742 
01743     //  We have a class message, and T is the type we're
01744     //  messaging. Build source-location information for it.
01745     TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
01746     ReceiverType = CreateParsedType(T, TSInfo);
01747     return ObjCClassMessage;
01748   }
01749   }
01750 
01751   ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
01752   if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
01753                                              Result.getLookupKind(), S, NULL,
01754                                              Validator)) {
01755     if (Corrected.isKeyword()) {
01756       // If we've found the keyword "super" (the only keyword that would be
01757       // returned by CorrectTypo), this is a send to super.
01758       Diag(NameLoc, diag::err_unknown_receiver_suggest)
01759         << Name << Corrected.getCorrection()
01760         << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
01761       return ObjCSuperMessage;
01762     } else if (ObjCInterfaceDecl *Class =
01763                Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
01764       // If we found a declaration, correct when it refers to an Objective-C
01765       // class.
01766       Diag(NameLoc, diag::err_unknown_receiver_suggest)
01767         << Name << Corrected.getCorrection()
01768         << FixItHint::CreateReplacement(SourceRange(NameLoc),
01769                                         Class->getNameAsString());
01770       Diag(Class->getLocation(), diag::note_previous_decl)
01771         << Corrected.getCorrection();
01772 
01773       QualType T = Context.getObjCInterfaceType(Class);
01774       TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
01775       ReceiverType = CreateParsedType(T, TSInfo);
01776       return ObjCClassMessage;
01777     }
01778   }
01779   
01780   // Fall back: let the parser try to parse it as an instance message.
01781   return ObjCInstanceMessage;
01782 }
01783 
01784 ExprResult Sema::ActOnSuperMessage(Scope *S, 
01785                                    SourceLocation SuperLoc,
01786                                    Selector Sel,
01787                                    SourceLocation LBracLoc,
01788                                    ArrayRef<SourceLocation> SelectorLocs,
01789                                    SourceLocation RBracLoc,
01790                                    MultiExprArg Args) {
01791   // Determine whether we are inside a method or not.
01792   ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
01793   if (!Method) {
01794     Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
01795     return ExprError();
01796   }
01797 
01798   ObjCInterfaceDecl *Class = Method->getClassInterface();
01799   if (!Class) {
01800     Diag(SuperLoc, diag::error_no_super_class_message)
01801       << Method->getDeclName();
01802     return ExprError();
01803   }
01804 
01805   ObjCInterfaceDecl *Super = Class->getSuperClass();
01806   if (!Super) {
01807     // The current class does not have a superclass.
01808     Diag(SuperLoc, diag::error_root_class_cannot_use_super)
01809       << Class->getIdentifier();
01810     return ExprError();
01811   }
01812 
01813   // We are in a method whose class has a superclass, so 'super'
01814   // is acting as a keyword.
01815   if (Method->isInstanceMethod()) {
01816     if (Sel.getMethodFamily() == OMF_dealloc)
01817       ObjCShouldCallSuperDealloc = false;
01818     if (Sel.getMethodFamily() == OMF_finalize)
01819       ObjCShouldCallSuperFinalize = false;
01820 
01821     // Since we are in an instance method, this is an instance
01822     // message to the superclass instance.
01823     QualType SuperTy = Context.getObjCInterfaceType(Super);
01824     SuperTy = Context.getObjCObjectPointerType(SuperTy);
01825     return BuildInstanceMessage(0, SuperTy, SuperLoc,
01826                                 Sel, /*Method=*/0,
01827                                 LBracLoc, SelectorLocs, RBracLoc, move(Args));
01828   }
01829   
01830   // Since we are in a class method, this is a class message to
01831   // the superclass.
01832   return BuildClassMessage(/*ReceiverTypeInfo=*/0,
01833                            Context.getObjCInterfaceType(Super),
01834                            SuperLoc, Sel, /*Method=*/0,
01835                            LBracLoc, SelectorLocs, RBracLoc, move(Args));
01836 }
01837 
01838 
01839 ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
01840                                            bool isSuperReceiver,
01841                                            SourceLocation Loc,
01842                                            Selector Sel,
01843                                            ObjCMethodDecl *Method,
01844                                            MultiExprArg Args) {
01845   TypeSourceInfo *receiverTypeInfo = 0;
01846   if (!ReceiverType.isNull())
01847     receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
01848 
01849   return BuildClassMessage(receiverTypeInfo, ReceiverType,
01850                           /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
01851                            Sel, Method, Loc, Loc, Loc, Args,
01852                            /*isImplicit=*/true);
01853 
01854 }
01855 
01856 static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
01857                                unsigned DiagID,
01858                                bool (*refactor)(const ObjCMessageExpr *,
01859                                               const NSAPI &, edit::Commit &)) {
01860   SourceLocation MsgLoc = Msg->getExprLoc();
01861   if (S.Diags.getDiagnosticLevel(DiagID, MsgLoc) == DiagnosticsEngine::Ignored)
01862     return;
01863 
01864   SourceManager &SM = S.SourceMgr;
01865   edit::Commit ECommit(SM, S.LangOpts);
01866   if (refactor(Msg,*S.NSAPIObj, ECommit)) {
01867     DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
01868                         << Msg->getSelector() << Msg->getSourceRange();
01869     // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
01870     if (!ECommit.isCommitable())
01871       return;
01872     for (edit::Commit::edit_iterator
01873            I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
01874       const edit::Commit::Edit &Edit = *I;
01875       switch (Edit.Kind) {
01876       case edit::Commit::Act_Insert:
01877         Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
01878                                                         Edit.Text,
01879                                                         Edit.BeforePrev));
01880         break;
01881       case edit::Commit::Act_InsertFromRange:
01882         Builder.AddFixItHint(
01883             FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
01884                                                 Edit.getInsertFromRange(SM),
01885                                                 Edit.BeforePrev));
01886         break;
01887       case edit::Commit::Act_Remove:
01888         Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
01889         break;
01890       }
01891     }
01892   }
01893 }
01894 
01895 static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
01896   applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
01897                      edit::rewriteObjCRedundantCallWithLiteral);
01898 }
01899 
01900 /// \brief Build an Objective-C class message expression.
01901 ///
01902 /// This routine takes care of both normal class messages and
01903 /// class messages to the superclass.
01904 ///
01905 /// \param ReceiverTypeInfo Type source information that describes the
01906 /// receiver of this message. This may be NULL, in which case we are
01907 /// sending to the superclass and \p SuperLoc must be a valid source
01908 /// location.
01909 
01910 /// \param ReceiverType The type of the object receiving the
01911 /// message. When \p ReceiverTypeInfo is non-NULL, this is the same
01912 /// type as that refers to. For a superclass send, this is the type of
01913 /// the superclass.
01914 ///
01915 /// \param SuperLoc The location of the "super" keyword in a
01916 /// superclass message.
01917 ///
01918 /// \param Sel The selector to which the message is being sent.
01919 ///
01920 /// \param Method The method that this class message is invoking, if
01921 /// already known.
01922 ///
01923 /// \param LBracLoc The location of the opening square bracket ']'.
01924 ///
01925 /// \param RBrac The location of the closing square bracket ']'.
01926 ///
01927 /// \param Args The message arguments.
01928 ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
01929                                    QualType ReceiverType,
01930                                    SourceLocation SuperLoc,
01931                                    Selector Sel,
01932                                    ObjCMethodDecl *Method,
01933                                    SourceLocation LBracLoc, 
01934                                    ArrayRef<SourceLocation> SelectorLocs,
01935                                    SourceLocation RBracLoc,
01936                                    MultiExprArg ArgsIn,
01937                                    bool isImplicit) {
01938   SourceLocation Loc = SuperLoc.isValid()? SuperLoc
01939     : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
01940   if (LBracLoc.isInvalid()) {
01941     Diag(Loc, diag::err_missing_open_square_message_send)
01942       << FixItHint::CreateInsertion(Loc, "[");
01943     LBracLoc = Loc;
01944   }
01945   
01946   if (ReceiverType->isDependentType()) {
01947     // If the receiver type is dependent, we can't type-check anything
01948     // at this point. Build a dependent expression.
01949     unsigned NumArgs = ArgsIn.size();
01950     Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
01951     assert(SuperLoc.isInvalid() && "Message to super with dependent type");
01952     return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
01953                                          VK_RValue, LBracLoc, ReceiverTypeInfo,
01954                                          Sel, SelectorLocs, /*Method=*/0,
01955                                          makeArrayRef(Args, NumArgs),RBracLoc,
01956                                          isImplicit));
01957   }
01958   
01959   // Find the class to which we are sending this message.
01960   ObjCInterfaceDecl *Class = 0;
01961   const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
01962   if (!ClassType || !(Class = ClassType->getInterface())) {
01963     Diag(Loc, diag::err_invalid_receiver_class_message)
01964       << ReceiverType;
01965     return ExprError();
01966   }
01967   assert(Class && "We don't know which class we're messaging?");
01968   // objc++ diagnoses during typename annotation.
01969   if (!getLangOpts().CPlusPlus)
01970     (void)DiagnoseUseOfDecl(Class, Loc);
01971   // Find the method we are messaging.
01972   if (!Method) {
01973     SourceRange TypeRange 
01974       = SuperLoc.isValid()? SourceRange(SuperLoc)
01975                           : ReceiverTypeInfo->getTypeLoc().getSourceRange();
01976     if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
01977                             (getLangOpts().ObjCAutoRefCount
01978                                ? diag::err_arc_receiver_forward_class
01979                                : diag::warn_receiver_forward_class),
01980                             TypeRange)) {
01981       // A forward class used in messaging is treated as a 'Class'
01982       Method = LookupFactoryMethodInGlobalPool(Sel, 
01983                                                SourceRange(LBracLoc, RBracLoc));
01984       if (Method && !getLangOpts().ObjCAutoRefCount)
01985         Diag(Method->getLocation(), diag::note_method_sent_forward_class)
01986           << Method->getDeclName();
01987     }
01988     if (!Method)
01989       Method = Class->lookupClassMethod(Sel);
01990 
01991     // If we have an implementation in scope, check "private" methods.
01992     if (!Method)
01993       Method = LookupPrivateClassMethod(Sel, Class);
01994 
01995     if (Method && DiagnoseUseOfDecl(Method, Loc))
01996       return ExprError();
01997   }
01998 
01999   // Check the argument types and determine the result type.
02000   QualType ReturnType;
02001   ExprValueKind VK = VK_RValue;
02002 
02003   unsigned NumArgs = ArgsIn.size();
02004   Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
02005   if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
02006                                 SuperLoc.isValid(), LBracLoc, RBracLoc, 
02007                                 ReturnType, VK))
02008     return ExprError();
02009 
02010   if (Method && !Method->getResultType()->isVoidType() &&
02011       RequireCompleteType(LBracLoc, Method->getResultType(), 
02012                           diag::err_illegal_message_expr_incomplete_type))
02013     return ExprError();
02014 
02015   // Construct the appropriate ObjCMessageExpr.
02016   ObjCMessageExpr *Result;
02017   if (SuperLoc.isValid())
02018     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, 
02019                                      SuperLoc, /*IsInstanceSuper=*/false, 
02020                                      ReceiverType, Sel, SelectorLocs,
02021                                      Method, makeArrayRef(Args, NumArgs),
02022                                      RBracLoc, isImplicit);
02023   else {
02024     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, 
02025                                      ReceiverTypeInfo, Sel, SelectorLocs,
02026                                      Method, makeArrayRef(Args, NumArgs),
02027                                      RBracLoc, isImplicit);
02028     if (!isImplicit)
02029       checkCocoaAPI(*this, Result);
02030   }
02031   return MaybeBindToTemporary(Result);
02032 }
02033 
02034 // ActOnClassMessage - used for both unary and keyword messages.
02035 // ArgExprs is optional - if it is present, the number of expressions
02036 // is obtained from Sel.getNumArgs().
02037 ExprResult Sema::ActOnClassMessage(Scope *S, 
02038                                    ParsedType Receiver,
02039                                    Selector Sel,
02040                                    SourceLocation LBracLoc,
02041                                    ArrayRef<SourceLocation> SelectorLocs,
02042                                    SourceLocation RBracLoc,
02043                                    MultiExprArg Args) {
02044   TypeSourceInfo *ReceiverTypeInfo;
02045   QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
02046   if (ReceiverType.isNull())
02047     return ExprError();
02048 
02049 
02050   if (!ReceiverTypeInfo)
02051     ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
02052 
02053   return BuildClassMessage(ReceiverTypeInfo, ReceiverType, 
02054                            /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
02055                            LBracLoc, SelectorLocs, RBracLoc, move(Args));
02056 }
02057 
02058 ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
02059                                               QualType ReceiverType,
02060                                               SourceLocation Loc,
02061                                               Selector Sel,
02062                                               ObjCMethodDecl *Method,
02063                                               MultiExprArg Args) {
02064   return BuildInstanceMessage(Receiver, ReceiverType,
02065                               /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
02066                               Sel, Method, Loc, Loc, Loc, Args,
02067                               /*isImplicit=*/true);
02068 }
02069 
02070 /// \brief Build an Objective-C instance message expression.
02071 ///
02072 /// This routine takes care of both normal instance messages and
02073 /// instance messages to the superclass instance.
02074 ///
02075 /// \param Receiver The expression that computes the object that will
02076 /// receive this message. This may be empty, in which case we are
02077 /// sending to the superclass instance and \p SuperLoc must be a valid
02078 /// source location.
02079 ///
02080 /// \param ReceiverType The (static) type of the object receiving the
02081 /// message. When a \p Receiver expression is provided, this is the
02082 /// same type as that expression. For a superclass instance send, this
02083 /// is a pointer to the type of the superclass.
02084 ///
02085 /// \param SuperLoc The location of the "super" keyword in a
02086 /// superclass instance message.
02087 ///
02088 /// \param Sel The selector to which the message is being sent.
02089 ///
02090 /// \param Method The method that this instance message is invoking, if
02091 /// already known.
02092 ///
02093 /// \param LBracLoc The location of the opening square bracket ']'.
02094 ///
02095 /// \param RBrac The location of the closing square bracket ']'.
02096 ///
02097 /// \param Args The message arguments.
02098 ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
02099                                       QualType ReceiverType,
02100                                       SourceLocation SuperLoc,
02101                                       Selector Sel,
02102                                       ObjCMethodDecl *Method,
02103                                       SourceLocation LBracLoc, 
02104                                       ArrayRef<SourceLocation> SelectorLocs,
02105                                       SourceLocation RBracLoc,
02106                                       MultiExprArg ArgsIn,
02107                                       bool isImplicit) {
02108   // The location of the receiver.
02109   SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
02110   
02111   if (LBracLoc.isInvalid()) {
02112     Diag(Loc, diag::err_missing_open_square_message_send)
02113       << FixItHint::CreateInsertion(Loc, "[");
02114     LBracLoc = Loc;
02115   }
02116 
02117   // If we have a receiver expression, perform appropriate promotions
02118   // and determine receiver type.
02119   if (Receiver) {
02120     if (Receiver->hasPlaceholderType()) {
02121       ExprResult Result;
02122       if (Receiver->getType() == Context.UnknownAnyTy)
02123         Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
02124       else
02125         Result = CheckPlaceholderExpr(Receiver);
02126       if (Result.isInvalid()) return ExprError();
02127       Receiver = Result.take();
02128     }
02129 
02130     if (Receiver->isTypeDependent()) {
02131       // If the receiver is type-dependent, we can't type-check anything
02132       // at this point. Build a dependent expression.
02133       unsigned NumArgs = ArgsIn.size();
02134       Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
02135       assert(SuperLoc.isInvalid() && "Message to super with dependent type");
02136       return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
02137                                            VK_RValue, LBracLoc, Receiver, Sel, 
02138                                            SelectorLocs, /*Method=*/0,
02139                                            makeArrayRef(Args, NumArgs),
02140                                            RBracLoc, isImplicit));
02141     }
02142 
02143     // If necessary, apply function/array conversion to the receiver.
02144     // C99 6.7.5.3p[7,8].
02145     ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
02146     if (Result.isInvalid())
02147       return ExprError();
02148     Receiver = Result.take();
02149     ReceiverType = Receiver->getType();
02150   }
02151 
02152   if (!Method) {
02153     // Handle messages to id.
02154     bool receiverIsId = ReceiverType->isObjCIdType();
02155     if (receiverIsId || ReceiverType->isBlockPointerType() ||
02156         (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
02157       Method = LookupInstanceMethodInGlobalPool(Sel, 
02158                                                 SourceRange(LBracLoc, RBracLoc),
02159                                                 receiverIsId);
02160       if (!Method)
02161         Method = LookupFactoryMethodInGlobalPool(Sel, 
02162                                                  SourceRange(LBracLoc,RBracLoc),
02163                                                  receiverIsId);
02164     } else if (ReceiverType->isObjCClassType() ||
02165                ReceiverType->isObjCQualifiedClassType()) {
02166       // Handle messages to Class.
02167       // We allow sending a message to a qualified Class ("Class<foo>"), which 
02168       // is ok as long as one of the protocols implements the selector (if not, warn).
02169       if (const ObjCObjectPointerType *QClassTy 
02170             = ReceiverType->getAsObjCQualifiedClassType()) {
02171         // Search protocols for class methods.
02172         Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
02173         if (!Method) {
02174           Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
02175           // warn if instance method found for a Class message.
02176           if (Method) {
02177             Diag(Loc, diag::warn_instance_method_on_class_found)
02178               << Method->getSelector() << Sel;
02179             Diag(Method->getLocation(), diag::note_method_declared_at)
02180               << Method->getDeclName();
02181           }
02182         }
02183       } else {
02184         if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
02185           if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
02186             // First check the public methods in the class interface.
02187             Method = ClassDecl->lookupClassMethod(Sel);
02188 
02189             if (!Method)
02190               Method = LookupPrivateClassMethod(Sel, ClassDecl);
02191           }
02192           if (Method && DiagnoseUseOfDecl(Method, Loc))
02193             return ExprError();
02194         }
02195         if (!Method) {
02196           // If not messaging 'self', look for any factory method named 'Sel'.
02197           if (!Receiver || !isSelfExpr(Receiver)) {
02198             Method = LookupFactoryMethodInGlobalPool(Sel, 
02199                                                 SourceRange(LBracLoc, RBracLoc),
02200                                                      true);
02201             if (!Method) {
02202               // If no class (factory) method was found, check if an _instance_
02203               // method of the same name exists in the root class only.
02204               Method = LookupInstanceMethodInGlobalPool(Sel,
02205                                                SourceRange(LBracLoc, RBracLoc),
02206                                                         true);
02207               if (Method)
02208                   if (const ObjCInterfaceDecl *ID =
02209                       dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
02210                     if (ID->getSuperClass())
02211                       Diag(Loc, diag::warn_root_inst_method_not_found)
02212                       << Sel << SourceRange(LBracLoc, RBracLoc);
02213                   }
02214             }
02215           }
02216         }
02217       }
02218     } else {
02219       ObjCInterfaceDecl* ClassDecl = 0;
02220 
02221       // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
02222       // long as one of the protocols implements the selector (if not, warn).
02223       if (const ObjCObjectPointerType *QIdTy 
02224                                    = ReceiverType->getAsObjCQualifiedIdType()) {
02225         // Search protocols for instance methods.
02226         Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
02227         if (!Method)
02228           Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
02229       } else if (const ObjCObjectPointerType *OCIType
02230                    = ReceiverType->getAsObjCInterfacePointerType()) {
02231         // We allow sending a message to a pointer to an interface (an object).
02232         ClassDecl = OCIType->getInterfaceDecl();
02233 
02234         // Try to complete the type. Under ARC, this is a hard error from which
02235         // we don't try to recover.
02236         const ObjCInterfaceDecl *forwardClass = 0;
02237         if (RequireCompleteType(Loc, OCIType->getPointeeType(),
02238               getLangOpts().ObjCAutoRefCount
02239                 ? diag::err_arc_receiver_forward_instance
02240                 : diag::warn_receiver_forward_instance,
02241                                 Receiver? Receiver->getSourceRange()
02242                                         : SourceRange(SuperLoc))) {
02243           if (getLangOpts().ObjCAutoRefCount)
02244             return ExprError();
02245           
02246           forwardClass = OCIType->getInterfaceDecl();
02247           Diag(Receiver ? Receiver->getLocStart() 
02248                         : SuperLoc, diag::note_receiver_is_id);
02249           Method = 0;
02250         } else {
02251           Method = ClassDecl->lookupInstanceMethod(Sel);
02252         }
02253 
02254         if (!Method)
02255           // Search protocol qualifiers.
02256           Method = LookupMethodInQualifiedType(Sel, OCIType, true);
02257         
02258         if (!Method) {
02259           // If we have implementations in scope, check "private" methods.
02260           Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
02261 
02262           if (!Method && getLangOpts().ObjCAutoRefCount) {
02263             Diag(Loc, diag::err_arc_may_not_respond)
02264               << OCIType->getPointeeType() << Sel;
02265             return ExprError();
02266           }
02267 
02268           if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
02269             // If we still haven't found a method, look in the global pool. This
02270             // behavior isn't very desirable, however we need it for GCC
02271             // compatibility. FIXME: should we deviate??
02272             if (OCIType->qual_empty()) {
02273               Method = LookupInstanceMethodInGlobalPool(Sel,
02274                                               SourceRange(LBracLoc, RBracLoc));
02275               if (Method && !forwardClass)
02276                 Diag(Loc, diag::warn_maynot_respond)
02277                   << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
02278             }
02279           }
02280         }
02281         if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
02282           return ExprError();
02283       } else if (!getLangOpts().ObjCAutoRefCount &&
02284                  !Context.getObjCIdType().isNull() &&
02285                  (ReceiverType->isPointerType() || 
02286                   ReceiverType->isIntegerType())) {
02287         // Implicitly convert integers and pointers to 'id' but emit a warning.
02288         // But not in ARC.
02289         Diag(Loc, diag::warn_bad_receiver_type)
02290           << ReceiverType 
02291           << Receiver->getSourceRange();
02292         if (ReceiverType->isPointerType())
02293           Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(), 
02294                             CK_CPointerToObjCPointerCast).take();
02295         else {
02296           // TODO: specialized warning on null receivers?
02297           bool IsNull = Receiver->isNullPointerConstant(Context,
02298                                               Expr::NPC_ValueDependentIsNull);
02299           CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
02300           Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
02301                                        Kind).take();
02302         }
02303         ReceiverType = Receiver->getType();
02304       } else {
02305         ExprResult ReceiverRes;
02306         if (getLangOpts().CPlusPlus)
02307           ReceiverRes = PerformContextuallyConvertToObjCPointer(Receiver);
02308         if (ReceiverRes.isUsable()) {
02309           Receiver = ReceiverRes.take();
02310           return BuildInstanceMessage(Receiver,
02311                                       ReceiverType,
02312                                       SuperLoc,
02313                                       Sel,
02314                                       Method,
02315                                       LBracLoc,
02316                                       SelectorLocs,
02317                                       RBracLoc,
02318                                       move(ArgsIn));
02319         } else {
02320           // Reject other random receiver types (e.g. structs).
02321           Diag(Loc, diag::err_bad_receiver_type)
02322             << ReceiverType << Receiver->getSourceRange();
02323           return ExprError();
02324         }
02325       }
02326     }
02327   }
02328 
02329   // Check the message arguments.
02330   unsigned NumArgs = ArgsIn.size();
02331   Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
02332   QualType ReturnType;
02333   ExprValueKind VK = VK_RValue;
02334   bool ClassMessage = (ReceiverType->isObjCClassType() ||
02335                        ReceiverType->isObjCQualifiedClassType());
02336   if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, 
02337                                 ClassMessage, SuperLoc.isValid(), 
02338                                 LBracLoc, RBracLoc, ReturnType, VK))
02339     return ExprError();
02340   
02341   if (Method && !Method->getResultType()->isVoidType() &&
02342       RequireCompleteType(LBracLoc, Method->getResultType(), 
02343                           diag::err_illegal_message_expr_incomplete_type))
02344     return ExprError();
02345 
02346   SourceLocation SelLoc = SelectorLocs.front();
02347 
02348   // In ARC, forbid the user from sending messages to 
02349   // retain/release/autorelease/dealloc/retainCount explicitly.
02350   if (getLangOpts().ObjCAutoRefCount) {
02351     ObjCMethodFamily family =
02352       (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
02353     switch (family) {
02354     case OMF_init:
02355       if (Method)
02356         checkInitMethod(Method, ReceiverType);
02357 
02358     case OMF_None:
02359     case OMF_alloc:
02360     case OMF_copy:
02361     case OMF_finalize:
02362     case OMF_mutableCopy:
02363     case OMF_new:
02364     case OMF_self:
02365       break;
02366 
02367     case OMF_dealloc:
02368     case OMF_retain:
02369     case OMF_release:
02370     case OMF_autorelease:
02371     case OMF_retainCount:
02372       Diag(Loc, diag::err_arc_illegal_explicit_message)
02373         << Sel << SelLoc;
02374       break;
02375     
02376     case OMF_performSelector:
02377       if (Method && NumArgs >= 1) {
02378         if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
02379           Selector ArgSel = SelExp->getSelector();
02380           ObjCMethodDecl *SelMethod = 
02381             LookupInstanceMethodInGlobalPool(ArgSel,
02382                                              SelExp->getSourceRange());
02383           if (!SelMethod)
02384             SelMethod =
02385               LookupFactoryMethodInGlobalPool(ArgSel,
02386                                               SelExp->getSourceRange());
02387           if (SelMethod) {
02388             ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
02389             switch (SelFamily) {
02390               case OMF_alloc:
02391               case OMF_copy:
02392               case OMF_mutableCopy:
02393               case OMF_new:
02394               case OMF_self:
02395               case OMF_init:
02396                 // Issue error, unless ns_returns_not_retained.
02397                 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
02398                   // selector names a +1 method 
02399                   Diag(SelLoc, 
02400                        diag::err_arc_perform_selector_retains);
02401                   Diag(SelMethod->getLocation(), diag::note_method_declared_at)
02402                     << SelMethod->getDeclName();
02403                 }
02404                 break;
02405               default:
02406                 // +0 call. OK. unless ns_returns_retained.
02407                 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
02408                   // selector names a +1 method
02409                   Diag(SelLoc, 
02410                        diag::err_arc_perform_selector_retains);
02411                   Diag(SelMethod->getLocation(), diag::note_method_declared_at)
02412                     << SelMethod->getDeclName();
02413                 }
02414                 break;
02415             }
02416           }
02417         } else {
02418           // error (may leak).
02419           Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
02420           Diag(Args[0]->getExprLoc(), diag::note_used_here);
02421         }
02422       }
02423       break;
02424     }
02425   }
02426 
02427   // Construct the appropriate ObjCMessageExpr instance.
02428   ObjCMessageExpr *Result;
02429   if (SuperLoc.isValid())
02430     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
02431                                      SuperLoc,  /*IsInstanceSuper=*/true,
02432                                      ReceiverType, Sel, SelectorLocs, Method, 
02433                                      makeArrayRef(Args, NumArgs), RBracLoc,
02434                                      isImplicit);
02435   else {
02436     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
02437                                      Receiver, Sel, SelectorLocs, Method,
02438                                      makeArrayRef(Args, NumArgs), RBracLoc,
02439                                      isImplicit);
02440     if (!isImplicit)
02441       checkCocoaAPI(*this, Result);
02442   }
02443 
02444   if (getLangOpts().ObjCAutoRefCount) {
02445     DiagnoseARCUseOfWeakReceiver(*this, Receiver);
02446     
02447     // In ARC, annotate delegate init calls.
02448     if (Result->getMethodFamily() == OMF_init &&
02449         (SuperLoc.isValid() || isSelfExpr(Receiver))) {
02450       // Only consider init calls *directly* in init implementations,
02451       // not within blocks.
02452       ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
02453       if (method && method->getMethodFamily() == OMF_init) {
02454         // The implicit assignment to self means we also don't want to
02455         // consume the result.
02456         Result->setDelegateInitCall(true);
02457         return Owned(Result);
02458       }
02459     }
02460 
02461     // In ARC, check for message sends which are likely to introduce
02462     // retain cycles.
02463     checkRetainCycles(Result);
02464   }
02465       
02466   return MaybeBindToTemporary(Result);
02467 }
02468 
02469 // ActOnInstanceMessage - used for both unary and keyword messages.
02470 // ArgExprs is optional - if it is present, the number of expressions
02471 // is obtained from Sel.getNumArgs().
02472 ExprResult Sema::ActOnInstanceMessage(Scope *S,
02473                                       Expr *Receiver, 
02474                                       Selector Sel,
02475                                       SourceLocation LBracLoc,
02476                                       ArrayRef<SourceLocation> SelectorLocs,
02477                                       SourceLocation RBracLoc,
02478                                       MultiExprArg Args) {
02479   if (!Receiver)
02480     return ExprError();
02481 
02482   return BuildInstanceMessage(Receiver, Receiver->getType(),
02483                               /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0, 
02484                               LBracLoc, SelectorLocs, RBracLoc, move(Args));
02485 }
02486 
02487 enum ARCConversionTypeClass {
02488   /// int, void, struct A
02489   ACTC_none,
02490 
02491   /// id, void (^)()
02492   ACTC_retainable,
02493 
02494   /// id*, id***, void (^*)(),
02495   ACTC_indirectRetainable,
02496 
02497   /// void* might be a normal C type, or it might a CF type.
02498   ACTC_voidPtr,
02499 
02500   /// struct A*
02501   ACTC_coreFoundation
02502 };
02503 static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
02504   return (ACTC == ACTC_retainable ||
02505           ACTC == ACTC_coreFoundation ||
02506           ACTC == ACTC_voidPtr);
02507 }
02508 static bool isAnyCLike(ARCConversionTypeClass ACTC) {
02509   return ACTC == ACTC_none ||
02510          ACTC == ACTC_voidPtr ||
02511          ACTC == ACTC_coreFoundation;
02512 }
02513 
02514 static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
02515   bool isIndirect = false;
02516   
02517   // Ignore an outermost reference type.
02518   if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
02519     type = ref->getPointeeType();
02520     isIndirect = true;
02521   }
02522   
02523   // Drill through pointers and arrays recursively.
02524   while (true) {
02525     if (const PointerType *ptr = type->getAs<PointerType>()) {
02526       type = ptr->getPointeeType();
02527 
02528       // The first level of pointer may be the innermost pointer on a CF type.
02529       if (!isIndirect) {
02530         if (type->isVoidType()) return ACTC_voidPtr;
02531         if (type->isRecordType()) return ACTC_coreFoundation;
02532       }
02533     } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
02534       type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
02535     } else {
02536       break;
02537     }
02538     isIndirect = true;
02539   }
02540   
02541   if (isIndirect) {
02542     if (type->isObjCARCBridgableType())
02543       return ACTC_indirectRetainable;
02544     return ACTC_none;
02545   }
02546 
02547   if (type->isObjCARCBridgableType())
02548     return ACTC_retainable;
02549 
02550   return ACTC_none;
02551 }
02552 
02553 namespace {
02554   /// A result from the cast checker.
02555   enum ACCResult {
02556     /// Cannot be casted.
02557     ACC_invalid,
02558 
02559     /// Can be safely retained or not retained.
02560     ACC_bottom,
02561 
02562     /// Can be casted at +0.
02563     ACC_plusZero,
02564 
02565     /// Can be casted at +1.
02566     ACC_plusOne
02567   };
02568   ACCResult merge(ACCResult left, ACCResult right) {
02569     if (left == right) return left;
02570     if (left == ACC_bottom) return right;
02571     if (right == ACC_bottom) return left;
02572     return ACC_invalid;
02573   }
02574 
02575   /// A checker which white-lists certain expressions whose conversion
02576   /// to or from retainable type would otherwise be forbidden in ARC.
02577   class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
02578     typedef StmtVisitor<ARCCastChecker, ACCResult> super;
02579 
02580     ASTContext &Context;
02581     ARCConversionTypeClass SourceClass;
02582     ARCConversionTypeClass TargetClass;
02583 
02584     static bool isCFType(QualType type) {
02585       // Someday this can use ns_bridged.  For now, it has to do this.
02586       return type->isCARCBridgableType();
02587     }
02588 
02589   public:
02590     ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
02591                    ARCConversionTypeClass target)
02592       : Context(Context), SourceClass(source), TargetClass(target) {}
02593 
02594     using super::Visit;
02595     ACCResult Visit(Expr *e) {
02596       return super::Visit(e->IgnoreParens());
02597     }
02598 
02599     ACCResult VisitStmt(Stmt *s) {
02600       return ACC_invalid;
02601     }
02602 
02603     /// Null pointer constants can be casted however you please.
02604     ACCResult VisitExpr(Expr *e) {
02605       if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
02606         return ACC_bottom;
02607       return ACC_invalid;
02608     }
02609 
02610     /// Objective-C string literals can be safely casted.
02611     ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
02612       // If we're casting to any retainable type, go ahead.  Global
02613       // strings are immune to retains, so this is bottom.
02614       if (isAnyRetainable(TargetClass)) return ACC_bottom;
02615 
02616       return ACC_invalid;
02617     }
02618     
02619     /// Look through certain implicit and explicit casts.
02620     ACCResult VisitCastExpr(CastExpr *e) {
02621       switch (e->getCastKind()) {
02622         case CK_NullToPointer:
02623           return ACC_bottom;
02624 
02625         case CK_NoOp:
02626         case CK_LValueToRValue:
02627         case CK_BitCast:
02628         case CK_CPointerToObjCPointerCast:
02629         case CK_BlockPointerToObjCPointerCast:
02630         case CK_AnyPointerToBlockPointerCast:
02631           return Visit(e->getSubExpr());
02632 
02633         default:
02634           return ACC_invalid;
02635       }
02636     }
02637 
02638     /// Look through unary extension.
02639     ACCResult VisitUnaryExtension(UnaryOperator *e) {
02640       return Visit(e->getSubExpr());
02641     }
02642 
02643     /// Ignore the LHS of a comma operator.
02644     ACCResult VisitBinComma(BinaryOperator *e) {
02645       return Visit(e->getRHS());
02646     }
02647 
02648     /// Conditional operators are okay if both sides are okay.
02649     ACCResult VisitConditionalOperator(ConditionalOperator *e) {
02650       ACCResult left = Visit(e->getTrueExpr());
02651       if (left == ACC_invalid) return ACC_invalid;
02652       return merge(left, Visit(e->getFalseExpr()));
02653     }
02654 
02655     /// Look through pseudo-objects.
02656     ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
02657       // If we're getting here, we should always have a result.
02658       return Visit(e->getResultExpr());
02659     }
02660 
02661     /// Statement expressions are okay if their result expression is okay.
02662     ACCResult VisitStmtExpr(StmtExpr *e) {
02663       return Visit(e->getSubStmt()->body_back());
02664     }
02665 
02666     /// Some declaration references are okay.
02667     ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
02668       // References to global constants from system headers are okay.
02669       // These are things like 'kCFStringTransformToLatin'.  They are
02670       // can also be assumed to be immune to retains.
02671       VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
02672       if (isAnyRetainable(TargetClass) &&
02673           isAnyRetainable(SourceClass) &&
02674           var &&
02675           var->getStorageClass() == SC_Extern &&
02676           var->getType().isConstQualified() &&
02677           Context.getSourceManager().isInSystemHeader(var->getLocation())) {
02678         return ACC_bottom;
02679       }
02680 
02681       // Nothing else.
02682       return ACC_invalid;
02683     }
02684 
02685     /// Some calls are okay.
02686     ACCResult VisitCallExpr(CallExpr *e) {
02687       if (FunctionDecl *fn = e->getDirectCallee())
02688         if (ACCResult result = checkCallToFunction(fn))
02689           return result;
02690 
02691       return super::VisitCallExpr(e);
02692     }
02693 
02694     ACCResult checkCallToFunction(FunctionDecl *fn) {
02695       // Require a CF*Ref return type.
02696       if (!isCFType(fn->getResultType()))
02697         return ACC_invalid;
02698 
02699       if (!isAnyRetainable(TargetClass))
02700         return ACC_invalid;
02701 
02702       // Honor an explicit 'not retained' attribute.
02703       if (fn->hasAttr<CFReturnsNotRetainedAttr>())
02704         return ACC_plusZero;
02705 
02706       // Honor an explicit 'retained' attribute, except that for
02707       // now we're not going to permit implicit handling of +1 results,
02708       // because it's a bit frightening.
02709       if (fn->hasAttr<CFReturnsRetainedAttr>())
02710         return ACC_invalid; // ACC_plusOne if we start accepting this
02711 
02712       // Recognize this specific builtin function, which is used by CFSTR.
02713       unsigned builtinID = fn->getBuiltinID();
02714       if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
02715         return ACC_bottom;
02716 
02717       // Otherwise, don't do anything implicit with an unaudited function.
02718       if (!fn->hasAttr<CFAuditedTransferAttr>())
02719         return ACC_invalid;
02720 
02721       // Otherwise, it's +0 unless it follows the create convention.
02722       if (ento::coreFoundation::followsCreateRule(fn))
02723         return ACC_invalid; // ACC_plusOne if we start accepting this
02724 
02725       return ACC_plusZero;
02726     }
02727 
02728     ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
02729       return checkCallToMethod(e->getMethodDecl());
02730     }
02731 
02732     ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
02733       ObjCMethodDecl *method;
02734       if (e->isExplicitProperty())
02735         method = e->getExplicitProperty()->getGetterMethodDecl();
02736       else
02737         method = e->getImplicitPropertyGetter();
02738       return checkCallToMethod(method);
02739     }
02740 
02741     ACCResult checkCallToMethod(ObjCMethodDecl *method) {
02742       if (!method) return ACC_invalid;
02743 
02744       // Check for message sends to functions returning CF types.  We
02745       // just obey the Cocoa conventions with these, even though the
02746       // return type is CF.
02747       if (!isAnyRetainable(TargetClass) || !isCFType(method->getResultType()))
02748         return ACC_invalid;
02749       
02750       // If the method is explicitly marked not-retained, it's +0.
02751       if (method->hasAttr<CFReturnsNotRetainedAttr>())
02752         return ACC_plusZero;
02753 
02754       // If the method is explicitly marked as returning retained, or its
02755       // selector follows a +1 Cocoa convention, treat it as +1.
02756       if (method->hasAttr<CFReturnsRetainedAttr>())
02757         return ACC_plusOne;
02758 
02759       switch (method->getSelector().getMethodFamily()) {
02760       case OMF_alloc:
02761       case OMF_copy:
02762       case OMF_mutableCopy:
02763       case OMF_new:
02764         return ACC_plusOne;
02765 
02766       default:
02767         // Otherwise, treat it as +0.
02768         return ACC_plusZero;
02769       }
02770     }
02771   };
02772 }
02773 
02774 static bool
02775 KnownName(Sema &S, const char *name) {
02776   LookupResult R(S, &S.Context.Idents.get(name), SourceLocation(),
02777                  Sema::LookupOrdinaryName);
02778   return S.LookupName(R, S.TUScope, false);
02779 }
02780 
02781 static void addFixitForObjCARCConversion(Sema &S,
02782                                          DiagnosticBuilder &DiagB,
02783                                          Sema::CheckedConversionKind CCK,
02784                                          SourceLocation afterLParen,
02785                                          QualType castType,
02786                                          Expr *castExpr,
02787                                          const char *bridgeKeyword,
02788                                          const char *CFBridgeName) {
02789   // We handle C-style and implicit casts here.
02790   switch (CCK) {
02791   case Sema::CCK_ImplicitConversion:
02792   case Sema::CCK_CStyleCast:
02793     break;
02794   case Sema::CCK_FunctionalCast:
02795   case Sema::CCK_OtherCast:
02796     return;
02797   }
02798 
02799   if (CFBridgeName) {
02800     Expr *castedE = castExpr;
02801     if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
02802       castedE = CCE->getSubExpr();
02803     castedE = castedE->IgnoreImpCasts();
02804     SourceRange range = castedE->getSourceRange();
02805     if (isa<ParenExpr>(castedE)) {
02806       DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
02807                          CFBridgeName));
02808     } else {
02809       std::string namePlusParen = CFBridgeName;
02810       namePlusParen += "(";
02811       DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
02812                                                     namePlusParen));
02813       DiagB.AddFixItHint(FixItHint::CreateInsertion(
02814                                        S.PP.getLocForEndOfToken(range.getEnd()),
02815                                        ")"));
02816     }
02817     return;
02818   }
02819 
02820   if (CCK == Sema::CCK_CStyleCast) {
02821     DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
02822   } else {
02823     std::string castCode = "(";
02824     castCode += bridgeKeyword;
02825     castCode += castType.getAsString();
02826     castCode += ")";
02827     Expr *castedE = castExpr->IgnoreImpCasts();
02828     SourceRange range = castedE->getSourceRange();
02829     if (isa<ParenExpr>(castedE)) {
02830       DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
02831                          castCode));
02832     } else {
02833       castCode += "(";
02834       DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
02835                                                     castCode));
02836       DiagB.AddFixItHint(FixItHint::CreateInsertion(
02837                                        S.PP.getLocForEndOfToken(range.getEnd()),
02838                                        ")"));
02839     }
02840   }
02841 }
02842 
02843 static void
02844 diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
02845                           QualType castType, ARCConversionTypeClass castACTC,
02846                           Expr *castExpr, ARCConversionTypeClass exprACTC,
02847                           Sema::CheckedConversionKind CCK) {
02848   SourceLocation loc =
02849     (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
02850   
02851   if (S.makeUnavailableInSystemHeader(loc,
02852                 "converts between Objective-C and C pointers in -fobjc-arc"))
02853     return;
02854 
02855   QualType castExprType = castExpr->getType();
02856   
02857   unsigned srcKind = 0;
02858   switch (exprACTC) {
02859   case ACTC_none:
02860   case ACTC_coreFoundation:
02861   case ACTC_voidPtr:
02862     srcKind = (castExprType->isPointerType() ? 1 : 0);
02863     break;
02864   case ACTC_retainable:
02865     srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
02866     break;
02867   case ACTC_indirectRetainable:
02868     srcKind = 4;
02869     break;
02870   }
02871   
02872   // Check whether this could be fixed with a bridge cast.
02873   SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
02874   SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
02875 
02876   // Bridge from an ARC type to a CF type.
02877   if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
02878 
02879     S.Diag(loc, diag::err_arc_cast_requires_bridge)
02880       << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
02881       << 2 // of C pointer type
02882       << castExprType
02883       << unsigned(castType->isBlockPointerType()) // to ObjC|block type
02884       << castType
02885       << castRange
02886       << castExpr->getSourceRange();
02887     bool br = KnownName(S, "CFBridgingRelease");
02888     {
02889       DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge);
02890       addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
02891                                    castType, castExpr, "__bridge ", 0);
02892     }
02893     {
02894       DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge_transfer)
02895         << castExprType << br;
02896       addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
02897                                    castType, castExpr, "__bridge_transfer ",
02898                                    br ? "CFBridgingRelease" : 0);
02899     }
02900 
02901     return;
02902   }
02903     
02904   // Bridge from a CF type to an ARC type.
02905   if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
02906     bool br = KnownName(S, "CFBridgingRetain");
02907     S.Diag(loc, diag::err_arc_cast_requires_bridge)
02908       << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
02909       << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
02910       << castExprType
02911       << 2 // to C pointer type
02912       << castType
02913       << castRange
02914       << castExpr->getSourceRange();
02915 
02916     {
02917       DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge);
02918       addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
02919                                    castType, castExpr, "__bridge ", 0);
02920     }
02921     {
02922       DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge_retained)
02923         << castType << br;
02924       addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
02925                                    castType, castExpr, "__bridge_retained ",
02926                                    br ? "CFBridgingRetain" : 0);
02927     }
02928 
02929     return;
02930   }
02931   
02932   S.Diag(loc, diag::err_arc_mismatched_cast)
02933     << (CCK != Sema::CCK_ImplicitConversion)
02934     << srcKind << castExprType << castType
02935     << castRange << castExpr->getSourceRange();
02936 }
02937 
02938 Sema::ARCConversionResult
02939 Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
02940                              Expr *&castExpr, CheckedConversionKind CCK) {
02941   QualType castExprType = castExpr->getType();
02942 
02943   // For the purposes of the classification, we assume reference types
02944   // will bind to temporaries.
02945   QualType effCastType = castType;
02946   if (const ReferenceType *ref = castType->getAs<ReferenceType>())
02947     effCastType = ref->getPointeeType();
02948   
02949   ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
02950   ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
02951   if (exprACTC == castACTC) {
02952     // check for viablity and report error if casting an rvalue to a
02953     // life-time qualifier.
02954     if ((castACTC == ACTC_retainable) &&
02955         (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
02956         (castType != castExprType)) {
02957       const Type *DT = castType.getTypePtr();
02958       QualType QDT = castType;
02959       // We desugar some types but not others. We ignore those
02960       // that cannot happen in a cast; i.e. auto, and those which
02961       // should not be de-sugared; i.e typedef.
02962       if (const ParenType *PT = dyn_cast<ParenType>(DT))
02963         QDT = PT->desugar();
02964       else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
02965         QDT = TP->desugar();
02966       else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
02967         QDT = AT->desugar();
02968       if (QDT != castType &&
02969           QDT.getObjCLifetime() !=  Qualifiers::OCL_None) {
02970         SourceLocation loc =
02971           (castRange.isValid() ? castRange.getBegin() 
02972                               : castExpr->getExprLoc());
02973         Diag(loc, diag::err_arc_nolifetime_behavior);
02974       }
02975     }
02976     return ACR_okay;
02977   }
02978   
02979   if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
02980 
02981   // Allow all of these types to be cast to integer types (but not
02982   // vice-versa).
02983   if (castACTC == ACTC_none && castType->isIntegralType(Context))
02984     return ACR_okay;
02985   
02986   // Allow casts between pointers to lifetime types (e.g., __strong id*)
02987   // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
02988   // must be explicit.
02989   if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
02990     return ACR_okay;
02991   if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
02992       CCK != CCK_ImplicitConversion)
02993     return ACR_okay;
02994 
02995   switch (ARCCastChecker(Context, exprACTC, castACTC).Visit(castExpr)) {
02996   // For invalid casts, fall through.
02997   case ACC_invalid:
02998     break;
02999 
03000   // Do nothing for both bottom and +0.
03001   case ACC_bottom:
03002   case ACC_plusZero:
03003     return ACR_okay;
03004 
03005   // If the result is +1, consume it here.
03006   case ACC_plusOne:
03007     castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
03008                                         CK_ARCConsumeObject, castExpr,
03009                                         0, VK_RValue);
03010     ExprNeedsCleanups = true;
03011     return ACR_okay;
03012   }
03013 
03014   // If this is a non-implicit cast from id or block type to a
03015   // CoreFoundation type, delay complaining in case the cast is used
03016   // in an acceptable context.
03017   if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
03018       CCK != CCK_ImplicitConversion)
03019     return ACR_unbridged;
03020 
03021   diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
03022                             castExpr, exprACTC, CCK);
03023   return ACR_okay;
03024 }
03025 
03026 /// Given that we saw an expression with the ARCUnbridgedCastTy
03027 /// placeholder type, complain bitterly.
03028 void Sema::diagnoseARCUnbridgedCast(Expr *e) {
03029   // We expect the spurious ImplicitCastExpr to already have been stripped.
03030   assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
03031   CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
03032 
03033   SourceRange castRange;
03034   QualType castType;
03035   CheckedConversionKind CCK;
03036 
03037   if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
03038     castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
03039     castType = cast->getTypeAsWritten();
03040     CCK = CCK_CStyleCast;
03041   } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
03042     castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
03043     castType = cast->getTypeAsWritten();
03044     CCK = CCK_OtherCast;
03045   } else {
03046     castType = cast->getType();
03047     CCK = CCK_ImplicitConversion;
03048   }
03049 
03050   ARCConversionTypeClass castACTC =
03051     classifyTypeForARCConversion(castType.getNonReferenceType());
03052 
03053   Expr *castExpr = realCast->getSubExpr();
03054   assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
03055 
03056   diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
03057                             castExpr, ACTC_retainable, CCK);
03058 }
03059 
03060 /// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
03061 /// type, remove the placeholder cast.
03062 Expr *Sema::stripARCUnbridgedCast(Expr *e) {
03063   assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
03064 
03065   if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
03066     Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
03067     return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
03068   } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
03069     assert(uo->getOpcode() == UO_Extension);
03070     Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
03071     return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
03072                                    sub->getValueKind(), sub->getObjectKind(),
03073                                        uo->getOperatorLoc());
03074   } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
03075     assert(!gse->isResultDependent());
03076 
03077     unsigned n = gse->getNumAssocs();
03078     SmallVector<Expr*, 4> subExprs(n);
03079     SmallVector<TypeSourceInfo*, 4> subTypes(n);
03080     for (unsigned i = 0; i != n; ++i) {
03081       subTypes[i] = gse->getAssocTypeSourceInfo(i);
03082       Expr *sub = gse->getAssocExpr(i);
03083       if (i == gse->getResultIndex())
03084         sub = stripARCUnbridgedCast(sub);
03085       subExprs[i] = sub;
03086     }
03087 
03088     return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
03089                                               gse->getControllingExpr(),
03090                                               subTypes.data(), subExprs.data(),
03091                                               n, gse->getDefaultLoc(),
03092                                               gse->getRParenLoc(),
03093                                        gse->containsUnexpandedParameterPack(),
03094                                               gse->getResultIndex());
03095   } else {
03096     assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
03097     return cast<ImplicitCastExpr>(e)->getSubExpr();
03098   }
03099 }
03100 
03101 bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
03102                                                  QualType exprType) {
03103   QualType canCastType = 
03104     Context.getCanonicalType(castType).getUnqualifiedType();
03105   QualType canExprType = 
03106     Context.getCanonicalType(exprType).getUnqualifiedType();
03107   if (isa<ObjCObjectPointerType>(canCastType) &&
03108       castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
03109       canExprType->isObjCObjectPointerType()) {
03110     if (const ObjCObjectPointerType *ObjT =
03111         canExprType->getAs<ObjCObjectPointerType>())
03112       if (ObjT->getInterfaceDecl()->isArcWeakrefUnavailable())
03113         return false;
03114   }
03115   return true;
03116 }
03117 
03118 /// Look for an ObjCReclaimReturnedObject cast and destroy it.
03119 static Expr *maybeUndoReclaimObject(Expr *e) {
03120   // For now, we just undo operands that are *immediately* reclaim
03121   // expressions, which prevents the vast majority of potential
03122   // problems here.  To catch them all, we'd need to rebuild arbitrary
03123   // value-propagating subexpressions --- we can't reliably rebuild
03124   // in-place because of expression sharing.
03125   if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
03126     if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
03127       return ice->getSubExpr();
03128 
03129   return e;
03130 }
03131 
03132 ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
03133                                       ObjCBridgeCastKind Kind,
03134                                       SourceLocation BridgeKeywordLoc,
03135                                       TypeSourceInfo *TSInfo,
03136                                       Expr *SubExpr) {
03137   ExprResult SubResult = UsualUnaryConversions(SubExpr);
03138   if (SubResult.isInvalid()) return ExprError();
03139   SubExpr = SubResult.take();
03140 
03141   QualType T = TSInfo->getType();
03142   QualType FromType = SubExpr->getType();
03143 
03144   CastKind CK;
03145 
03146   bool MustConsume = false;
03147   if (T->isDependentType() || SubExpr->isTypeDependent()) {
03148     // Okay: we'll build a dependent expression type.
03149     CK = CK_Dependent;
03150   } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
03151     // Casting CF -> id
03152     CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
03153                                   : CK_CPointerToObjCPointerCast);
03154     switch (Kind) {
03155     case OBC_Bridge:
03156       break;
03157       
03158     case OBC_BridgeRetained: {
03159       bool br = KnownName(*this, "CFBridgingRelease");
03160       Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
03161         << 2
03162         << FromType
03163         << (T->isBlockPointerType()? 1 : 0)
03164         << T
03165         << SubExpr->getSourceRange()
03166         << Kind;
03167       Diag(BridgeKeywordLoc, diag::note_arc_bridge)
03168         << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
03169       Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
03170         << FromType << br
03171         << FixItHint::CreateReplacement(BridgeKeywordLoc, 
03172                                         br ? "CFBridgingRelease " 
03173                                            : "__bridge_transfer ");
03174 
03175       Kind = OBC_Bridge;
03176       break;
03177     }
03178       
03179     case OBC_BridgeTransfer:
03180       // We must consume the Objective-C object produced by the cast.
03181       MustConsume = true;
03182       break;
03183     }
03184   } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
03185     // Okay: id -> CF
03186     CK = CK_BitCast;
03187     switch (Kind) {
03188     case OBC_Bridge:
03189       // Reclaiming a value that's going to be __bridge-casted to CF
03190       // is very dangerous, so we don't do it.
03191       SubExpr = maybeUndoReclaimObject(SubExpr);
03192       break;
03193       
03194     case OBC_BridgeRetained:        
03195       // Produce the object before casting it.
03196       SubExpr = ImplicitCastExpr::Create(Context, FromType,
03197                                          CK_ARCProduceObject,
03198                                          SubExpr, 0, VK_RValue);
03199       break;
03200       
03201     case OBC_BridgeTransfer: {
03202       bool br = KnownName(*this, "CFBridgingRetain");
03203       Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
03204         << (FromType->isBlockPointerType()? 1 : 0)
03205         << FromType
03206         << 2
03207         << T
03208         << SubExpr->getSourceRange()
03209         << Kind;
03210         
03211       Diag(BridgeKeywordLoc, diag::note_arc_bridge)
03212         << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
03213       Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
03214         << T << br
03215         << FixItHint::CreateReplacement(BridgeKeywordLoc, 
03216                           br ? "CFBridgingRetain " : "__bridge_retained");
03217         
03218       Kind = OBC_Bridge;
03219       break;
03220     }
03221     }
03222   } else {
03223     Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
03224       << FromType << T << Kind
03225       << SubExpr->getSourceRange()
03226       << TSInfo->getTypeLoc().getSourceRange();
03227     return ExprError();
03228   }
03229 
03230   Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
03231                                                    BridgeKeywordLoc,
03232                                                    TSInfo, SubExpr);
03233   
03234   if (MustConsume) {
03235     ExprNeedsCleanups = true;
03236     Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result, 
03237                                       0, VK_RValue);    
03238   }
03239   
03240   return Result;
03241 }
03242 
03243 ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
03244                                       SourceLocation LParenLoc,
03245                                       ObjCBridgeCastKind Kind,
03246                                       SourceLocation BridgeKeywordLoc,
03247                                       ParsedType Type,
03248                                       SourceLocation RParenLoc,
03249                                       Expr *SubExpr) {
03250   TypeSourceInfo *TSInfo = 0;
03251   QualType T = GetTypeFromParser(Type, &TSInfo);
03252   if (!TSInfo)
03253     TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
03254   return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo, 
03255                               SubExpr);
03256 }