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