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