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