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