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