1 //===--- SemaPseudoObject.cpp - Semantic Analysis for Pseudo-Objects ------===// 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 expressions involving 11 // pseudo-object references. Pseudo-objects are conceptual objects 12 // whose storage is entirely abstract and all accesses to which are 13 // translated through some sort of abstraction barrier. 14 // 15 // For example, Objective-C objects can have "properties", either 16 // declared or undeclared. A property may be accessed by writing 17 // expr.prop 18 // where 'expr' is an r-value of Objective-C pointer type and 'prop' 19 // is the name of the property. If this expression is used in a context 20 // needing an r-value, it is treated as if it were a message-send 21 // of the associated 'getter' selector, typically: 22 // [expr prop] 23 // If it is used as the LHS of a simple assignment, it is treated 24 // as a message-send of the associated 'setter' selector, typically: 25 // [expr setProp: RHS] 26 // If it is used as the LHS of a compound assignment, or the operand 27 // of a unary increment or decrement, both are required; for example, 28 // 'expr.prop *= 100' would be translated to: 29 // [expr setProp: [expr prop] * 100] 30 // 31 //===----------------------------------------------------------------------===// 32 33 #include "clang/Sema/SemaInternal.h" 34 #include "clang/AST/ExprObjC.h" 35 #include "clang/Basic/CharInfo.h" 36 #include "clang/Lex/Preprocessor.h" 37 #include "clang/Sema/Initialization.h" 38 #include "clang/Sema/ScopeInfo.h" 39 #include "llvm/ADT/SmallString.h" 40 41 using namespace clang; 42 using namespace sema; 43 44 namespace { 45 // Basically just a very focused copy of TreeTransform. 46 template <class T> struct Rebuilder { 47 Sema &S; 48 Rebuilder(Sema &S) : S(S) {} 49 50 T &getDerived() { return static_cast<T&>(*this); } 51 52 Expr *rebuild(Expr *e) { 53 // Fast path: nothing to look through. 54 if (typename T::specific_type *specific 55 = dyn_cast<typename T::specific_type>(e)) 56 return getDerived().rebuildSpecific(specific); 57 58 // Otherwise, we should look through and rebuild anything that 59 // IgnoreParens would. 60 61 if (ParenExpr *parens = dyn_cast<ParenExpr>(e)) { 62 e = rebuild(parens->getSubExpr()); 63 return new (S.Context) ParenExpr(parens->getLParen(), 64 parens->getRParen(), 65 e); 66 } 67 68 if (UnaryOperator *uop = dyn_cast<UnaryOperator>(e)) { 69 assert(uop->getOpcode() == UO_Extension); 70 e = rebuild(uop->getSubExpr()); 71 return new (S.Context) UnaryOperator(e, uop->getOpcode(), 72 uop->getType(), 73 uop->getValueKind(), 74 uop->getObjectKind(), 75 uop->getOperatorLoc()); 76 } 77 78 if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) { 79 assert(!gse->isResultDependent()); 80 unsigned resultIndex = gse->getResultIndex(); 81 unsigned numAssocs = gse->getNumAssocs(); 82 83 SmallVector<Expr*, 8> assocs(numAssocs); 84 SmallVector<TypeSourceInfo*, 8> assocTypes(numAssocs); 85 86 for (unsigned i = 0; i != numAssocs; ++i) { 87 Expr *assoc = gse->getAssocExpr(i); 88 if (i == resultIndex) assoc = rebuild(assoc); 89 assocs[i] = assoc; 90 assocTypes[i] = gse->getAssocTypeSourceInfo(i); 91 } 92 93 return new (S.Context) GenericSelectionExpr(S.Context, 94 gse->getGenericLoc(), 95 gse->getControllingExpr(), 96 assocTypes, 97 assocs, 98 gse->getDefaultLoc(), 99 gse->getRParenLoc(), 100 gse->containsUnexpandedParameterPack(), 101 resultIndex); 102 } 103 104 if (ChooseExpr *ce = dyn_cast<ChooseExpr>(e)) { 105 assert(!ce->isConditionDependent()); 106 107 Expr *LHS = ce->getLHS(), *RHS = ce->getRHS(); 108 Expr *&rebuiltExpr = ce->isConditionTrue() ? LHS : RHS; 109 rebuiltExpr = rebuild(rebuiltExpr); 110 111 return new (S.Context) ChooseExpr(ce->getBuiltinLoc(), 112 ce->getCond(), 113 LHS, RHS, 114 rebuiltExpr->getType(), 115 rebuiltExpr->getValueKind(), 116 rebuiltExpr->getObjectKind(), 117 ce->getRParenLoc(), 118 ce->isConditionTrue(), 119 rebuiltExpr->isTypeDependent(), 120 rebuiltExpr->isValueDependent()); 121 } 122 123 llvm_unreachable("bad expression to rebuild!"); 124 } 125 }; 126 127 struct ObjCPropertyRefRebuilder : Rebuilder<ObjCPropertyRefRebuilder> { 128 Expr *NewBase; 129 ObjCPropertyRefRebuilder(Sema &S, Expr *newBase) 130 : Rebuilder<ObjCPropertyRefRebuilder>(S), NewBase(newBase) {} 131 132 typedef ObjCPropertyRefExpr specific_type; 133 Expr *rebuildSpecific(ObjCPropertyRefExpr *refExpr) { 134 // Fortunately, the constraint that we're rebuilding something 135 // with a base limits the number of cases here. 136 assert(refExpr->isObjectReceiver()); 137 138 if (refExpr->isExplicitProperty()) { 139 return new (S.Context) 140 ObjCPropertyRefExpr(refExpr->getExplicitProperty(), 141 refExpr->getType(), refExpr->getValueKind(), 142 refExpr->getObjectKind(), refExpr->getLocation(), 143 NewBase); 144 } 145 return new (S.Context) 146 ObjCPropertyRefExpr(refExpr->getImplicitPropertyGetter(), 147 refExpr->getImplicitPropertySetter(), 148 refExpr->getType(), refExpr->getValueKind(), 149 refExpr->getObjectKind(),refExpr->getLocation(), 150 NewBase); 151 } 152 }; 153 154 struct ObjCSubscriptRefRebuilder : Rebuilder<ObjCSubscriptRefRebuilder> { 155 Expr *NewBase; 156 Expr *NewKeyExpr; 157 ObjCSubscriptRefRebuilder(Sema &S, Expr *newBase, Expr *newKeyExpr) 158 : Rebuilder<ObjCSubscriptRefRebuilder>(S), 159 NewBase(newBase), NewKeyExpr(newKeyExpr) {} 160 161 typedef ObjCSubscriptRefExpr specific_type; 162 Expr *rebuildSpecific(ObjCSubscriptRefExpr *refExpr) { 163 assert(refExpr->getBaseExpr()); 164 assert(refExpr->getKeyExpr()); 165 166 return new (S.Context) 167 ObjCSubscriptRefExpr(NewBase, 168 NewKeyExpr, 169 refExpr->getType(), refExpr->getValueKind(), 170 refExpr->getObjectKind(),refExpr->getAtIndexMethodDecl(), 171 refExpr->setAtIndexMethodDecl(), 172 refExpr->getRBracket()); 173 } 174 }; 175 176 struct MSPropertyRefRebuilder : Rebuilder<MSPropertyRefRebuilder> { 177 Expr *NewBase; 178 MSPropertyRefRebuilder(Sema &S, Expr *newBase) 179 : Rebuilder<MSPropertyRefRebuilder>(S), NewBase(newBase) {} 180 181 typedef MSPropertyRefExpr specific_type; 182 Expr *rebuildSpecific(MSPropertyRefExpr *refExpr) { 183 assert(refExpr->getBaseExpr()); 184 185 return new (S.Context) 186 MSPropertyRefExpr(NewBase, refExpr->getPropertyDecl(), 187 refExpr->isArrow(), refExpr->getType(), 188 refExpr->getValueKind(), refExpr->getQualifierLoc(), 189 refExpr->getMemberLoc()); 190 } 191 }; 192 193 class PseudoOpBuilder { 194 public: 195 Sema &S; 196 unsigned ResultIndex; 197 SourceLocation GenericLoc; 198 SmallVector<Expr *, 4> Semantics; 199 200 PseudoOpBuilder(Sema &S, SourceLocation genericLoc) 201 : S(S), ResultIndex(PseudoObjectExpr::NoResult), 202 GenericLoc(genericLoc) {} 203 204 virtual ~PseudoOpBuilder() {} 205 206 /// Add a normal semantic expression. 207 void addSemanticExpr(Expr *semantic) { 208 Semantics.push_back(semantic); 209 } 210 211 /// Add the 'result' semantic expression. 212 void addResultSemanticExpr(Expr *resultExpr) { 213 assert(ResultIndex == PseudoObjectExpr::NoResult); 214 ResultIndex = Semantics.size(); 215 Semantics.push_back(resultExpr); 216 } 217 218 ExprResult buildRValueOperation(Expr *op); 219 ExprResult buildAssignmentOperation(Scope *Sc, 220 SourceLocation opLoc, 221 BinaryOperatorKind opcode, 222 Expr *LHS, Expr *RHS); 223 ExprResult buildIncDecOperation(Scope *Sc, SourceLocation opLoc, 224 UnaryOperatorKind opcode, 225 Expr *op); 226 227 virtual ExprResult complete(Expr *syntacticForm); 228 229 OpaqueValueExpr *capture(Expr *op); 230 OpaqueValueExpr *captureValueAsResult(Expr *op); 231 232 void setResultToLastSemantic() { 233 assert(ResultIndex == PseudoObjectExpr::NoResult); 234 ResultIndex = Semantics.size() - 1; 235 } 236 237 /// Return true if assignments have a non-void result. 238 bool CanCaptureValue(Expr *exp) { 239 if (exp->isGLValue()) 240 return true; 241 QualType ty = exp->getType(); 242 assert(!ty->isIncompleteType()); 243 assert(!ty->isDependentType()); 244 245 if (const CXXRecordDecl *ClassDecl = ty->getAsCXXRecordDecl()) 246 return ClassDecl->isTriviallyCopyable(); 247 return true; 248 } 249 250 virtual Expr *rebuildAndCaptureObject(Expr *) = 0; 251 virtual ExprResult buildGet() = 0; 252 virtual ExprResult buildSet(Expr *, SourceLocation, 253 bool captureSetValueAsResult) = 0; 254 }; 255 256 /// A PseudoOpBuilder for Objective-C \@properties. 257 class ObjCPropertyOpBuilder : public PseudoOpBuilder { 258 ObjCPropertyRefExpr *RefExpr; 259 ObjCPropertyRefExpr *SyntacticRefExpr; 260 OpaqueValueExpr *InstanceReceiver; 261 ObjCMethodDecl *Getter; 262 263 ObjCMethodDecl *Setter; 264 Selector SetterSelector; 265 Selector GetterSelector; 266 267 public: 268 ObjCPropertyOpBuilder(Sema &S, ObjCPropertyRefExpr *refExpr) : 269 PseudoOpBuilder(S, refExpr->getLocation()), RefExpr(refExpr), 270 SyntacticRefExpr(0), InstanceReceiver(0), Getter(0), Setter(0) { 271 } 272 273 ExprResult buildRValueOperation(Expr *op); 274 ExprResult buildAssignmentOperation(Scope *Sc, 275 SourceLocation opLoc, 276 BinaryOperatorKind opcode, 277 Expr *LHS, Expr *RHS); 278 ExprResult buildIncDecOperation(Scope *Sc, SourceLocation opLoc, 279 UnaryOperatorKind opcode, 280 Expr *op); 281 282 bool tryBuildGetOfReference(Expr *op, ExprResult &result); 283 bool findSetter(bool warn=true); 284 bool findGetter(); 285 286 Expr *rebuildAndCaptureObject(Expr *syntacticBase) override; 287 ExprResult buildGet() override; 288 ExprResult buildSet(Expr *op, SourceLocation, bool) override; 289 ExprResult complete(Expr *SyntacticForm) override; 290 291 bool isWeakProperty() const; 292 }; 293 294 /// A PseudoOpBuilder for Objective-C array/dictionary indexing. 295 class ObjCSubscriptOpBuilder : public PseudoOpBuilder { 296 ObjCSubscriptRefExpr *RefExpr; 297 OpaqueValueExpr *InstanceBase; 298 OpaqueValueExpr *InstanceKey; 299 ObjCMethodDecl *AtIndexGetter; 300 Selector AtIndexGetterSelector; 301 302 ObjCMethodDecl *AtIndexSetter; 303 Selector AtIndexSetterSelector; 304 305 public: 306 ObjCSubscriptOpBuilder(Sema &S, ObjCSubscriptRefExpr *refExpr) : 307 PseudoOpBuilder(S, refExpr->getSourceRange().getBegin()), 308 RefExpr(refExpr), 309 InstanceBase(0), InstanceKey(0), 310 AtIndexGetter(0), AtIndexSetter(0) { } 311 312 ExprResult buildRValueOperation(Expr *op); 313 ExprResult buildAssignmentOperation(Scope *Sc, 314 SourceLocation opLoc, 315 BinaryOperatorKind opcode, 316 Expr *LHS, Expr *RHS); 317 Expr *rebuildAndCaptureObject(Expr *syntacticBase) override; 318 319 bool findAtIndexGetter(); 320 bool findAtIndexSetter(); 321 322 ExprResult buildGet() override; 323 ExprResult buildSet(Expr *op, SourceLocation, bool) override; 324 }; 325 326 class MSPropertyOpBuilder : public PseudoOpBuilder { 327 MSPropertyRefExpr *RefExpr; 328 329 public: 330 MSPropertyOpBuilder(Sema &S, MSPropertyRefExpr *refExpr) : 331 PseudoOpBuilder(S, refExpr->getSourceRange().getBegin()), 332 RefExpr(refExpr) {} 333 334 Expr *rebuildAndCaptureObject(Expr *) override; 335 ExprResult buildGet() override; 336 ExprResult buildSet(Expr *op, SourceLocation, bool) override; 337 }; 338 } 339 340 /// Capture the given expression in an OpaqueValueExpr. 341 OpaqueValueExpr *PseudoOpBuilder::capture(Expr *e) { 342 // Make a new OVE whose source is the given expression. 343 OpaqueValueExpr *captured = 344 new (S.Context) OpaqueValueExpr(GenericLoc, e->getType(), 345 e->getValueKind(), e->getObjectKind(), 346 e); 347 348 // Make sure we bind that in the semantics. 349 addSemanticExpr(captured); 350 return captured; 351 } 352 353 /// Capture the given expression as the result of this pseudo-object 354 /// operation. This routine is safe against expressions which may 355 /// already be captured. 356 /// 357 /// \returns the captured expression, which will be the 358 /// same as the input if the input was already captured 359 OpaqueValueExpr *PseudoOpBuilder::captureValueAsResult(Expr *e) { 360 assert(ResultIndex == PseudoObjectExpr::NoResult); 361 362 // If the expression hasn't already been captured, just capture it 363 // and set the new semantic 364 if (!isa<OpaqueValueExpr>(e)) { 365 OpaqueValueExpr *cap = capture(e); 366 setResultToLastSemantic(); 367 return cap; 368 } 369 370 // Otherwise, it must already be one of our semantic expressions; 371 // set ResultIndex to its index. 372 unsigned index = 0; 373 for (;; ++index) { 374 assert(index < Semantics.size() && 375 "captured expression not found in semantics!"); 376 if (e == Semantics[index]) break; 377 } 378 ResultIndex = index; 379 return cast<OpaqueValueExpr>(e); 380 } 381 382 /// The routine which creates the final PseudoObjectExpr. 383 ExprResult PseudoOpBuilder::complete(Expr *syntactic) { 384 return PseudoObjectExpr::Create(S.Context, syntactic, 385 Semantics, ResultIndex); 386 } 387 388 /// The main skeleton for building an r-value operation. 389 ExprResult PseudoOpBuilder::buildRValueOperation(Expr *op) { 390 Expr *syntacticBase = rebuildAndCaptureObject(op); 391 392 ExprResult getExpr = buildGet(); 393 if (getExpr.isInvalid()) return ExprError(); 394 addResultSemanticExpr(getExpr.take()); 395 396 return complete(syntacticBase); 397 } 398 399 /// The basic skeleton for building a simple or compound 400 /// assignment operation. 401 ExprResult 402 PseudoOpBuilder::buildAssignmentOperation(Scope *Sc, SourceLocation opcLoc, 403 BinaryOperatorKind opcode, 404 Expr *LHS, Expr *RHS) { 405 assert(BinaryOperator::isAssignmentOp(opcode)); 406 407 Expr *syntacticLHS = rebuildAndCaptureObject(LHS); 408 OpaqueValueExpr *capturedRHS = capture(RHS); 409 410 Expr *syntactic; 411 412 ExprResult result; 413 if (opcode == BO_Assign) { 414 result = capturedRHS; 415 syntactic = new (S.Context) BinaryOperator(syntacticLHS, capturedRHS, 416 opcode, capturedRHS->getType(), 417 capturedRHS->getValueKind(), 418 OK_Ordinary, opcLoc, false); 419 } else { 420 ExprResult opLHS = buildGet(); 421 if (opLHS.isInvalid()) return ExprError(); 422 423 // Build an ordinary, non-compound operation. 424 BinaryOperatorKind nonCompound = 425 BinaryOperator::getOpForCompoundAssignment(opcode); 426 result = S.BuildBinOp(Sc, opcLoc, nonCompound, 427 opLHS.take(), capturedRHS); 428 if (result.isInvalid()) return ExprError(); 429 430 syntactic = 431 new (S.Context) CompoundAssignOperator(syntacticLHS, capturedRHS, opcode, 432 result.get()->getType(), 433 result.get()->getValueKind(), 434 OK_Ordinary, 435 opLHS.get()->getType(), 436 result.get()->getType(), 437 opcLoc, false); 438 } 439 440 // The result of the assignment, if not void, is the value set into 441 // the l-value. 442 result = buildSet(result.take(), opcLoc, /*captureSetValueAsResult*/ true); 443 if (result.isInvalid()) return ExprError(); 444 addSemanticExpr(result.take()); 445 446 return complete(syntactic); 447 } 448 449 /// The basic skeleton for building an increment or decrement 450 /// operation. 451 ExprResult 452 PseudoOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc, 453 UnaryOperatorKind opcode, 454 Expr *op) { 455 assert(UnaryOperator::isIncrementDecrementOp(opcode)); 456 457 Expr *syntacticOp = rebuildAndCaptureObject(op); 458 459 // Load the value. 460 ExprResult result = buildGet(); 461 if (result.isInvalid()) return ExprError(); 462 463 QualType resultType = result.get()->getType(); 464 465 // That's the postfix result. 466 if (UnaryOperator::isPostfix(opcode) && 467 (result.get()->isTypeDependent() || CanCaptureValue(result.get()))) { 468 result = capture(result.take()); 469 setResultToLastSemantic(); 470 } 471 472 // Add or subtract a literal 1. 473 llvm::APInt oneV(S.Context.getTypeSize(S.Context.IntTy), 1); 474 Expr *one = IntegerLiteral::Create(S.Context, oneV, S.Context.IntTy, 475 GenericLoc); 476 477 if (UnaryOperator::isIncrementOp(opcode)) { 478 result = S.BuildBinOp(Sc, opcLoc, BO_Add, result.take(), one); 479 } else { 480 result = S.BuildBinOp(Sc, opcLoc, BO_Sub, result.take(), one); 481 } 482 if (result.isInvalid()) return ExprError(); 483 484 // Store that back into the result. The value stored is the result 485 // of a prefix operation. 486 result = buildSet(result.take(), opcLoc, UnaryOperator::isPrefix(opcode)); 487 if (result.isInvalid()) return ExprError(); 488 addSemanticExpr(result.take()); 489 490 UnaryOperator *syntactic = 491 new (S.Context) UnaryOperator(syntacticOp, opcode, resultType, 492 VK_LValue, OK_Ordinary, opcLoc); 493 return complete(syntactic); 494 } 495 496 497 //===----------------------------------------------------------------------===// 498 // Objective-C @property and implicit property references 499 //===----------------------------------------------------------------------===// 500 501 /// Look up a method in the receiver type of an Objective-C property 502 /// reference. 503 static ObjCMethodDecl *LookupMethodInReceiverType(Sema &S, Selector sel, 504 const ObjCPropertyRefExpr *PRE) { 505 if (PRE->isObjectReceiver()) { 506 const ObjCObjectPointerType *PT = 507 PRE->getBase()->getType()->castAs<ObjCObjectPointerType>(); 508 509 // Special case for 'self' in class method implementations. 510 if (PT->isObjCClassType() && 511 S.isSelfExpr(const_cast<Expr*>(PRE->getBase()))) { 512 // This cast is safe because isSelfExpr is only true within 513 // methods. 514 ObjCMethodDecl *method = 515 cast<ObjCMethodDecl>(S.CurContext->getNonClosureAncestor()); 516 return S.LookupMethodInObjectType(sel, 517 S.Context.getObjCInterfaceType(method->getClassInterface()), 518 /*instance*/ false); 519 } 520 521 return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true); 522 } 523 524 if (PRE->isSuperReceiver()) { 525 if (const ObjCObjectPointerType *PT = 526 PRE->getSuperReceiverType()->getAs<ObjCObjectPointerType>()) 527 return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true); 528 529 return S.LookupMethodInObjectType(sel, PRE->getSuperReceiverType(), false); 530 } 531 532 assert(PRE->isClassReceiver() && "Invalid expression"); 533 QualType IT = S.Context.getObjCInterfaceType(PRE->getClassReceiver()); 534 return S.LookupMethodInObjectType(sel, IT, false); 535 } 536 537 bool ObjCPropertyOpBuilder::isWeakProperty() const { 538 QualType T; 539 if (RefExpr->isExplicitProperty()) { 540 const ObjCPropertyDecl *Prop = RefExpr->getExplicitProperty(); 541 if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak) 542 return true; 543 544 T = Prop->getType(); 545 } else if (Getter) { 546 T = Getter->getReturnType(); 547 } else { 548 return false; 549 } 550 551 return T.getObjCLifetime() == Qualifiers::OCL_Weak; 552 } 553 554 bool ObjCPropertyOpBuilder::findGetter() { 555 if (Getter) return true; 556 557 // For implicit properties, just trust the lookup we already did. 558 if (RefExpr->isImplicitProperty()) { 559 if ((Getter = RefExpr->getImplicitPropertyGetter())) { 560 GetterSelector = Getter->getSelector(); 561 return true; 562 } 563 else { 564 // Must build the getter selector the hard way. 565 ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter(); 566 assert(setter && "both setter and getter are null - cannot happen"); 567 IdentifierInfo *setterName = 568 setter->getSelector().getIdentifierInfoForSlot(0); 569 const char *compStr = setterName->getNameStart(); 570 compStr += 3; 571 IdentifierInfo *getterName = &S.Context.Idents.get(compStr); 572 GetterSelector = 573 S.PP.getSelectorTable().getNullarySelector(getterName); 574 return false; 575 576 } 577 } 578 579 ObjCPropertyDecl *prop = RefExpr->getExplicitProperty(); 580 Getter = LookupMethodInReceiverType(S, prop->getGetterName(), RefExpr); 581 return (Getter != 0); 582 } 583 584 /// Try to find the most accurate setter declaration for the property 585 /// reference. 586 /// 587 /// \return true if a setter was found, in which case Setter 588 bool ObjCPropertyOpBuilder::findSetter(bool warn) { 589 // For implicit properties, just trust the lookup we already did. 590 if (RefExpr->isImplicitProperty()) { 591 if (ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter()) { 592 Setter = setter; 593 SetterSelector = setter->getSelector(); 594 return true; 595 } else { 596 IdentifierInfo *getterName = 597 RefExpr->getImplicitPropertyGetter()->getSelector() 598 .getIdentifierInfoForSlot(0); 599 SetterSelector = 600 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(), 601 S.PP.getSelectorTable(), 602 getterName); 603 return false; 604 } 605 } 606 607 // For explicit properties, this is more involved. 608 ObjCPropertyDecl *prop = RefExpr->getExplicitProperty(); 609 SetterSelector = prop->getSetterName(); 610 611 // Do a normal method lookup first. 612 if (ObjCMethodDecl *setter = 613 LookupMethodInReceiverType(S, SetterSelector, RefExpr)) { 614 if (setter->isPropertyAccessor() && warn) 615 if (const ObjCInterfaceDecl *IFace = 616 dyn_cast<ObjCInterfaceDecl>(setter->getDeclContext())) { 617 const StringRef thisPropertyName(prop->getName()); 618 // Try flipping the case of the first character. 619 char front = thisPropertyName.front(); 620 front = isLowercase(front) ? toUppercase(front) : toLowercase(front); 621 SmallString<100> PropertyName = thisPropertyName; 622 PropertyName[0] = front; 623 IdentifierInfo *AltMember = &S.PP.getIdentifierTable().get(PropertyName); 624 if (ObjCPropertyDecl *prop1 = IFace->FindPropertyDeclaration(AltMember)) 625 if (prop != prop1 && (prop1->getSetterMethodDecl() == setter)) { 626 S.Diag(RefExpr->getExprLoc(), diag::error_property_setter_ambiguous_use) 627 << prop << prop1 << setter->getSelector(); 628 S.Diag(prop->getLocation(), diag::note_property_declare); 629 S.Diag(prop1->getLocation(), diag::note_property_declare); 630 } 631 } 632 Setter = setter; 633 return true; 634 } 635 636 // That can fail in the somewhat crazy situation that we're 637 // type-checking a message send within the @interface declaration 638 // that declared the @property. But it's not clear that that's 639 // valuable to support. 640 641 return false; 642 } 643 644 /// Capture the base object of an Objective-C property expression. 645 Expr *ObjCPropertyOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) { 646 assert(InstanceReceiver == 0); 647 648 // If we have a base, capture it in an OVE and rebuild the syntactic 649 // form to use the OVE as its base. 650 if (RefExpr->isObjectReceiver()) { 651 InstanceReceiver = capture(RefExpr->getBase()); 652 653 syntacticBase = 654 ObjCPropertyRefRebuilder(S, InstanceReceiver).rebuild(syntacticBase); 655 } 656 657 if (ObjCPropertyRefExpr * 658 refE = dyn_cast<ObjCPropertyRefExpr>(syntacticBase->IgnoreParens())) 659 SyntacticRefExpr = refE; 660 661 return syntacticBase; 662 } 663 664 /// Load from an Objective-C property reference. 665 ExprResult ObjCPropertyOpBuilder::buildGet() { 666 findGetter(); 667 assert(Getter); 668 669 if (SyntacticRefExpr) 670 SyntacticRefExpr->setIsMessagingGetter(); 671 672 QualType receiverType; 673 if (RefExpr->isClassReceiver()) { 674 receiverType = S.Context.getObjCInterfaceType(RefExpr->getClassReceiver()); 675 } else if (RefExpr->isSuperReceiver()) { 676 receiverType = RefExpr->getSuperReceiverType(); 677 } else { 678 assert(InstanceReceiver); 679 receiverType = InstanceReceiver->getType(); 680 } 681 682 // Build a message-send. 683 ExprResult msg; 684 if ((Getter->isInstanceMethod() && !RefExpr->isClassReceiver()) || 685 RefExpr->isObjectReceiver()) { 686 assert(InstanceReceiver || RefExpr->isSuperReceiver()); 687 msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType, 688 GenericLoc, Getter->getSelector(), 689 Getter, None); 690 } else { 691 msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(), 692 GenericLoc, Getter->getSelector(), 693 Getter, None); 694 } 695 return msg; 696 } 697 698 /// Store to an Objective-C property reference. 699 /// 700 /// \param captureSetValueAsResult If true, capture the actual 701 /// value being set as the value of the property operation. 702 ExprResult ObjCPropertyOpBuilder::buildSet(Expr *op, SourceLocation opcLoc, 703 bool captureSetValueAsResult) { 704 bool hasSetter = findSetter(false); 705 assert(hasSetter); (void) hasSetter; 706 707 if (SyntacticRefExpr) 708 SyntacticRefExpr->setIsMessagingSetter(); 709 710 QualType receiverType; 711 if (RefExpr->isClassReceiver()) { 712 receiverType = S.Context.getObjCInterfaceType(RefExpr->getClassReceiver()); 713 } else if (RefExpr->isSuperReceiver()) { 714 receiverType = RefExpr->getSuperReceiverType(); 715 } else { 716 assert(InstanceReceiver); 717 receiverType = InstanceReceiver->getType(); 718 } 719 720 // Use assignment constraints when possible; they give us better 721 // diagnostics. "When possible" basically means anything except a 722 // C++ class type. 723 if (!S.getLangOpts().CPlusPlus || !op->getType()->isRecordType()) { 724 QualType paramType = (*Setter->param_begin())->getType(); 725 if (!S.getLangOpts().CPlusPlus || !paramType->isRecordType()) { 726 ExprResult opResult = op; 727 Sema::AssignConvertType assignResult 728 = S.CheckSingleAssignmentConstraints(paramType, opResult); 729 if (S.DiagnoseAssignmentResult(assignResult, opcLoc, paramType, 730 op->getType(), opResult.get(), 731 Sema::AA_Assigning)) 732 return ExprError(); 733 734 op = opResult.take(); 735 assert(op && "successful assignment left argument invalid?"); 736 } 737 else if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(op)) { 738 Expr *Initializer = OVE->getSourceExpr(); 739 // passing C++11 style initialized temporaries to objc++ properties 740 // requires special treatment by removing OpaqueValueExpr so type 741 // conversion takes place and adding the OpaqueValueExpr later on. 742 if (isa<InitListExpr>(Initializer) && 743 Initializer->getType()->isVoidType()) { 744 op = Initializer; 745 } 746 } 747 } 748 749 // Arguments. 750 Expr *args[] = { op }; 751 752 // Build a message-send. 753 ExprResult msg; 754 if ((Setter->isInstanceMethod() && !RefExpr->isClassReceiver()) || 755 RefExpr->isObjectReceiver()) { 756 msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType, 757 GenericLoc, SetterSelector, Setter, 758 MultiExprArg(args, 1)); 759 } else { 760 msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(), 761 GenericLoc, 762 SetterSelector, Setter, 763 MultiExprArg(args, 1)); 764 } 765 766 if (!msg.isInvalid() && captureSetValueAsResult) { 767 ObjCMessageExpr *msgExpr = 768 cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit()); 769 Expr *arg = msgExpr->getArg(0); 770 if (CanCaptureValue(arg)) 771 msgExpr->setArg(0, captureValueAsResult(arg)); 772 } 773 774 return msg; 775 } 776 777 /// @property-specific behavior for doing lvalue-to-rvalue conversion. 778 ExprResult ObjCPropertyOpBuilder::buildRValueOperation(Expr *op) { 779 // Explicit properties always have getters, but implicit ones don't. 780 // Check that before proceeding. 781 if (RefExpr->isImplicitProperty() && !RefExpr->getImplicitPropertyGetter()) { 782 S.Diag(RefExpr->getLocation(), diag::err_getter_not_found) 783 << RefExpr->getSourceRange(); 784 return ExprError(); 785 } 786 787 ExprResult result = PseudoOpBuilder::buildRValueOperation(op); 788 if (result.isInvalid()) return ExprError(); 789 790 if (RefExpr->isExplicitProperty() && !Getter->hasRelatedResultType()) 791 S.DiagnosePropertyAccessorMismatch(RefExpr->getExplicitProperty(), 792 Getter, RefExpr->getLocation()); 793 794 // As a special case, if the method returns 'id', try to get 795 // a better type from the property. 796 if (RefExpr->isExplicitProperty() && result.get()->isRValue() && 797 result.get()->getType()->isObjCIdType()) { 798 QualType propType = RefExpr->getExplicitProperty()->getType(); 799 if (const ObjCObjectPointerType *ptr 800 = propType->getAs<ObjCObjectPointerType>()) { 801 if (!ptr->isObjCIdType()) 802 result = S.ImpCastExprToType(result.get(), propType, CK_BitCast); 803 } 804 } 805 806 return result; 807 } 808 809 /// Try to build this as a call to a getter that returns a reference. 810 /// 811 /// \return true if it was possible, whether or not it actually 812 /// succeeded 813 bool ObjCPropertyOpBuilder::tryBuildGetOfReference(Expr *op, 814 ExprResult &result) { 815 if (!S.getLangOpts().CPlusPlus) return false; 816 817 findGetter(); 818 assert(Getter && "property has no setter and no getter!"); 819 820 // Only do this if the getter returns an l-value reference type. 821 QualType resultType = Getter->getReturnType(); 822 if (!resultType->isLValueReferenceType()) return false; 823 824 result = buildRValueOperation(op); 825 return true; 826 } 827 828 /// @property-specific behavior for doing assignments. 829 ExprResult 830 ObjCPropertyOpBuilder::buildAssignmentOperation(Scope *Sc, 831 SourceLocation opcLoc, 832 BinaryOperatorKind opcode, 833 Expr *LHS, Expr *RHS) { 834 assert(BinaryOperator::isAssignmentOp(opcode)); 835 836 // If there's no setter, we have no choice but to try to assign to 837 // the result of the getter. 838 if (!findSetter()) { 839 ExprResult result; 840 if (tryBuildGetOfReference(LHS, result)) { 841 if (result.isInvalid()) return ExprError(); 842 return S.BuildBinOp(Sc, opcLoc, opcode, result.take(), RHS); 843 } 844 845 // Otherwise, it's an error. 846 S.Diag(opcLoc, diag::err_nosetter_property_assignment) 847 << unsigned(RefExpr->isImplicitProperty()) 848 << SetterSelector 849 << LHS->getSourceRange() << RHS->getSourceRange(); 850 return ExprError(); 851 } 852 853 // If there is a setter, we definitely want to use it. 854 855 // Verify that we can do a compound assignment. 856 if (opcode != BO_Assign && !findGetter()) { 857 S.Diag(opcLoc, diag::err_nogetter_property_compound_assignment) 858 << LHS->getSourceRange() << RHS->getSourceRange(); 859 return ExprError(); 860 } 861 862 ExprResult result = 863 PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS); 864 if (result.isInvalid()) return ExprError(); 865 866 // Various warnings about property assignments in ARC. 867 if (S.getLangOpts().ObjCAutoRefCount && InstanceReceiver) { 868 S.checkRetainCycles(InstanceReceiver->getSourceExpr(), RHS); 869 S.checkUnsafeExprAssigns(opcLoc, LHS, RHS); 870 } 871 872 return result; 873 } 874 875 /// @property-specific behavior for doing increments and decrements. 876 ExprResult 877 ObjCPropertyOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc, 878 UnaryOperatorKind opcode, 879 Expr *op) { 880 // If there's no setter, we have no choice but to try to assign to 881 // the result of the getter. 882 if (!findSetter()) { 883 ExprResult result; 884 if (tryBuildGetOfReference(op, result)) { 885 if (result.isInvalid()) return ExprError(); 886 return S.BuildUnaryOp(Sc, opcLoc, opcode, result.take()); 887 } 888 889 // Otherwise, it's an error. 890 S.Diag(opcLoc, diag::err_nosetter_property_incdec) 891 << unsigned(RefExpr->isImplicitProperty()) 892 << unsigned(UnaryOperator::isDecrementOp(opcode)) 893 << SetterSelector 894 << op->getSourceRange(); 895 return ExprError(); 896 } 897 898 // If there is a setter, we definitely want to use it. 899 900 // We also need a getter. 901 if (!findGetter()) { 902 assert(RefExpr->isImplicitProperty()); 903 S.Diag(opcLoc, diag::err_nogetter_property_incdec) 904 << unsigned(UnaryOperator::isDecrementOp(opcode)) 905 << GetterSelector 906 << op->getSourceRange(); 907 return ExprError(); 908 } 909 910 return PseudoOpBuilder::buildIncDecOperation(Sc, opcLoc, opcode, op); 911 } 912 913 ExprResult ObjCPropertyOpBuilder::complete(Expr *SyntacticForm) { 914 if (S.getLangOpts().ObjCAutoRefCount && isWeakProperty()) { 915 DiagnosticsEngine::Level Level = 916 S.Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 917 SyntacticForm->getLocStart()); 918 if (Level != DiagnosticsEngine::Ignored) 919 S.recordUseOfEvaluatedWeak(SyntacticRefExpr, 920 SyntacticRefExpr->isMessagingGetter()); 921 } 922 923 return PseudoOpBuilder::complete(SyntacticForm); 924 } 925 926 // ObjCSubscript build stuff. 927 // 928 929 /// objective-c subscripting-specific behavior for doing lvalue-to-rvalue 930 /// conversion. 931 /// FIXME. Remove this routine if it is proven that no additional 932 /// specifity is needed. 933 ExprResult ObjCSubscriptOpBuilder::buildRValueOperation(Expr *op) { 934 ExprResult result = PseudoOpBuilder::buildRValueOperation(op); 935 if (result.isInvalid()) return ExprError(); 936 return result; 937 } 938 939 /// objective-c subscripting-specific behavior for doing assignments. 940 ExprResult 941 ObjCSubscriptOpBuilder::buildAssignmentOperation(Scope *Sc, 942 SourceLocation opcLoc, 943 BinaryOperatorKind opcode, 944 Expr *LHS, Expr *RHS) { 945 assert(BinaryOperator::isAssignmentOp(opcode)); 946 // There must be a method to do the Index'ed assignment. 947 if (!findAtIndexSetter()) 948 return ExprError(); 949 950 // Verify that we can do a compound assignment. 951 if (opcode != BO_Assign && !findAtIndexGetter()) 952 return ExprError(); 953 954 ExprResult result = 955 PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS); 956 if (result.isInvalid()) return ExprError(); 957 958 // Various warnings about objc Index'ed assignments in ARC. 959 if (S.getLangOpts().ObjCAutoRefCount && InstanceBase) { 960 S.checkRetainCycles(InstanceBase->getSourceExpr(), RHS); 961 S.checkUnsafeExprAssigns(opcLoc, LHS, RHS); 962 } 963 964 return result; 965 } 966 967 /// Capture the base object of an Objective-C Index'ed expression. 968 Expr *ObjCSubscriptOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) { 969 assert(InstanceBase == 0); 970 971 // Capture base expression in an OVE and rebuild the syntactic 972 // form to use the OVE as its base expression. 973 InstanceBase = capture(RefExpr->getBaseExpr()); 974 InstanceKey = capture(RefExpr->getKeyExpr()); 975 976 syntacticBase = 977 ObjCSubscriptRefRebuilder(S, InstanceBase, 978 InstanceKey).rebuild(syntacticBase); 979 980 return syntacticBase; 981 } 982 983 /// CheckSubscriptingKind - This routine decide what type 984 /// of indexing represented by "FromE" is being done. 985 Sema::ObjCSubscriptKind 986 Sema::CheckSubscriptingKind(Expr *FromE) { 987 // If the expression already has integral or enumeration type, we're golden. 988 QualType T = FromE->getType(); 989 if (T->isIntegralOrEnumerationType()) 990 return OS_Array; 991 992 // If we don't have a class type in C++, there's no way we can get an 993 // expression of integral or enumeration type. 994 const RecordType *RecordTy = T->getAs<RecordType>(); 995 if (!RecordTy && T->isObjCObjectPointerType()) 996 // All other scalar cases are assumed to be dictionary indexing which 997 // caller handles, with diagnostics if needed. 998 return OS_Dictionary; 999 if (!getLangOpts().CPlusPlus || 1000 !RecordTy || RecordTy->isIncompleteType()) { 1001 // No indexing can be done. Issue diagnostics and quit. 1002 const Expr *IndexExpr = FromE->IgnoreParenImpCasts(); 1003 if (isa<StringLiteral>(IndexExpr)) 1004 Diag(FromE->getExprLoc(), diag::err_objc_subscript_pointer) 1005 << T << FixItHint::CreateInsertion(FromE->getExprLoc(), "@"); 1006 else 1007 Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion) 1008 << T; 1009 return OS_Error; 1010 } 1011 1012 // We must have a complete class type. 1013 if (RequireCompleteType(FromE->getExprLoc(), T, 1014 diag::err_objc_index_incomplete_class_type, FromE)) 1015 return OS_Error; 1016 1017 // Look for a conversion to an integral, enumeration type, or 1018 // objective-C pointer type. 1019 std::pair<CXXRecordDecl::conversion_iterator, 1020 CXXRecordDecl::conversion_iterator> Conversions 1021 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 1022 1023 int NoIntegrals=0, NoObjCIdPointers=0; 1024 SmallVector<CXXConversionDecl *, 4> ConversionDecls; 1025 1026 for (CXXRecordDecl::conversion_iterator 1027 I = Conversions.first, E = Conversions.second; I != E; ++I) { 1028 if (CXXConversionDecl *Conversion 1029 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) { 1030 QualType CT = Conversion->getConversionType().getNonReferenceType(); 1031 if (CT->isIntegralOrEnumerationType()) { 1032 ++NoIntegrals; 1033 ConversionDecls.push_back(Conversion); 1034 } 1035 else if (CT->isObjCIdType() ||CT->isBlockPointerType()) { 1036 ++NoObjCIdPointers; 1037 ConversionDecls.push_back(Conversion); 1038 } 1039 } 1040 } 1041 if (NoIntegrals ==1 && NoObjCIdPointers == 0) 1042 return OS_Array; 1043 if (NoIntegrals == 0 && NoObjCIdPointers == 1) 1044 return OS_Dictionary; 1045 if (NoIntegrals == 0 && NoObjCIdPointers == 0) { 1046 // No conversion function was found. Issue diagnostic and return. 1047 Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion) 1048 << FromE->getType(); 1049 return OS_Error; 1050 } 1051 Diag(FromE->getExprLoc(), diag::err_objc_multiple_subscript_type_conversion) 1052 << FromE->getType(); 1053 for (unsigned int i = 0; i < ConversionDecls.size(); i++) 1054 Diag(ConversionDecls[i]->getLocation(), diag::not_conv_function_declared_at); 1055 1056 return OS_Error; 1057 } 1058 1059 /// CheckKeyForObjCARCConversion - This routine suggests bridge casting of CF 1060 /// objects used as dictionary subscript key objects. 1061 static void CheckKeyForObjCARCConversion(Sema &S, QualType ContainerT, 1062 Expr *Key) { 1063 if (ContainerT.isNull()) 1064 return; 1065 // dictionary subscripting. 1066 // - (id)objectForKeyedSubscript:(id)key; 1067 IdentifierInfo *KeyIdents[] = { 1068 &S.Context.Idents.get("objectForKeyedSubscript") 1069 }; 1070 Selector GetterSelector = S.Context.Selectors.getSelector(1, KeyIdents); 1071 ObjCMethodDecl *Getter = S.LookupMethodInObjectType(GetterSelector, ContainerT, 1072 true /*instance*/); 1073 if (!Getter) 1074 return; 1075 QualType T = Getter->param_begin()[0]->getType(); 1076 S.CheckObjCARCConversion(Key->getSourceRange(), 1077 T, Key, Sema::CCK_ImplicitConversion); 1078 } 1079 1080 bool ObjCSubscriptOpBuilder::findAtIndexGetter() { 1081 if (AtIndexGetter) 1082 return true; 1083 1084 Expr *BaseExpr = RefExpr->getBaseExpr(); 1085 QualType BaseT = BaseExpr->getType(); 1086 1087 QualType ResultType; 1088 if (const ObjCObjectPointerType *PTy = 1089 BaseT->getAs<ObjCObjectPointerType>()) { 1090 ResultType = PTy->getPointeeType(); 1091 if (const ObjCObjectType *iQFaceTy = 1092 ResultType->getAsObjCQualifiedInterfaceType()) 1093 ResultType = iQFaceTy->getBaseType(); 1094 } 1095 Sema::ObjCSubscriptKind Res = 1096 S.CheckSubscriptingKind(RefExpr->getKeyExpr()); 1097 if (Res == Sema::OS_Error) { 1098 if (S.getLangOpts().ObjCAutoRefCount) 1099 CheckKeyForObjCARCConversion(S, ResultType, 1100 RefExpr->getKeyExpr()); 1101 return false; 1102 } 1103 bool arrayRef = (Res == Sema::OS_Array); 1104 1105 if (ResultType.isNull()) { 1106 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type) 1107 << BaseExpr->getType() << arrayRef; 1108 return false; 1109 } 1110 if (!arrayRef) { 1111 // dictionary subscripting. 1112 // - (id)objectForKeyedSubscript:(id)key; 1113 IdentifierInfo *KeyIdents[] = { 1114 &S.Context.Idents.get("objectForKeyedSubscript") 1115 }; 1116 AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents); 1117 } 1118 else { 1119 // - (id)objectAtIndexedSubscript:(size_t)index; 1120 IdentifierInfo *KeyIdents[] = { 1121 &S.Context.Idents.get("objectAtIndexedSubscript") 1122 }; 1123 1124 AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents); 1125 } 1126 1127 AtIndexGetter = S.LookupMethodInObjectType(AtIndexGetterSelector, ResultType, 1128 true /*instance*/); 1129 bool receiverIdType = (BaseT->isObjCIdType() || 1130 BaseT->isObjCQualifiedIdType()); 1131 1132 if (!AtIndexGetter && S.getLangOpts().DebuggerObjCLiteral) { 1133 AtIndexGetter = ObjCMethodDecl::Create(S.Context, SourceLocation(), 1134 SourceLocation(), AtIndexGetterSelector, 1135 S.Context.getObjCIdType() /*ReturnType*/, 1136 0 /*TypeSourceInfo */, 1137 S.Context.getTranslationUnitDecl(), 1138 true /*Instance*/, false/*isVariadic*/, 1139 /*isPropertyAccessor=*/false, 1140 /*isImplicitlyDeclared=*/true, /*isDefined=*/false, 1141 ObjCMethodDecl::Required, 1142 false); 1143 ParmVarDecl *Argument = ParmVarDecl::Create(S.Context, AtIndexGetter, 1144 SourceLocation(), SourceLocation(), 1145 arrayRef ? &S.Context.Idents.get("index") 1146 : &S.Context.Idents.get("key"), 1147 arrayRef ? S.Context.UnsignedLongTy 1148 : S.Context.getObjCIdType(), 1149 /*TInfo=*/0, 1150 SC_None, 1151 0); 1152 AtIndexGetter->setMethodParams(S.Context, Argument, None); 1153 } 1154 1155 if (!AtIndexGetter) { 1156 if (!receiverIdType) { 1157 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_method_not_found) 1158 << BaseExpr->getType() << 0 << arrayRef; 1159 return false; 1160 } 1161 AtIndexGetter = 1162 S.LookupInstanceMethodInGlobalPool(AtIndexGetterSelector, 1163 RefExpr->getSourceRange(), 1164 true, false); 1165 } 1166 1167 if (AtIndexGetter) { 1168 QualType T = AtIndexGetter->param_begin()[0]->getType(); 1169 if ((arrayRef && !T->isIntegralOrEnumerationType()) || 1170 (!arrayRef && !T->isObjCObjectPointerType())) { 1171 S.Diag(RefExpr->getKeyExpr()->getExprLoc(), 1172 arrayRef ? diag::err_objc_subscript_index_type 1173 : diag::err_objc_subscript_key_type) << T; 1174 S.Diag(AtIndexGetter->param_begin()[0]->getLocation(), 1175 diag::note_parameter_type) << T; 1176 return false; 1177 } 1178 QualType R = AtIndexGetter->getReturnType(); 1179 if (!R->isObjCObjectPointerType()) { 1180 S.Diag(RefExpr->getKeyExpr()->getExprLoc(), 1181 diag::err_objc_indexing_method_result_type) << R << arrayRef; 1182 S.Diag(AtIndexGetter->getLocation(), diag::note_method_declared_at) << 1183 AtIndexGetter->getDeclName(); 1184 } 1185 } 1186 return true; 1187 } 1188 1189 bool ObjCSubscriptOpBuilder::findAtIndexSetter() { 1190 if (AtIndexSetter) 1191 return true; 1192 1193 Expr *BaseExpr = RefExpr->getBaseExpr(); 1194 QualType BaseT = BaseExpr->getType(); 1195 1196 QualType ResultType; 1197 if (const ObjCObjectPointerType *PTy = 1198 BaseT->getAs<ObjCObjectPointerType>()) { 1199 ResultType = PTy->getPointeeType(); 1200 if (const ObjCObjectType *iQFaceTy = 1201 ResultType->getAsObjCQualifiedInterfaceType()) 1202 ResultType = iQFaceTy->getBaseType(); 1203 } 1204 1205 Sema::ObjCSubscriptKind Res = 1206 S.CheckSubscriptingKind(RefExpr->getKeyExpr()); 1207 if (Res == Sema::OS_Error) { 1208 if (S.getLangOpts().ObjCAutoRefCount) 1209 CheckKeyForObjCARCConversion(S, ResultType, 1210 RefExpr->getKeyExpr()); 1211 return false; 1212 } 1213 bool arrayRef = (Res == Sema::OS_Array); 1214 1215 if (ResultType.isNull()) { 1216 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type) 1217 << BaseExpr->getType() << arrayRef; 1218 return false; 1219 } 1220 1221 if (!arrayRef) { 1222 // dictionary subscripting. 1223 // - (void)setObject:(id)object forKeyedSubscript:(id)key; 1224 IdentifierInfo *KeyIdents[] = { 1225 &S.Context.Idents.get("setObject"), 1226 &S.Context.Idents.get("forKeyedSubscript") 1227 }; 1228 AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents); 1229 } 1230 else { 1231 // - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index; 1232 IdentifierInfo *KeyIdents[] = { 1233 &S.Context.Idents.get("setObject"), 1234 &S.Context.Idents.get("atIndexedSubscript") 1235 }; 1236 AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents); 1237 } 1238 AtIndexSetter = S.LookupMethodInObjectType(AtIndexSetterSelector, ResultType, 1239 true /*instance*/); 1240 1241 bool receiverIdType = (BaseT->isObjCIdType() || 1242 BaseT->isObjCQualifiedIdType()); 1243 1244 if (!AtIndexSetter && S.getLangOpts().DebuggerObjCLiteral) { 1245 TypeSourceInfo *ReturnTInfo = 0; 1246 QualType ReturnType = S.Context.VoidTy; 1247 AtIndexSetter = ObjCMethodDecl::Create( 1248 S.Context, SourceLocation(), SourceLocation(), AtIndexSetterSelector, 1249 ReturnType, ReturnTInfo, S.Context.getTranslationUnitDecl(), 1250 true /*Instance*/, false /*isVariadic*/, 1251 /*isPropertyAccessor=*/false, 1252 /*isImplicitlyDeclared=*/true, /*isDefined=*/false, 1253 ObjCMethodDecl::Required, false); 1254 SmallVector<ParmVarDecl *, 2> Params; 1255 ParmVarDecl *object = ParmVarDecl::Create(S.Context, AtIndexSetter, 1256 SourceLocation(), SourceLocation(), 1257 &S.Context.Idents.get("object"), 1258 S.Context.getObjCIdType(), 1259 /*TInfo=*/0, 1260 SC_None, 1261 0); 1262 Params.push_back(object); 1263 ParmVarDecl *key = ParmVarDecl::Create(S.Context, AtIndexSetter, 1264 SourceLocation(), SourceLocation(), 1265 arrayRef ? &S.Context.Idents.get("index") 1266 : &S.Context.Idents.get("key"), 1267 arrayRef ? S.Context.UnsignedLongTy 1268 : S.Context.getObjCIdType(), 1269 /*TInfo=*/0, 1270 SC_None, 1271 0); 1272 Params.push_back(key); 1273 AtIndexSetter->setMethodParams(S.Context, Params, None); 1274 } 1275 1276 if (!AtIndexSetter) { 1277 if (!receiverIdType) { 1278 S.Diag(BaseExpr->getExprLoc(), 1279 diag::err_objc_subscript_method_not_found) 1280 << BaseExpr->getType() << 1 << arrayRef; 1281 return false; 1282 } 1283 AtIndexSetter = 1284 S.LookupInstanceMethodInGlobalPool(AtIndexSetterSelector, 1285 RefExpr->getSourceRange(), 1286 true, false); 1287 } 1288 1289 bool err = false; 1290 if (AtIndexSetter && arrayRef) { 1291 QualType T = AtIndexSetter->param_begin()[1]->getType(); 1292 if (!T->isIntegralOrEnumerationType()) { 1293 S.Diag(RefExpr->getKeyExpr()->getExprLoc(), 1294 diag::err_objc_subscript_index_type) << T; 1295 S.Diag(AtIndexSetter->param_begin()[1]->getLocation(), 1296 diag::note_parameter_type) << T; 1297 err = true; 1298 } 1299 T = AtIndexSetter->param_begin()[0]->getType(); 1300 if (!T->isObjCObjectPointerType()) { 1301 S.Diag(RefExpr->getBaseExpr()->getExprLoc(), 1302 diag::err_objc_subscript_object_type) << T << arrayRef; 1303 S.Diag(AtIndexSetter->param_begin()[0]->getLocation(), 1304 diag::note_parameter_type) << T; 1305 err = true; 1306 } 1307 } 1308 else if (AtIndexSetter && !arrayRef) 1309 for (unsigned i=0; i <2; i++) { 1310 QualType T = AtIndexSetter->param_begin()[i]->getType(); 1311 if (!T->isObjCObjectPointerType()) { 1312 if (i == 1) 1313 S.Diag(RefExpr->getKeyExpr()->getExprLoc(), 1314 diag::err_objc_subscript_key_type) << T; 1315 else 1316 S.Diag(RefExpr->getBaseExpr()->getExprLoc(), 1317 diag::err_objc_subscript_dic_object_type) << T; 1318 S.Diag(AtIndexSetter->param_begin()[i]->getLocation(), 1319 diag::note_parameter_type) << T; 1320 err = true; 1321 } 1322 } 1323 1324 return !err; 1325 } 1326 1327 // Get the object at "Index" position in the container. 1328 // [BaseExpr objectAtIndexedSubscript : IndexExpr]; 1329 ExprResult ObjCSubscriptOpBuilder::buildGet() { 1330 if (!findAtIndexGetter()) 1331 return ExprError(); 1332 1333 QualType receiverType = InstanceBase->getType(); 1334 1335 // Build a message-send. 1336 ExprResult msg; 1337 Expr *Index = InstanceKey; 1338 1339 // Arguments. 1340 Expr *args[] = { Index }; 1341 assert(InstanceBase); 1342 msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType, 1343 GenericLoc, 1344 AtIndexGetterSelector, AtIndexGetter, 1345 MultiExprArg(args, 1)); 1346 return msg; 1347 } 1348 1349 /// Store into the container the "op" object at "Index"'ed location 1350 /// by building this messaging expression: 1351 /// - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index; 1352 /// \param captureSetValueAsResult If true, capture the actual 1353 /// value being set as the value of the property operation. 1354 ExprResult ObjCSubscriptOpBuilder::buildSet(Expr *op, SourceLocation opcLoc, 1355 bool captureSetValueAsResult) { 1356 if (!findAtIndexSetter()) 1357 return ExprError(); 1358 1359 QualType receiverType = InstanceBase->getType(); 1360 Expr *Index = InstanceKey; 1361 1362 // Arguments. 1363 Expr *args[] = { op, Index }; 1364 1365 // Build a message-send. 1366 ExprResult msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType, 1367 GenericLoc, 1368 AtIndexSetterSelector, 1369 AtIndexSetter, 1370 MultiExprArg(args, 2)); 1371 1372 if (!msg.isInvalid() && captureSetValueAsResult) { 1373 ObjCMessageExpr *msgExpr = 1374 cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit()); 1375 Expr *arg = msgExpr->getArg(0); 1376 if (CanCaptureValue(arg)) 1377 msgExpr->setArg(0, captureValueAsResult(arg)); 1378 } 1379 1380 return msg; 1381 } 1382 1383 //===----------------------------------------------------------------------===// 1384 // MSVC __declspec(property) references 1385 //===----------------------------------------------------------------------===// 1386 1387 Expr *MSPropertyOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) { 1388 Expr *NewBase = capture(RefExpr->getBaseExpr()); 1389 1390 syntacticBase = 1391 MSPropertyRefRebuilder(S, NewBase).rebuild(syntacticBase); 1392 1393 return syntacticBase; 1394 } 1395 1396 ExprResult MSPropertyOpBuilder::buildGet() { 1397 if (!RefExpr->getPropertyDecl()->hasGetter()) { 1398 S.Diag(RefExpr->getMemberLoc(), diag::err_no_accessor_for_property) 1399 << 0 /* getter */ << RefExpr->getPropertyDecl(); 1400 return ExprError(); 1401 } 1402 1403 UnqualifiedId GetterName; 1404 IdentifierInfo *II = RefExpr->getPropertyDecl()->getGetterId(); 1405 GetterName.setIdentifier(II, RefExpr->getMemberLoc()); 1406 CXXScopeSpec SS; 1407 SS.Adopt(RefExpr->getQualifierLoc()); 1408 ExprResult GetterExpr = S.ActOnMemberAccessExpr( 1409 S.getCurScope(), RefExpr->getBaseExpr(), SourceLocation(), 1410 RefExpr->isArrow() ? tok::arrow : tok::period, SS, SourceLocation(), 1411 GetterName, 0, true); 1412 if (GetterExpr.isInvalid()) { 1413 S.Diag(RefExpr->getMemberLoc(), 1414 diag::error_cannot_find_suitable_accessor) << 0 /* getter */ 1415 << RefExpr->getPropertyDecl(); 1416 return ExprError(); 1417 } 1418 1419 MultiExprArg ArgExprs; 1420 return S.ActOnCallExpr(S.getCurScope(), GetterExpr.take(), 1421 RefExpr->getSourceRange().getBegin(), ArgExprs, 1422 RefExpr->getSourceRange().getEnd()); 1423 } 1424 1425 ExprResult MSPropertyOpBuilder::buildSet(Expr *op, SourceLocation sl, 1426 bool captureSetValueAsResult) { 1427 if (!RefExpr->getPropertyDecl()->hasSetter()) { 1428 S.Diag(RefExpr->getMemberLoc(), diag::err_no_accessor_for_property) 1429 << 1 /* setter */ << RefExpr->getPropertyDecl(); 1430 return ExprError(); 1431 } 1432 1433 UnqualifiedId SetterName; 1434 IdentifierInfo *II = RefExpr->getPropertyDecl()->getSetterId(); 1435 SetterName.setIdentifier(II, RefExpr->getMemberLoc()); 1436 CXXScopeSpec SS; 1437 SS.Adopt(RefExpr->getQualifierLoc()); 1438 ExprResult SetterExpr = S.ActOnMemberAccessExpr( 1439 S.getCurScope(), RefExpr->getBaseExpr(), SourceLocation(), 1440 RefExpr->isArrow() ? tok::arrow : tok::period, SS, SourceLocation(), 1441 SetterName, 0, true); 1442 if (SetterExpr.isInvalid()) { 1443 S.Diag(RefExpr->getMemberLoc(), 1444 diag::error_cannot_find_suitable_accessor) << 1 /* setter */ 1445 << RefExpr->getPropertyDecl(); 1446 return ExprError(); 1447 } 1448 1449 SmallVector<Expr*, 1> ArgExprs; 1450 ArgExprs.push_back(op); 1451 return S.ActOnCallExpr(S.getCurScope(), SetterExpr.take(), 1452 RefExpr->getSourceRange().getBegin(), ArgExprs, 1453 op->getSourceRange().getEnd()); 1454 } 1455 1456 //===----------------------------------------------------------------------===// 1457 // General Sema routines. 1458 //===----------------------------------------------------------------------===// 1459 1460 ExprResult Sema::checkPseudoObjectRValue(Expr *E) { 1461 Expr *opaqueRef = E->IgnoreParens(); 1462 if (ObjCPropertyRefExpr *refExpr 1463 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) { 1464 ObjCPropertyOpBuilder builder(*this, refExpr); 1465 return builder.buildRValueOperation(E); 1466 } 1467 else if (ObjCSubscriptRefExpr *refExpr 1468 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) { 1469 ObjCSubscriptOpBuilder builder(*this, refExpr); 1470 return builder.buildRValueOperation(E); 1471 } else if (MSPropertyRefExpr *refExpr 1472 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) { 1473 MSPropertyOpBuilder builder(*this, refExpr); 1474 return builder.buildRValueOperation(E); 1475 } else { 1476 llvm_unreachable("unknown pseudo-object kind!"); 1477 } 1478 } 1479 1480 /// Check an increment or decrement of a pseudo-object expression. 1481 ExprResult Sema::checkPseudoObjectIncDec(Scope *Sc, SourceLocation opcLoc, 1482 UnaryOperatorKind opcode, Expr *op) { 1483 // Do nothing if the operand is dependent. 1484 if (op->isTypeDependent()) 1485 return new (Context) UnaryOperator(op, opcode, Context.DependentTy, 1486 VK_RValue, OK_Ordinary, opcLoc); 1487 1488 assert(UnaryOperator::isIncrementDecrementOp(opcode)); 1489 Expr *opaqueRef = op->IgnoreParens(); 1490 if (ObjCPropertyRefExpr *refExpr 1491 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) { 1492 ObjCPropertyOpBuilder builder(*this, refExpr); 1493 return builder.buildIncDecOperation(Sc, opcLoc, opcode, op); 1494 } else if (isa<ObjCSubscriptRefExpr>(opaqueRef)) { 1495 Diag(opcLoc, diag::err_illegal_container_subscripting_op); 1496 return ExprError(); 1497 } else if (MSPropertyRefExpr *refExpr 1498 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) { 1499 MSPropertyOpBuilder builder(*this, refExpr); 1500 return builder.buildIncDecOperation(Sc, opcLoc, opcode, op); 1501 } else { 1502 llvm_unreachable("unknown pseudo-object kind!"); 1503 } 1504 } 1505 1506 ExprResult Sema::checkPseudoObjectAssignment(Scope *S, SourceLocation opcLoc, 1507 BinaryOperatorKind opcode, 1508 Expr *LHS, Expr *RHS) { 1509 // Do nothing if either argument is dependent. 1510 if (LHS->isTypeDependent() || RHS->isTypeDependent()) 1511 return new (Context) BinaryOperator(LHS, RHS, opcode, Context.DependentTy, 1512 VK_RValue, OK_Ordinary, opcLoc, false); 1513 1514 // Filter out non-overload placeholder types in the RHS. 1515 if (RHS->getType()->isNonOverloadPlaceholderType()) { 1516 ExprResult result = CheckPlaceholderExpr(RHS); 1517 if (result.isInvalid()) return ExprError(); 1518 RHS = result.take(); 1519 } 1520 1521 Expr *opaqueRef = LHS->IgnoreParens(); 1522 if (ObjCPropertyRefExpr *refExpr 1523 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) { 1524 ObjCPropertyOpBuilder builder(*this, refExpr); 1525 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS); 1526 } else if (ObjCSubscriptRefExpr *refExpr 1527 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) { 1528 ObjCSubscriptOpBuilder builder(*this, refExpr); 1529 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS); 1530 } else if (MSPropertyRefExpr *refExpr 1531 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) { 1532 MSPropertyOpBuilder builder(*this, refExpr); 1533 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS); 1534 } else { 1535 llvm_unreachable("unknown pseudo-object kind!"); 1536 } 1537 } 1538 1539 /// Given a pseudo-object reference, rebuild it without the opaque 1540 /// values. Basically, undo the behavior of rebuildAndCaptureObject. 1541 /// This should never operate in-place. 1542 static Expr *stripOpaqueValuesFromPseudoObjectRef(Sema &S, Expr *E) { 1543 Expr *opaqueRef = E->IgnoreParens(); 1544 if (ObjCPropertyRefExpr *refExpr 1545 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) { 1546 // Class and super property references don't have opaque values in them. 1547 if (refExpr->isClassReceiver() || refExpr->isSuperReceiver()) 1548 return E; 1549 1550 assert(refExpr->isObjectReceiver() && "Unknown receiver kind?"); 1551 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBase()); 1552 return ObjCPropertyRefRebuilder(S, baseOVE->getSourceExpr()).rebuild(E); 1553 } else if (ObjCSubscriptRefExpr *refExpr 1554 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) { 1555 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBaseExpr()); 1556 OpaqueValueExpr *keyOVE = cast<OpaqueValueExpr>(refExpr->getKeyExpr()); 1557 return ObjCSubscriptRefRebuilder(S, baseOVE->getSourceExpr(), 1558 keyOVE->getSourceExpr()).rebuild(E); 1559 } else if (MSPropertyRefExpr *refExpr 1560 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) { 1561 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBaseExpr()); 1562 return MSPropertyRefRebuilder(S, baseOVE->getSourceExpr()).rebuild(E); 1563 } else { 1564 llvm_unreachable("unknown pseudo-object kind!"); 1565 } 1566 } 1567 1568 /// Given a pseudo-object expression, recreate what it looks like 1569 /// syntactically without the attendant OpaqueValueExprs. 1570 /// 1571 /// This is a hack which should be removed when TreeTransform is 1572 /// capable of rebuilding a tree without stripping implicit 1573 /// operations. 1574 Expr *Sema::recreateSyntacticForm(PseudoObjectExpr *E) { 1575 Expr *syntax = E->getSyntacticForm(); 1576 if (UnaryOperator *uop = dyn_cast<UnaryOperator>(syntax)) { 1577 Expr *op = stripOpaqueValuesFromPseudoObjectRef(*this, uop->getSubExpr()); 1578 return new (Context) UnaryOperator(op, uop->getOpcode(), uop->getType(), 1579 uop->getValueKind(), uop->getObjectKind(), 1580 uop->getOperatorLoc()); 1581 } else if (CompoundAssignOperator *cop 1582 = dyn_cast<CompoundAssignOperator>(syntax)) { 1583 Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, cop->getLHS()); 1584 Expr *rhs = cast<OpaqueValueExpr>(cop->getRHS())->getSourceExpr(); 1585 return new (Context) CompoundAssignOperator(lhs, rhs, cop->getOpcode(), 1586 cop->getType(), 1587 cop->getValueKind(), 1588 cop->getObjectKind(), 1589 cop->getComputationLHSType(), 1590 cop->getComputationResultType(), 1591 cop->getOperatorLoc(), false); 1592 } else if (BinaryOperator *bop = dyn_cast<BinaryOperator>(syntax)) { 1593 Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, bop->getLHS()); 1594 Expr *rhs = cast<OpaqueValueExpr>(bop->getRHS())->getSourceExpr(); 1595 return new (Context) BinaryOperator(lhs, rhs, bop->getOpcode(), 1596 bop->getType(), bop->getValueKind(), 1597 bop->getObjectKind(), 1598 bop->getOperatorLoc(), false); 1599 } else { 1600 assert(syntax->hasPlaceholderType(BuiltinType::PseudoObject)); 1601 return stripOpaqueValuesFromPseudoObjectRef(*this, syntax); 1602 } 1603 } 1604