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