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