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