blob: 19cb12c73b3dceffc70411af1f7e55396889502b [file] [log] [blame]
John McCall526ab472011-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"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000034#include "clang/AST/ExprCXX.h"
John McCall526ab472011-10-25 17:37:35 +000035#include "clang/AST/ExprObjC.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000036#include "clang/Basic/CharInfo.h"
John McCall526ab472011-10-25 17:37:35 +000037#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "clang/Sema/Initialization.h"
39#include "clang/Sema/ScopeInfo.h"
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +000040#include "llvm/ADT/SmallString.h"
John McCall526ab472011-10-25 17:37:35 +000041
42using namespace clang;
43using namespace sema;
44
John McCallfe96e0b2011-11-06 09:01:30 +000045namespace {
46 // Basically just a very focused copy of TreeTransform.
47 template <class T> struct Rebuilder {
48 Sema &S;
49 Rebuilder(Sema &S) : S(S) {}
50
51 T &getDerived() { return static_cast<T&>(*this); }
52
53 Expr *rebuild(Expr *e) {
54 // Fast path: nothing to look through.
55 if (typename T::specific_type *specific
56 = dyn_cast<typename T::specific_type>(e))
57 return getDerived().rebuildSpecific(specific);
58
59 // Otherwise, we should look through and rebuild anything that
60 // IgnoreParens would.
61
62 if (ParenExpr *parens = dyn_cast<ParenExpr>(e)) {
63 e = rebuild(parens->getSubExpr());
64 return new (S.Context) ParenExpr(parens->getLParen(),
65 parens->getRParen(),
66 e);
67 }
68
69 if (UnaryOperator *uop = dyn_cast<UnaryOperator>(e)) {
70 assert(uop->getOpcode() == UO_Extension);
71 e = rebuild(uop->getSubExpr());
72 return new (S.Context) UnaryOperator(e, uop->getOpcode(),
73 uop->getType(),
74 uop->getValueKind(),
75 uop->getObjectKind(),
76 uop->getOperatorLoc());
77 }
78
79 if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
80 assert(!gse->isResultDependent());
81 unsigned resultIndex = gse->getResultIndex();
82 unsigned numAssocs = gse->getNumAssocs();
83
84 SmallVector<Expr*, 8> assocs(numAssocs);
85 SmallVector<TypeSourceInfo*, 8> assocTypes(numAssocs);
86
87 for (unsigned i = 0; i != numAssocs; ++i) {
88 Expr *assoc = gse->getAssocExpr(i);
89 if (i == resultIndex) assoc = rebuild(assoc);
90 assocs[i] = assoc;
91 assocTypes[i] = gse->getAssocTypeSourceInfo(i);
92 }
93
94 return new (S.Context) GenericSelectionExpr(S.Context,
95 gse->getGenericLoc(),
96 gse->getControllingExpr(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000097 assocTypes,
98 assocs,
John McCallfe96e0b2011-11-06 09:01:30 +000099 gse->getDefaultLoc(),
100 gse->getRParenLoc(),
101 gse->containsUnexpandedParameterPack(),
102 resultIndex);
103 }
104
Eli Friedman75807f22013-07-20 00:40:58 +0000105 if (ChooseExpr *ce = dyn_cast<ChooseExpr>(e)) {
106 assert(!ce->isConditionDependent());
107
108 Expr *LHS = ce->getLHS(), *RHS = ce->getRHS();
109 Expr *&rebuiltExpr = ce->isConditionTrue() ? LHS : RHS;
110 rebuiltExpr = rebuild(rebuiltExpr);
111
112 return new (S.Context) ChooseExpr(ce->getBuiltinLoc(),
113 ce->getCond(),
114 LHS, RHS,
115 rebuiltExpr->getType(),
116 rebuiltExpr->getValueKind(),
117 rebuiltExpr->getObjectKind(),
118 ce->getRParenLoc(),
119 ce->isConditionTrue(),
120 rebuiltExpr->isTypeDependent(),
121 rebuiltExpr->isValueDependent());
122 }
123
John McCallfe96e0b2011-11-06 09:01:30 +0000124 llvm_unreachable("bad expression to rebuild!");
125 }
126 };
127
128 struct ObjCPropertyRefRebuilder : Rebuilder<ObjCPropertyRefRebuilder> {
129 Expr *NewBase;
130 ObjCPropertyRefRebuilder(Sema &S, Expr *newBase)
Benjamin Kramer5c29d692011-11-06 09:50:13 +0000131 : Rebuilder<ObjCPropertyRefRebuilder>(S), NewBase(newBase) {}
John McCallfe96e0b2011-11-06 09:01:30 +0000132
133 typedef ObjCPropertyRefExpr specific_type;
134 Expr *rebuildSpecific(ObjCPropertyRefExpr *refExpr) {
135 // Fortunately, the constraint that we're rebuilding something
136 // with a base limits the number of cases here.
Eli Friedmanfd41aee2012-11-29 03:13:49 +0000137 assert(refExpr->isObjectReceiver());
John McCallfe96e0b2011-11-06 09:01:30 +0000138
139 if (refExpr->isExplicitProperty()) {
140 return new (S.Context)
141 ObjCPropertyRefExpr(refExpr->getExplicitProperty(),
142 refExpr->getType(), refExpr->getValueKind(),
143 refExpr->getObjectKind(), refExpr->getLocation(),
144 NewBase);
145 }
146 return new (S.Context)
147 ObjCPropertyRefExpr(refExpr->getImplicitPropertyGetter(),
148 refExpr->getImplicitPropertySetter(),
149 refExpr->getType(), refExpr->getValueKind(),
150 refExpr->getObjectKind(),refExpr->getLocation(),
151 NewBase);
152 }
153 };
154
Ted Kremeneke65b0862012-03-06 20:05:56 +0000155 struct ObjCSubscriptRefRebuilder : Rebuilder<ObjCSubscriptRefRebuilder> {
156 Expr *NewBase;
157 Expr *NewKeyExpr;
158 ObjCSubscriptRefRebuilder(Sema &S, Expr *newBase, Expr *newKeyExpr)
159 : Rebuilder<ObjCSubscriptRefRebuilder>(S),
160 NewBase(newBase), NewKeyExpr(newKeyExpr) {}
161
162 typedef ObjCSubscriptRefExpr specific_type;
163 Expr *rebuildSpecific(ObjCSubscriptRefExpr *refExpr) {
164 assert(refExpr->getBaseExpr());
165 assert(refExpr->getKeyExpr());
166
167 return new (S.Context)
168 ObjCSubscriptRefExpr(NewBase,
169 NewKeyExpr,
170 refExpr->getType(), refExpr->getValueKind(),
171 refExpr->getObjectKind(),refExpr->getAtIndexMethodDecl(),
172 refExpr->setAtIndexMethodDecl(),
173 refExpr->getRBracket());
174 }
175 };
John McCall5e77d762013-04-16 07:28:30 +0000176
177 struct MSPropertyRefRebuilder : Rebuilder<MSPropertyRefRebuilder> {
178 Expr *NewBase;
179 MSPropertyRefRebuilder(Sema &S, Expr *newBase)
180 : Rebuilder<MSPropertyRefRebuilder>(S), NewBase(newBase) {}
181
182 typedef MSPropertyRefExpr specific_type;
183 Expr *rebuildSpecific(MSPropertyRefExpr *refExpr) {
184 assert(refExpr->getBaseExpr());
185
186 return new (S.Context)
187 MSPropertyRefExpr(NewBase, refExpr->getPropertyDecl(),
188 refExpr->isArrow(), refExpr->getType(),
189 refExpr->getValueKind(), refExpr->getQualifierLoc(),
190 refExpr->getMemberLoc());
191 }
192 };
Ted Kremeneke65b0862012-03-06 20:05:56 +0000193
John McCallfe96e0b2011-11-06 09:01:30 +0000194 class PseudoOpBuilder {
195 public:
196 Sema &S;
197 unsigned ResultIndex;
198 SourceLocation GenericLoc;
199 SmallVector<Expr *, 4> Semantics;
200
201 PseudoOpBuilder(Sema &S, SourceLocation genericLoc)
202 : S(S), ResultIndex(PseudoObjectExpr::NoResult),
203 GenericLoc(genericLoc) {}
204
Matt Beaumont-Gayfb3cb9a2011-11-08 01:53:17 +0000205 virtual ~PseudoOpBuilder() {}
206
John McCallfe96e0b2011-11-06 09:01:30 +0000207 /// Add a normal semantic expression.
208 void addSemanticExpr(Expr *semantic) {
209 Semantics.push_back(semantic);
210 }
211
212 /// Add the 'result' semantic expression.
213 void addResultSemanticExpr(Expr *resultExpr) {
214 assert(ResultIndex == PseudoObjectExpr::NoResult);
215 ResultIndex = Semantics.size();
216 Semantics.push_back(resultExpr);
217 }
218
219 ExprResult buildRValueOperation(Expr *op);
220 ExprResult buildAssignmentOperation(Scope *Sc,
221 SourceLocation opLoc,
222 BinaryOperatorKind opcode,
223 Expr *LHS, Expr *RHS);
224 ExprResult buildIncDecOperation(Scope *Sc, SourceLocation opLoc,
225 UnaryOperatorKind opcode,
226 Expr *op);
227
Jordan Rosed3934582012-09-28 22:21:30 +0000228 virtual ExprResult complete(Expr *syntacticForm);
John McCallfe96e0b2011-11-06 09:01:30 +0000229
230 OpaqueValueExpr *capture(Expr *op);
231 OpaqueValueExpr *captureValueAsResult(Expr *op);
232
233 void setResultToLastSemantic() {
234 assert(ResultIndex == PseudoObjectExpr::NoResult);
235 ResultIndex = Semantics.size() - 1;
236 }
237
238 /// Return true if assignments have a non-void result.
Fariborz Jahanian15dde892014-03-06 00:34:05 +0000239 bool CanCaptureValue(Expr *exp) {
240 if (exp->isGLValue())
241 return true;
242 QualType ty = exp->getType();
Eli Friedman00fa4292012-11-13 23:16:33 +0000243 assert(!ty->isIncompleteType());
244 assert(!ty->isDependentType());
245
246 if (const CXXRecordDecl *ClassDecl = ty->getAsCXXRecordDecl())
247 return ClassDecl->isTriviallyCopyable();
248 return true;
249 }
John McCallfe96e0b2011-11-06 09:01:30 +0000250
251 virtual Expr *rebuildAndCaptureObject(Expr *) = 0;
252 virtual ExprResult buildGet() = 0;
253 virtual ExprResult buildSet(Expr *, SourceLocation,
254 bool captureSetValueAsResult) = 0;
255 };
256
Dmitri Gribenko00bcdd32012-09-12 17:01:48 +0000257 /// A PseudoOpBuilder for Objective-C \@properties.
John McCallfe96e0b2011-11-06 09:01:30 +0000258 class ObjCPropertyOpBuilder : public PseudoOpBuilder {
259 ObjCPropertyRefExpr *RefExpr;
Argyrios Kyrtzidisab468b02012-03-30 00:19:18 +0000260 ObjCPropertyRefExpr *SyntacticRefExpr;
John McCallfe96e0b2011-11-06 09:01:30 +0000261 OpaqueValueExpr *InstanceReceiver;
262 ObjCMethodDecl *Getter;
263
264 ObjCMethodDecl *Setter;
265 Selector SetterSelector;
Fariborz Jahanianb525b522012-04-18 19:13:23 +0000266 Selector GetterSelector;
John McCallfe96e0b2011-11-06 09:01:30 +0000267
268 public:
269 ObjCPropertyOpBuilder(Sema &S, ObjCPropertyRefExpr *refExpr) :
270 PseudoOpBuilder(S, refExpr->getLocation()), RefExpr(refExpr),
Craig Topperc3ec1492014-05-26 06:22:03 +0000271 SyntacticRefExpr(nullptr), InstanceReceiver(nullptr), Getter(nullptr),
272 Setter(nullptr) {
John McCallfe96e0b2011-11-06 09:01:30 +0000273 }
274
275 ExprResult buildRValueOperation(Expr *op);
276 ExprResult buildAssignmentOperation(Scope *Sc,
277 SourceLocation opLoc,
278 BinaryOperatorKind opcode,
279 Expr *LHS, Expr *RHS);
280 ExprResult buildIncDecOperation(Scope *Sc, SourceLocation opLoc,
281 UnaryOperatorKind opcode,
282 Expr *op);
283
284 bool tryBuildGetOfReference(Expr *op, ExprResult &result);
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000285 bool findSetter(bool warn=true);
John McCallfe96e0b2011-11-06 09:01:30 +0000286 bool findGetter();
Fariborz Jahanian55513282014-05-28 18:12:10 +0000287 bool DiagnoseUnsupportedPropertyUse();
John McCallfe96e0b2011-11-06 09:01:30 +0000288
Craig Toppere14c0f82014-03-12 04:55:44 +0000289 Expr *rebuildAndCaptureObject(Expr *syntacticBase) override;
290 ExprResult buildGet() override;
291 ExprResult buildSet(Expr *op, SourceLocation, bool) override;
292 ExprResult complete(Expr *SyntacticForm) override;
Jordan Rosed3934582012-09-28 22:21:30 +0000293
294 bool isWeakProperty() const;
John McCallfe96e0b2011-11-06 09:01:30 +0000295 };
Ted Kremeneke65b0862012-03-06 20:05:56 +0000296
297 /// A PseudoOpBuilder for Objective-C array/dictionary indexing.
298 class ObjCSubscriptOpBuilder : public PseudoOpBuilder {
299 ObjCSubscriptRefExpr *RefExpr;
300 OpaqueValueExpr *InstanceBase;
301 OpaqueValueExpr *InstanceKey;
302 ObjCMethodDecl *AtIndexGetter;
303 Selector AtIndexGetterSelector;
304
305 ObjCMethodDecl *AtIndexSetter;
306 Selector AtIndexSetterSelector;
307
308 public:
309 ObjCSubscriptOpBuilder(Sema &S, ObjCSubscriptRefExpr *refExpr) :
310 PseudoOpBuilder(S, refExpr->getSourceRange().getBegin()),
311 RefExpr(refExpr),
Craig Topperc3ec1492014-05-26 06:22:03 +0000312 InstanceBase(nullptr), InstanceKey(nullptr),
313 AtIndexGetter(nullptr), AtIndexSetter(nullptr) {}
314
Ted Kremeneke65b0862012-03-06 20:05:56 +0000315 ExprResult buildRValueOperation(Expr *op);
316 ExprResult buildAssignmentOperation(Scope *Sc,
317 SourceLocation opLoc,
318 BinaryOperatorKind opcode,
319 Expr *LHS, Expr *RHS);
Craig Toppere14c0f82014-03-12 04:55:44 +0000320 Expr *rebuildAndCaptureObject(Expr *syntacticBase) override;
321
Ted Kremeneke65b0862012-03-06 20:05:56 +0000322 bool findAtIndexGetter();
323 bool findAtIndexSetter();
Craig Toppere14c0f82014-03-12 04:55:44 +0000324
325 ExprResult buildGet() override;
326 ExprResult buildSet(Expr *op, SourceLocation, bool) override;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000327 };
328
John McCall5e77d762013-04-16 07:28:30 +0000329 class MSPropertyOpBuilder : public PseudoOpBuilder {
330 MSPropertyRefExpr *RefExpr;
331
332 public:
333 MSPropertyOpBuilder(Sema &S, MSPropertyRefExpr *refExpr) :
334 PseudoOpBuilder(S, refExpr->getSourceRange().getBegin()),
335 RefExpr(refExpr) {}
336
Craig Toppere14c0f82014-03-12 04:55:44 +0000337 Expr *rebuildAndCaptureObject(Expr *) override;
338 ExprResult buildGet() override;
339 ExprResult buildSet(Expr *op, SourceLocation, bool) override;
John McCall5e77d762013-04-16 07:28:30 +0000340 };
John McCallfe96e0b2011-11-06 09:01:30 +0000341}
342
343/// Capture the given expression in an OpaqueValueExpr.
344OpaqueValueExpr *PseudoOpBuilder::capture(Expr *e) {
345 // Make a new OVE whose source is the given expression.
346 OpaqueValueExpr *captured =
347 new (S.Context) OpaqueValueExpr(GenericLoc, e->getType(),
Douglas Gregor2d5aea02012-02-23 22:17:26 +0000348 e->getValueKind(), e->getObjectKind(),
349 e);
John McCallfe96e0b2011-11-06 09:01:30 +0000350
351 // Make sure we bind that in the semantics.
352 addSemanticExpr(captured);
353 return captured;
354}
355
356/// Capture the given expression as the result of this pseudo-object
357/// operation. This routine is safe against expressions which may
358/// already be captured.
359///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +0000360/// \returns the captured expression, which will be the
John McCallfe96e0b2011-11-06 09:01:30 +0000361/// same as the input if the input was already captured
362OpaqueValueExpr *PseudoOpBuilder::captureValueAsResult(Expr *e) {
363 assert(ResultIndex == PseudoObjectExpr::NoResult);
364
365 // If the expression hasn't already been captured, just capture it
366 // and set the new semantic
367 if (!isa<OpaqueValueExpr>(e)) {
368 OpaqueValueExpr *cap = capture(e);
369 setResultToLastSemantic();
370 return cap;
371 }
372
373 // Otherwise, it must already be one of our semantic expressions;
374 // set ResultIndex to its index.
375 unsigned index = 0;
376 for (;; ++index) {
377 assert(index < Semantics.size() &&
378 "captured expression not found in semantics!");
379 if (e == Semantics[index]) break;
380 }
381 ResultIndex = index;
382 return cast<OpaqueValueExpr>(e);
383}
384
385/// The routine which creates the final PseudoObjectExpr.
386ExprResult PseudoOpBuilder::complete(Expr *syntactic) {
387 return PseudoObjectExpr::Create(S.Context, syntactic,
388 Semantics, ResultIndex);
389}
390
391/// The main skeleton for building an r-value operation.
392ExprResult PseudoOpBuilder::buildRValueOperation(Expr *op) {
393 Expr *syntacticBase = rebuildAndCaptureObject(op);
394
395 ExprResult getExpr = buildGet();
396 if (getExpr.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000397 addResultSemanticExpr(getExpr.get());
John McCallfe96e0b2011-11-06 09:01:30 +0000398
399 return complete(syntacticBase);
400}
401
402/// The basic skeleton for building a simple or compound
403/// assignment operation.
404ExprResult
405PseudoOpBuilder::buildAssignmentOperation(Scope *Sc, SourceLocation opcLoc,
406 BinaryOperatorKind opcode,
407 Expr *LHS, Expr *RHS) {
408 assert(BinaryOperator::isAssignmentOp(opcode));
409
410 Expr *syntacticLHS = rebuildAndCaptureObject(LHS);
411 OpaqueValueExpr *capturedRHS = capture(RHS);
412
413 Expr *syntactic;
414
415 ExprResult result;
416 if (opcode == BO_Assign) {
417 result = capturedRHS;
418 syntactic = new (S.Context) BinaryOperator(syntacticLHS, capturedRHS,
419 opcode, capturedRHS->getType(),
420 capturedRHS->getValueKind(),
Lang Hames5de91cc2012-10-02 04:45:10 +0000421 OK_Ordinary, opcLoc, false);
John McCallfe96e0b2011-11-06 09:01:30 +0000422 } else {
423 ExprResult opLHS = buildGet();
424 if (opLHS.isInvalid()) return ExprError();
425
426 // Build an ordinary, non-compound operation.
427 BinaryOperatorKind nonCompound =
428 BinaryOperator::getOpForCompoundAssignment(opcode);
429 result = S.BuildBinOp(Sc, opcLoc, nonCompound,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000430 opLHS.get(), capturedRHS);
John McCallfe96e0b2011-11-06 09:01:30 +0000431 if (result.isInvalid()) return ExprError();
432
433 syntactic =
434 new (S.Context) CompoundAssignOperator(syntacticLHS, capturedRHS, opcode,
435 result.get()->getType(),
436 result.get()->getValueKind(),
437 OK_Ordinary,
438 opLHS.get()->getType(),
439 result.get()->getType(),
Lang Hames5de91cc2012-10-02 04:45:10 +0000440 opcLoc, false);
John McCallfe96e0b2011-11-06 09:01:30 +0000441 }
442
443 // The result of the assignment, if not void, is the value set into
444 // the l-value.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000445 result = buildSet(result.get(), opcLoc, /*captureSetValueAsResult*/ true);
John McCallfe96e0b2011-11-06 09:01:30 +0000446 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000447 addSemanticExpr(result.get());
John McCallfe96e0b2011-11-06 09:01:30 +0000448
449 return complete(syntactic);
450}
451
452/// The basic skeleton for building an increment or decrement
453/// operation.
454ExprResult
455PseudoOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc,
456 UnaryOperatorKind opcode,
457 Expr *op) {
458 assert(UnaryOperator::isIncrementDecrementOp(opcode));
459
460 Expr *syntacticOp = rebuildAndCaptureObject(op);
461
462 // Load the value.
463 ExprResult result = buildGet();
464 if (result.isInvalid()) return ExprError();
465
466 QualType resultType = result.get()->getType();
467
468 // That's the postfix result.
John McCall0d9dd732013-04-16 22:32:04 +0000469 if (UnaryOperator::isPostfix(opcode) &&
Fariborz Jahanian15dde892014-03-06 00:34:05 +0000470 (result.get()->isTypeDependent() || CanCaptureValue(result.get()))) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000471 result = capture(result.get());
John McCallfe96e0b2011-11-06 09:01:30 +0000472 setResultToLastSemantic();
473 }
474
475 // Add or subtract a literal 1.
476 llvm::APInt oneV(S.Context.getTypeSize(S.Context.IntTy), 1);
477 Expr *one = IntegerLiteral::Create(S.Context, oneV, S.Context.IntTy,
478 GenericLoc);
479
480 if (UnaryOperator::isIncrementOp(opcode)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000481 result = S.BuildBinOp(Sc, opcLoc, BO_Add, result.get(), one);
John McCallfe96e0b2011-11-06 09:01:30 +0000482 } else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000483 result = S.BuildBinOp(Sc, opcLoc, BO_Sub, result.get(), one);
John McCallfe96e0b2011-11-06 09:01:30 +0000484 }
485 if (result.isInvalid()) return ExprError();
486
487 // Store that back into the result. The value stored is the result
488 // of a prefix operation.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000489 result = buildSet(result.get(), opcLoc, UnaryOperator::isPrefix(opcode));
John McCallfe96e0b2011-11-06 09:01:30 +0000490 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000491 addSemanticExpr(result.get());
John McCallfe96e0b2011-11-06 09:01:30 +0000492
493 UnaryOperator *syntactic =
494 new (S.Context) UnaryOperator(syntacticOp, opcode, resultType,
495 VK_LValue, OK_Ordinary, opcLoc);
496 return complete(syntactic);
497}
498
499
500//===----------------------------------------------------------------------===//
501// Objective-C @property and implicit property references
502//===----------------------------------------------------------------------===//
503
504/// Look up a method in the receiver type of an Objective-C property
505/// reference.
John McCall526ab472011-10-25 17:37:35 +0000506static ObjCMethodDecl *LookupMethodInReceiverType(Sema &S, Selector sel,
507 const ObjCPropertyRefExpr *PRE) {
John McCall526ab472011-10-25 17:37:35 +0000508 if (PRE->isObjectReceiver()) {
Benjamin Kramer8dc57602011-10-28 13:21:18 +0000509 const ObjCObjectPointerType *PT =
510 PRE->getBase()->getType()->castAs<ObjCObjectPointerType>();
John McCallfe96e0b2011-11-06 09:01:30 +0000511
512 // Special case for 'self' in class method implementations.
513 if (PT->isObjCClassType() &&
514 S.isSelfExpr(const_cast<Expr*>(PRE->getBase()))) {
515 // This cast is safe because isSelfExpr is only true within
516 // methods.
517 ObjCMethodDecl *method =
518 cast<ObjCMethodDecl>(S.CurContext->getNonClosureAncestor());
519 return S.LookupMethodInObjectType(sel,
520 S.Context.getObjCInterfaceType(method->getClassInterface()),
521 /*instance*/ false);
522 }
523
Benjamin Kramer8dc57602011-10-28 13:21:18 +0000524 return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true);
John McCall526ab472011-10-25 17:37:35 +0000525 }
526
Benjamin Kramer8dc57602011-10-28 13:21:18 +0000527 if (PRE->isSuperReceiver()) {
528 if (const ObjCObjectPointerType *PT =
529 PRE->getSuperReceiverType()->getAs<ObjCObjectPointerType>())
530 return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true);
531
532 return S.LookupMethodInObjectType(sel, PRE->getSuperReceiverType(), false);
533 }
534
535 assert(PRE->isClassReceiver() && "Invalid expression");
536 QualType IT = S.Context.getObjCInterfaceType(PRE->getClassReceiver());
537 return S.LookupMethodInObjectType(sel, IT, false);
John McCall526ab472011-10-25 17:37:35 +0000538}
539
Jordan Rosed3934582012-09-28 22:21:30 +0000540bool ObjCPropertyOpBuilder::isWeakProperty() const {
541 QualType T;
542 if (RefExpr->isExplicitProperty()) {
543 const ObjCPropertyDecl *Prop = RefExpr->getExplicitProperty();
544 if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
545 return true;
546
547 T = Prop->getType();
548 } else if (Getter) {
Alp Toker314cc812014-01-25 16:55:45 +0000549 T = Getter->getReturnType();
Jordan Rosed3934582012-09-28 22:21:30 +0000550 } else {
551 return false;
552 }
553
554 return T.getObjCLifetime() == Qualifiers::OCL_Weak;
555}
556
John McCallfe96e0b2011-11-06 09:01:30 +0000557bool ObjCPropertyOpBuilder::findGetter() {
558 if (Getter) return true;
John McCall526ab472011-10-25 17:37:35 +0000559
John McCallcfef5462011-11-07 22:49:50 +0000560 // For implicit properties, just trust the lookup we already did.
561 if (RefExpr->isImplicitProperty()) {
Fariborz Jahanianb525b522012-04-18 19:13:23 +0000562 if ((Getter = RefExpr->getImplicitPropertyGetter())) {
563 GetterSelector = Getter->getSelector();
564 return true;
565 }
566 else {
567 // Must build the getter selector the hard way.
568 ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter();
569 assert(setter && "both setter and getter are null - cannot happen");
570 IdentifierInfo *setterName =
571 setter->getSelector().getIdentifierInfoForSlot(0);
572 const char *compStr = setterName->getNameStart();
573 compStr += 3;
574 IdentifierInfo *getterName = &S.Context.Idents.get(compStr);
575 GetterSelector =
576 S.PP.getSelectorTable().getNullarySelector(getterName);
577 return false;
578
579 }
John McCallcfef5462011-11-07 22:49:50 +0000580 }
581
582 ObjCPropertyDecl *prop = RefExpr->getExplicitProperty();
583 Getter = LookupMethodInReceiverType(S, prop->getGetterName(), RefExpr);
Craig Topperc3ec1492014-05-26 06:22:03 +0000584 return (Getter != nullptr);
John McCallfe96e0b2011-11-06 09:01:30 +0000585}
586
587/// Try to find the most accurate setter declaration for the property
588/// reference.
589///
590/// \return true if a setter was found, in which case Setter
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000591bool ObjCPropertyOpBuilder::findSetter(bool warn) {
John McCallfe96e0b2011-11-06 09:01:30 +0000592 // For implicit properties, just trust the lookup we already did.
593 if (RefExpr->isImplicitProperty()) {
594 if (ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter()) {
595 Setter = setter;
596 SetterSelector = setter->getSelector();
597 return true;
John McCall526ab472011-10-25 17:37:35 +0000598 } else {
John McCallfe96e0b2011-11-06 09:01:30 +0000599 IdentifierInfo *getterName =
600 RefExpr->getImplicitPropertyGetter()->getSelector()
601 .getIdentifierInfoForSlot(0);
602 SetterSelector =
Adrian Prantla4ce9062013-06-07 22:29:12 +0000603 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
604 S.PP.getSelectorTable(),
605 getterName);
John McCallfe96e0b2011-11-06 09:01:30 +0000606 return false;
John McCall526ab472011-10-25 17:37:35 +0000607 }
John McCallfe96e0b2011-11-06 09:01:30 +0000608 }
609
610 // For explicit properties, this is more involved.
611 ObjCPropertyDecl *prop = RefExpr->getExplicitProperty();
612 SetterSelector = prop->getSetterName();
613
614 // Do a normal method lookup first.
615 if (ObjCMethodDecl *setter =
616 LookupMethodInReceiverType(S, SetterSelector, RefExpr)) {
Jordan Rosed01e83a2012-10-10 16:42:25 +0000617 if (setter->isPropertyAccessor() && warn)
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000618 if (const ObjCInterfaceDecl *IFace =
619 dyn_cast<ObjCInterfaceDecl>(setter->getDeclContext())) {
620 const StringRef thisPropertyName(prop->getName());
Jordan Rosea7d03842013-02-08 22:30:41 +0000621 // Try flipping the case of the first character.
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000622 char front = thisPropertyName.front();
Jordan Rosea7d03842013-02-08 22:30:41 +0000623 front = isLowercase(front) ? toUppercase(front) : toLowercase(front);
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000624 SmallString<100> PropertyName = thisPropertyName;
625 PropertyName[0] = front;
626 IdentifierInfo *AltMember = &S.PP.getIdentifierTable().get(PropertyName);
627 if (ObjCPropertyDecl *prop1 = IFace->FindPropertyDeclaration(AltMember))
628 if (prop != prop1 && (prop1->getSetterMethodDecl() == setter)) {
Fariborz Jahanianf3b76812012-05-26 16:10:06 +0000629 S.Diag(RefExpr->getExprLoc(), diag::error_property_setter_ambiguous_use)
Aaron Ballman1fb39552014-01-03 14:23:03 +0000630 << prop << prop1 << setter->getSelector();
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000631 S.Diag(prop->getLocation(), diag::note_property_declare);
632 S.Diag(prop1->getLocation(), diag::note_property_declare);
633 }
634 }
John McCallfe96e0b2011-11-06 09:01:30 +0000635 Setter = setter;
636 return true;
637 }
638
639 // That can fail in the somewhat crazy situation that we're
640 // type-checking a message send within the @interface declaration
641 // that declared the @property. But it's not clear that that's
642 // valuable to support.
643
644 return false;
645}
646
Fariborz Jahanian55513282014-05-28 18:12:10 +0000647bool ObjCPropertyOpBuilder::DiagnoseUnsupportedPropertyUse() {
648 if (S.getCurLexicalContext()->isObjCContainer() &&
649 S.getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
650 S.getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) {
651 if (ObjCPropertyDecl *prop = RefExpr->getExplicitProperty()) {
652 S.Diag(RefExpr->getLocation(),
653 diag::err_property_function_in_objc_container);
654 S.Diag(prop->getLocation(), diag::note_property_declare);
655 return true;
656 }
657 }
658 return false;
659}
660
John McCallfe96e0b2011-11-06 09:01:30 +0000661/// Capture the base object of an Objective-C property expression.
662Expr *ObjCPropertyOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000663 assert(InstanceReceiver == nullptr);
John McCallfe96e0b2011-11-06 09:01:30 +0000664
665 // If we have a base, capture it in an OVE and rebuild the syntactic
666 // form to use the OVE as its base.
667 if (RefExpr->isObjectReceiver()) {
668 InstanceReceiver = capture(RefExpr->getBase());
669
670 syntacticBase =
671 ObjCPropertyRefRebuilder(S, InstanceReceiver).rebuild(syntacticBase);
672 }
673
Argyrios Kyrtzidisab468b02012-03-30 00:19:18 +0000674 if (ObjCPropertyRefExpr *
675 refE = dyn_cast<ObjCPropertyRefExpr>(syntacticBase->IgnoreParens()))
676 SyntacticRefExpr = refE;
677
John McCallfe96e0b2011-11-06 09:01:30 +0000678 return syntacticBase;
679}
680
681/// Load from an Objective-C property reference.
682ExprResult ObjCPropertyOpBuilder::buildGet() {
683 findGetter();
Fariborz Jahanian55513282014-05-28 18:12:10 +0000684 if (!Getter && DiagnoseUnsupportedPropertyUse())
685 return ExprError();
686
John McCallfe96e0b2011-11-06 09:01:30 +0000687 assert(Getter);
Argyrios Kyrtzidisab468b02012-03-30 00:19:18 +0000688
689 if (SyntacticRefExpr)
690 SyntacticRefExpr->setIsMessagingGetter();
691
John McCallfe96e0b2011-11-06 09:01:30 +0000692 QualType receiverType;
John McCallfe96e0b2011-11-06 09:01:30 +0000693 if (RefExpr->isClassReceiver()) {
694 receiverType = S.Context.getObjCInterfaceType(RefExpr->getClassReceiver());
695 } else if (RefExpr->isSuperReceiver()) {
John McCallfe96e0b2011-11-06 09:01:30 +0000696 receiverType = RefExpr->getSuperReceiverType();
John McCall526ab472011-10-25 17:37:35 +0000697 } else {
John McCallfe96e0b2011-11-06 09:01:30 +0000698 assert(InstanceReceiver);
699 receiverType = InstanceReceiver->getType();
700 }
John McCall526ab472011-10-25 17:37:35 +0000701
John McCallfe96e0b2011-11-06 09:01:30 +0000702 // Build a message-send.
703 ExprResult msg;
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +0000704 if ((Getter->isInstanceMethod() && !RefExpr->isClassReceiver()) ||
705 RefExpr->isObjectReceiver()) {
John McCallfe96e0b2011-11-06 09:01:30 +0000706 assert(InstanceReceiver || RefExpr->isSuperReceiver());
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +0000707 msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType,
708 GenericLoc, Getter->getSelector(),
Dmitri Gribenko78852e92013-05-05 20:40:26 +0000709 Getter, None);
John McCallfe96e0b2011-11-06 09:01:30 +0000710 } else {
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +0000711 msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(),
Dmitri Gribenko78852e92013-05-05 20:40:26 +0000712 GenericLoc, Getter->getSelector(),
713 Getter, None);
John McCallfe96e0b2011-11-06 09:01:30 +0000714 }
715 return msg;
716}
John McCall526ab472011-10-25 17:37:35 +0000717
John McCallfe96e0b2011-11-06 09:01:30 +0000718/// Store to an Objective-C property reference.
719///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +0000720/// \param captureSetValueAsResult If true, capture the actual
John McCallfe96e0b2011-11-06 09:01:30 +0000721/// value being set as the value of the property operation.
722ExprResult ObjCPropertyOpBuilder::buildSet(Expr *op, SourceLocation opcLoc,
723 bool captureSetValueAsResult) {
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000724 bool hasSetter = findSetter(false);
Fariborz Jahanian55513282014-05-28 18:12:10 +0000725 if (!hasSetter && DiagnoseUnsupportedPropertyUse())
726 return ExprError();
John McCallfe96e0b2011-11-06 09:01:30 +0000727 assert(hasSetter); (void) hasSetter;
728
Argyrios Kyrtzidisab468b02012-03-30 00:19:18 +0000729 if (SyntacticRefExpr)
730 SyntacticRefExpr->setIsMessagingSetter();
731
John McCallfe96e0b2011-11-06 09:01:30 +0000732 QualType receiverType;
John McCallfe96e0b2011-11-06 09:01:30 +0000733 if (RefExpr->isClassReceiver()) {
734 receiverType = S.Context.getObjCInterfaceType(RefExpr->getClassReceiver());
735 } else if (RefExpr->isSuperReceiver()) {
John McCallfe96e0b2011-11-06 09:01:30 +0000736 receiverType = RefExpr->getSuperReceiverType();
737 } else {
738 assert(InstanceReceiver);
739 receiverType = InstanceReceiver->getType();
740 }
741
742 // Use assignment constraints when possible; they give us better
743 // diagnostics. "When possible" basically means anything except a
744 // C++ class type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000745 if (!S.getLangOpts().CPlusPlus || !op->getType()->isRecordType()) {
John McCallfe96e0b2011-11-06 09:01:30 +0000746 QualType paramType = (*Setter->param_begin())->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000747 if (!S.getLangOpts().CPlusPlus || !paramType->isRecordType()) {
John McCallfe96e0b2011-11-06 09:01:30 +0000748 ExprResult opResult = op;
749 Sema::AssignConvertType assignResult
750 = S.CheckSingleAssignmentConstraints(paramType, opResult);
751 if (S.DiagnoseAssignmentResult(assignResult, opcLoc, paramType,
752 op->getType(), opResult.get(),
753 Sema::AA_Assigning))
754 return ExprError();
755
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000756 op = opResult.get();
John McCallfe96e0b2011-11-06 09:01:30 +0000757 assert(op && "successful assignment left argument invalid?");
John McCall526ab472011-10-25 17:37:35 +0000758 }
Fariborz Jahanian2eaec612013-10-16 17:51:43 +0000759 else if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(op)) {
760 Expr *Initializer = OVE->getSourceExpr();
761 // passing C++11 style initialized temporaries to objc++ properties
762 // requires special treatment by removing OpaqueValueExpr so type
763 // conversion takes place and adding the OpaqueValueExpr later on.
764 if (isa<InitListExpr>(Initializer) &&
765 Initializer->getType()->isVoidType()) {
766 op = Initializer;
767 }
768 }
John McCall526ab472011-10-25 17:37:35 +0000769 }
770
John McCallfe96e0b2011-11-06 09:01:30 +0000771 // Arguments.
772 Expr *args[] = { op };
John McCall526ab472011-10-25 17:37:35 +0000773
John McCallfe96e0b2011-11-06 09:01:30 +0000774 // Build a message-send.
775 ExprResult msg;
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +0000776 if ((Setter->isInstanceMethod() && !RefExpr->isClassReceiver()) ||
777 RefExpr->isObjectReceiver()) {
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +0000778 msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType,
779 GenericLoc, SetterSelector, Setter,
780 MultiExprArg(args, 1));
John McCallfe96e0b2011-11-06 09:01:30 +0000781 } else {
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +0000782 msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(),
783 GenericLoc,
784 SetterSelector, Setter,
785 MultiExprArg(args, 1));
John McCallfe96e0b2011-11-06 09:01:30 +0000786 }
787
788 if (!msg.isInvalid() && captureSetValueAsResult) {
789 ObjCMessageExpr *msgExpr =
790 cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit());
791 Expr *arg = msgExpr->getArg(0);
Fariborz Jahanian15dde892014-03-06 00:34:05 +0000792 if (CanCaptureValue(arg))
Eli Friedman00fa4292012-11-13 23:16:33 +0000793 msgExpr->setArg(0, captureValueAsResult(arg));
John McCallfe96e0b2011-11-06 09:01:30 +0000794 }
795
796 return msg;
John McCall526ab472011-10-25 17:37:35 +0000797}
798
John McCallfe96e0b2011-11-06 09:01:30 +0000799/// @property-specific behavior for doing lvalue-to-rvalue conversion.
800ExprResult ObjCPropertyOpBuilder::buildRValueOperation(Expr *op) {
801 // Explicit properties always have getters, but implicit ones don't.
802 // Check that before proceeding.
Eli Friedmanfd41aee2012-11-29 03:13:49 +0000803 if (RefExpr->isImplicitProperty() && !RefExpr->getImplicitPropertyGetter()) {
John McCallfe96e0b2011-11-06 09:01:30 +0000804 S.Diag(RefExpr->getLocation(), diag::err_getter_not_found)
Eli Friedmanfd41aee2012-11-29 03:13:49 +0000805 << RefExpr->getSourceRange();
John McCall526ab472011-10-25 17:37:35 +0000806 return ExprError();
807 }
808
John McCallfe96e0b2011-11-06 09:01:30 +0000809 ExprResult result = PseudoOpBuilder::buildRValueOperation(op);
John McCall526ab472011-10-25 17:37:35 +0000810 if (result.isInvalid()) return ExprError();
811
John McCallfe96e0b2011-11-06 09:01:30 +0000812 if (RefExpr->isExplicitProperty() && !Getter->hasRelatedResultType())
813 S.DiagnosePropertyAccessorMismatch(RefExpr->getExplicitProperty(),
814 Getter, RefExpr->getLocation());
815
816 // As a special case, if the method returns 'id', try to get
817 // a better type from the property.
818 if (RefExpr->isExplicitProperty() && result.get()->isRValue() &&
819 result.get()->getType()->isObjCIdType()) {
820 QualType propType = RefExpr->getExplicitProperty()->getType();
821 if (const ObjCObjectPointerType *ptr
822 = propType->getAs<ObjCObjectPointerType>()) {
823 if (!ptr->isObjCIdType())
824 result = S.ImpCastExprToType(result.get(), propType, CK_BitCast);
825 }
826 }
827
John McCall526ab472011-10-25 17:37:35 +0000828 return result;
829}
830
John McCallfe96e0b2011-11-06 09:01:30 +0000831/// Try to build this as a call to a getter that returns a reference.
832///
833/// \return true if it was possible, whether or not it actually
834/// succeeded
835bool ObjCPropertyOpBuilder::tryBuildGetOfReference(Expr *op,
836 ExprResult &result) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000837 if (!S.getLangOpts().CPlusPlus) return false;
John McCallfe96e0b2011-11-06 09:01:30 +0000838
839 findGetter();
840 assert(Getter && "property has no setter and no getter!");
841
842 // Only do this if the getter returns an l-value reference type.
Alp Toker314cc812014-01-25 16:55:45 +0000843 QualType resultType = Getter->getReturnType();
John McCallfe96e0b2011-11-06 09:01:30 +0000844 if (!resultType->isLValueReferenceType()) return false;
845
846 result = buildRValueOperation(op);
847 return true;
848}
849
850/// @property-specific behavior for doing assignments.
851ExprResult
852ObjCPropertyOpBuilder::buildAssignmentOperation(Scope *Sc,
853 SourceLocation opcLoc,
854 BinaryOperatorKind opcode,
855 Expr *LHS, Expr *RHS) {
John McCall526ab472011-10-25 17:37:35 +0000856 assert(BinaryOperator::isAssignmentOp(opcode));
John McCall526ab472011-10-25 17:37:35 +0000857
858 // If there's no setter, we have no choice but to try to assign to
859 // the result of the getter.
John McCallfe96e0b2011-11-06 09:01:30 +0000860 if (!findSetter()) {
861 ExprResult result;
862 if (tryBuildGetOfReference(LHS, result)) {
863 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000864 return S.BuildBinOp(Sc, opcLoc, opcode, result.get(), RHS);
John McCall526ab472011-10-25 17:37:35 +0000865 }
866
867 // Otherwise, it's an error.
John McCallfe96e0b2011-11-06 09:01:30 +0000868 S.Diag(opcLoc, diag::err_nosetter_property_assignment)
869 << unsigned(RefExpr->isImplicitProperty())
870 << SetterSelector
John McCall526ab472011-10-25 17:37:35 +0000871 << LHS->getSourceRange() << RHS->getSourceRange();
872 return ExprError();
873 }
874
875 // If there is a setter, we definitely want to use it.
876
John McCallfe96e0b2011-11-06 09:01:30 +0000877 // Verify that we can do a compound assignment.
878 if (opcode != BO_Assign && !findGetter()) {
879 S.Diag(opcLoc, diag::err_nogetter_property_compound_assignment)
John McCall526ab472011-10-25 17:37:35 +0000880 << LHS->getSourceRange() << RHS->getSourceRange();
881 return ExprError();
882 }
883
John McCallfe96e0b2011-11-06 09:01:30 +0000884 ExprResult result =
885 PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS);
John McCall526ab472011-10-25 17:37:35 +0000886 if (result.isInvalid()) return ExprError();
887
John McCallfe96e0b2011-11-06 09:01:30 +0000888 // Various warnings about property assignments in ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000889 if (S.getLangOpts().ObjCAutoRefCount && InstanceReceiver) {
John McCallfe96e0b2011-11-06 09:01:30 +0000890 S.checkRetainCycles(InstanceReceiver->getSourceExpr(), RHS);
891 S.checkUnsafeExprAssigns(opcLoc, LHS, RHS);
892 }
893
John McCall526ab472011-10-25 17:37:35 +0000894 return result;
895}
John McCallfe96e0b2011-11-06 09:01:30 +0000896
897/// @property-specific behavior for doing increments and decrements.
898ExprResult
899ObjCPropertyOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc,
900 UnaryOperatorKind opcode,
901 Expr *op) {
902 // If there's no setter, we have no choice but to try to assign to
903 // the result of the getter.
904 if (!findSetter()) {
905 ExprResult result;
906 if (tryBuildGetOfReference(op, result)) {
907 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000908 return S.BuildUnaryOp(Sc, opcLoc, opcode, result.get());
John McCallfe96e0b2011-11-06 09:01:30 +0000909 }
910
911 // Otherwise, it's an error.
912 S.Diag(opcLoc, diag::err_nosetter_property_incdec)
913 << unsigned(RefExpr->isImplicitProperty())
914 << unsigned(UnaryOperator::isDecrementOp(opcode))
915 << SetterSelector
916 << op->getSourceRange();
917 return ExprError();
918 }
919
920 // If there is a setter, we definitely want to use it.
921
922 // We also need a getter.
923 if (!findGetter()) {
924 assert(RefExpr->isImplicitProperty());
925 S.Diag(opcLoc, diag::err_nogetter_property_incdec)
926 << unsigned(UnaryOperator::isDecrementOp(opcode))
Fariborz Jahanianb525b522012-04-18 19:13:23 +0000927 << GetterSelector
John McCallfe96e0b2011-11-06 09:01:30 +0000928 << op->getSourceRange();
929 return ExprError();
930 }
931
932 return PseudoOpBuilder::buildIncDecOperation(Sc, opcLoc, opcode, op);
933}
934
Jordan Rosed3934582012-09-28 22:21:30 +0000935ExprResult ObjCPropertyOpBuilder::complete(Expr *SyntacticForm) {
936 if (S.getLangOpts().ObjCAutoRefCount && isWeakProperty()) {
937 DiagnosticsEngine::Level Level =
938 S.Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
939 SyntacticForm->getLocStart());
940 if (Level != DiagnosticsEngine::Ignored)
Fariborz Jahanian6f829e32013-05-21 21:20:26 +0000941 S.recordUseOfEvaluatedWeak(SyntacticRefExpr,
942 SyntacticRefExpr->isMessagingGetter());
Jordan Rosed3934582012-09-28 22:21:30 +0000943 }
944
945 return PseudoOpBuilder::complete(SyntacticForm);
946}
947
Ted Kremeneke65b0862012-03-06 20:05:56 +0000948// ObjCSubscript build stuff.
949//
950
951/// objective-c subscripting-specific behavior for doing lvalue-to-rvalue
952/// conversion.
953/// FIXME. Remove this routine if it is proven that no additional
954/// specifity is needed.
955ExprResult ObjCSubscriptOpBuilder::buildRValueOperation(Expr *op) {
956 ExprResult result = PseudoOpBuilder::buildRValueOperation(op);
957 if (result.isInvalid()) return ExprError();
958 return result;
959}
960
961/// objective-c subscripting-specific behavior for doing assignments.
962ExprResult
963ObjCSubscriptOpBuilder::buildAssignmentOperation(Scope *Sc,
964 SourceLocation opcLoc,
965 BinaryOperatorKind opcode,
966 Expr *LHS, Expr *RHS) {
967 assert(BinaryOperator::isAssignmentOp(opcode));
968 // There must be a method to do the Index'ed assignment.
969 if (!findAtIndexSetter())
970 return ExprError();
971
972 // Verify that we can do a compound assignment.
973 if (opcode != BO_Assign && !findAtIndexGetter())
974 return ExprError();
975
976 ExprResult result =
977 PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS);
978 if (result.isInvalid()) return ExprError();
979
980 // Various warnings about objc Index'ed assignments in ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000981 if (S.getLangOpts().ObjCAutoRefCount && InstanceBase) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000982 S.checkRetainCycles(InstanceBase->getSourceExpr(), RHS);
983 S.checkUnsafeExprAssigns(opcLoc, LHS, RHS);
984 }
985
986 return result;
987}
988
989/// Capture the base object of an Objective-C Index'ed expression.
990Expr *ObjCSubscriptOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000991 assert(InstanceBase == nullptr);
992
Ted Kremeneke65b0862012-03-06 20:05:56 +0000993 // Capture base expression in an OVE and rebuild the syntactic
994 // form to use the OVE as its base expression.
995 InstanceBase = capture(RefExpr->getBaseExpr());
996 InstanceKey = capture(RefExpr->getKeyExpr());
997
998 syntacticBase =
999 ObjCSubscriptRefRebuilder(S, InstanceBase,
1000 InstanceKey).rebuild(syntacticBase);
1001
1002 return syntacticBase;
1003}
1004
1005/// CheckSubscriptingKind - This routine decide what type
1006/// of indexing represented by "FromE" is being done.
1007Sema::ObjCSubscriptKind
1008 Sema::CheckSubscriptingKind(Expr *FromE) {
1009 // If the expression already has integral or enumeration type, we're golden.
1010 QualType T = FromE->getType();
1011 if (T->isIntegralOrEnumerationType())
1012 return OS_Array;
1013
1014 // If we don't have a class type in C++, there's no way we can get an
1015 // expression of integral or enumeration type.
1016 const RecordType *RecordTy = T->getAs<RecordType>();
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00001017 if (!RecordTy && T->isObjCObjectPointerType())
Ted Kremeneke65b0862012-03-06 20:05:56 +00001018 // All other scalar cases are assumed to be dictionary indexing which
1019 // caller handles, with diagnostics if needed.
1020 return OS_Dictionary;
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00001021 if (!getLangOpts().CPlusPlus ||
1022 !RecordTy || RecordTy->isIncompleteType()) {
Ted Kremeneke65b0862012-03-06 20:05:56 +00001023 // No indexing can be done. Issue diagnostics and quit.
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00001024 const Expr *IndexExpr = FromE->IgnoreParenImpCasts();
1025 if (isa<StringLiteral>(IndexExpr))
1026 Diag(FromE->getExprLoc(), diag::err_objc_subscript_pointer)
1027 << T << FixItHint::CreateInsertion(FromE->getExprLoc(), "@");
1028 else
1029 Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion)
1030 << T;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001031 return OS_Error;
1032 }
1033
1034 // We must have a complete class type.
1035 if (RequireCompleteType(FromE->getExprLoc(), T,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001036 diag::err_objc_index_incomplete_class_type, FromE))
Ted Kremeneke65b0862012-03-06 20:05:56 +00001037 return OS_Error;
1038
1039 // Look for a conversion to an integral, enumeration type, or
1040 // objective-C pointer type.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00001041 std::pair<CXXRecordDecl::conversion_iterator,
1042 CXXRecordDecl::conversion_iterator> Conversions
Ted Kremeneke65b0862012-03-06 20:05:56 +00001043 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
1044
1045 int NoIntegrals=0, NoObjCIdPointers=0;
1046 SmallVector<CXXConversionDecl *, 4> ConversionDecls;
1047
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00001048 for (CXXRecordDecl::conversion_iterator
1049 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Ted Kremeneke65b0862012-03-06 20:05:56 +00001050 if (CXXConversionDecl *Conversion
1051 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
1052 QualType CT = Conversion->getConversionType().getNonReferenceType();
1053 if (CT->isIntegralOrEnumerationType()) {
1054 ++NoIntegrals;
1055 ConversionDecls.push_back(Conversion);
1056 }
1057 else if (CT->isObjCIdType() ||CT->isBlockPointerType()) {
1058 ++NoObjCIdPointers;
1059 ConversionDecls.push_back(Conversion);
1060 }
1061 }
1062 }
1063 if (NoIntegrals ==1 && NoObjCIdPointers == 0)
1064 return OS_Array;
1065 if (NoIntegrals == 0 && NoObjCIdPointers == 1)
1066 return OS_Dictionary;
1067 if (NoIntegrals == 0 && NoObjCIdPointers == 0) {
1068 // No conversion function was found. Issue diagnostic and return.
1069 Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion)
1070 << FromE->getType();
1071 return OS_Error;
1072 }
1073 Diag(FromE->getExprLoc(), diag::err_objc_multiple_subscript_type_conversion)
1074 << FromE->getType();
1075 for (unsigned int i = 0; i < ConversionDecls.size(); i++)
1076 Diag(ConversionDecls[i]->getLocation(), diag::not_conv_function_declared_at);
1077
1078 return OS_Error;
1079}
1080
Fariborz Jahanian90804912012-08-02 18:03:58 +00001081/// CheckKeyForObjCARCConversion - This routine suggests bridge casting of CF
1082/// objects used as dictionary subscript key objects.
1083static void CheckKeyForObjCARCConversion(Sema &S, QualType ContainerT,
1084 Expr *Key) {
1085 if (ContainerT.isNull())
1086 return;
1087 // dictionary subscripting.
1088 // - (id)objectForKeyedSubscript:(id)key;
1089 IdentifierInfo *KeyIdents[] = {
1090 &S.Context.Idents.get("objectForKeyedSubscript")
1091 };
1092 Selector GetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1093 ObjCMethodDecl *Getter = S.LookupMethodInObjectType(GetterSelector, ContainerT,
1094 true /*instance*/);
1095 if (!Getter)
1096 return;
1097 QualType T = Getter->param_begin()[0]->getType();
1098 S.CheckObjCARCConversion(Key->getSourceRange(),
1099 T, Key, Sema::CCK_ImplicitConversion);
1100}
1101
Ted Kremeneke65b0862012-03-06 20:05:56 +00001102bool ObjCSubscriptOpBuilder::findAtIndexGetter() {
1103 if (AtIndexGetter)
1104 return true;
1105
1106 Expr *BaseExpr = RefExpr->getBaseExpr();
1107 QualType BaseT = BaseExpr->getType();
1108
1109 QualType ResultType;
1110 if (const ObjCObjectPointerType *PTy =
1111 BaseT->getAs<ObjCObjectPointerType>()) {
1112 ResultType = PTy->getPointeeType();
1113 if (const ObjCObjectType *iQFaceTy =
1114 ResultType->getAsObjCQualifiedInterfaceType())
1115 ResultType = iQFaceTy->getBaseType();
1116 }
1117 Sema::ObjCSubscriptKind Res =
1118 S.CheckSubscriptingKind(RefExpr->getKeyExpr());
Fariborz Jahanian90804912012-08-02 18:03:58 +00001119 if (Res == Sema::OS_Error) {
1120 if (S.getLangOpts().ObjCAutoRefCount)
1121 CheckKeyForObjCARCConversion(S, ResultType,
1122 RefExpr->getKeyExpr());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001123 return false;
Fariborz Jahanian90804912012-08-02 18:03:58 +00001124 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001125 bool arrayRef = (Res == Sema::OS_Array);
1126
1127 if (ResultType.isNull()) {
1128 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type)
1129 << BaseExpr->getType() << arrayRef;
1130 return false;
1131 }
1132 if (!arrayRef) {
1133 // dictionary subscripting.
1134 // - (id)objectForKeyedSubscript:(id)key;
1135 IdentifierInfo *KeyIdents[] = {
1136 &S.Context.Idents.get("objectForKeyedSubscript")
1137 };
1138 AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1139 }
1140 else {
1141 // - (id)objectAtIndexedSubscript:(size_t)index;
1142 IdentifierInfo *KeyIdents[] = {
1143 &S.Context.Idents.get("objectAtIndexedSubscript")
1144 };
1145
1146 AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1147 }
1148
1149 AtIndexGetter = S.LookupMethodInObjectType(AtIndexGetterSelector, ResultType,
1150 true /*instance*/);
1151 bool receiverIdType = (BaseT->isObjCIdType() ||
1152 BaseT->isObjCQualifiedIdType());
1153
David Blaikiebbafb8a2012-03-11 07:00:24 +00001154 if (!AtIndexGetter && S.getLangOpts().DebuggerObjCLiteral) {
Ted Kremeneke65b0862012-03-06 20:05:56 +00001155 AtIndexGetter = ObjCMethodDecl::Create(S.Context, SourceLocation(),
1156 SourceLocation(), AtIndexGetterSelector,
1157 S.Context.getObjCIdType() /*ReturnType*/,
Craig Topperc3ec1492014-05-26 06:22:03 +00001158 nullptr /*TypeSourceInfo */,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001159 S.Context.getTranslationUnitDecl(),
1160 true /*Instance*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +00001161 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001162 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
1163 ObjCMethodDecl::Required,
1164 false);
1165 ParmVarDecl *Argument = ParmVarDecl::Create(S.Context, AtIndexGetter,
1166 SourceLocation(), SourceLocation(),
1167 arrayRef ? &S.Context.Idents.get("index")
1168 : &S.Context.Idents.get("key"),
1169 arrayRef ? S.Context.UnsignedLongTy
1170 : S.Context.getObjCIdType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001171 /*TInfo=*/nullptr,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001172 SC_None,
Craig Topperc3ec1492014-05-26 06:22:03 +00001173 nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00001174 AtIndexGetter->setMethodParams(S.Context, Argument, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001175 }
1176
1177 if (!AtIndexGetter) {
1178 if (!receiverIdType) {
1179 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_method_not_found)
1180 << BaseExpr->getType() << 0 << arrayRef;
1181 return false;
1182 }
1183 AtIndexGetter =
1184 S.LookupInstanceMethodInGlobalPool(AtIndexGetterSelector,
1185 RefExpr->getSourceRange(),
1186 true, false);
1187 }
1188
1189 if (AtIndexGetter) {
1190 QualType T = AtIndexGetter->param_begin()[0]->getType();
1191 if ((arrayRef && !T->isIntegralOrEnumerationType()) ||
1192 (!arrayRef && !T->isObjCObjectPointerType())) {
1193 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1194 arrayRef ? diag::err_objc_subscript_index_type
1195 : diag::err_objc_subscript_key_type) << T;
1196 S.Diag(AtIndexGetter->param_begin()[0]->getLocation(),
1197 diag::note_parameter_type) << T;
1198 return false;
1199 }
Alp Toker314cc812014-01-25 16:55:45 +00001200 QualType R = AtIndexGetter->getReturnType();
Ted Kremeneke65b0862012-03-06 20:05:56 +00001201 if (!R->isObjCObjectPointerType()) {
1202 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1203 diag::err_objc_indexing_method_result_type) << R << arrayRef;
1204 S.Diag(AtIndexGetter->getLocation(), diag::note_method_declared_at) <<
1205 AtIndexGetter->getDeclName();
1206 }
1207 }
1208 return true;
1209}
1210
1211bool ObjCSubscriptOpBuilder::findAtIndexSetter() {
1212 if (AtIndexSetter)
1213 return true;
1214
1215 Expr *BaseExpr = RefExpr->getBaseExpr();
1216 QualType BaseT = BaseExpr->getType();
1217
1218 QualType ResultType;
1219 if (const ObjCObjectPointerType *PTy =
1220 BaseT->getAs<ObjCObjectPointerType>()) {
1221 ResultType = PTy->getPointeeType();
1222 if (const ObjCObjectType *iQFaceTy =
1223 ResultType->getAsObjCQualifiedInterfaceType())
1224 ResultType = iQFaceTy->getBaseType();
1225 }
1226
1227 Sema::ObjCSubscriptKind Res =
1228 S.CheckSubscriptingKind(RefExpr->getKeyExpr());
Fariborz Jahanian90804912012-08-02 18:03:58 +00001229 if (Res == Sema::OS_Error) {
1230 if (S.getLangOpts().ObjCAutoRefCount)
1231 CheckKeyForObjCARCConversion(S, ResultType,
1232 RefExpr->getKeyExpr());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001233 return false;
Fariborz Jahanian90804912012-08-02 18:03:58 +00001234 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001235 bool arrayRef = (Res == Sema::OS_Array);
1236
1237 if (ResultType.isNull()) {
1238 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type)
1239 << BaseExpr->getType() << arrayRef;
1240 return false;
1241 }
1242
1243 if (!arrayRef) {
1244 // dictionary subscripting.
1245 // - (void)setObject:(id)object forKeyedSubscript:(id)key;
1246 IdentifierInfo *KeyIdents[] = {
1247 &S.Context.Idents.get("setObject"),
1248 &S.Context.Idents.get("forKeyedSubscript")
1249 };
1250 AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents);
1251 }
1252 else {
1253 // - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index;
1254 IdentifierInfo *KeyIdents[] = {
1255 &S.Context.Idents.get("setObject"),
1256 &S.Context.Idents.get("atIndexedSubscript")
1257 };
1258 AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents);
1259 }
1260 AtIndexSetter = S.LookupMethodInObjectType(AtIndexSetterSelector, ResultType,
1261 true /*instance*/);
1262
1263 bool receiverIdType = (BaseT->isObjCIdType() ||
1264 BaseT->isObjCQualifiedIdType());
1265
David Blaikiebbafb8a2012-03-11 07:00:24 +00001266 if (!AtIndexSetter && S.getLangOpts().DebuggerObjCLiteral) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001267 TypeSourceInfo *ReturnTInfo = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001268 QualType ReturnType = S.Context.VoidTy;
Alp Toker314cc812014-01-25 16:55:45 +00001269 AtIndexSetter = ObjCMethodDecl::Create(
1270 S.Context, SourceLocation(), SourceLocation(), AtIndexSetterSelector,
1271 ReturnType, ReturnTInfo, S.Context.getTranslationUnitDecl(),
1272 true /*Instance*/, false /*isVariadic*/,
1273 /*isPropertyAccessor=*/false,
1274 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
1275 ObjCMethodDecl::Required, false);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001276 SmallVector<ParmVarDecl *, 2> Params;
1277 ParmVarDecl *object = ParmVarDecl::Create(S.Context, AtIndexSetter,
1278 SourceLocation(), SourceLocation(),
1279 &S.Context.Idents.get("object"),
1280 S.Context.getObjCIdType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001281 /*TInfo=*/nullptr,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001282 SC_None,
Craig Topperc3ec1492014-05-26 06:22:03 +00001283 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001284 Params.push_back(object);
1285 ParmVarDecl *key = ParmVarDecl::Create(S.Context, AtIndexSetter,
1286 SourceLocation(), SourceLocation(),
1287 arrayRef ? &S.Context.Idents.get("index")
1288 : &S.Context.Idents.get("key"),
1289 arrayRef ? S.Context.UnsignedLongTy
1290 : S.Context.getObjCIdType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001291 /*TInfo=*/nullptr,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001292 SC_None,
Craig Topperc3ec1492014-05-26 06:22:03 +00001293 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001294 Params.push_back(key);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00001295 AtIndexSetter->setMethodParams(S.Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001296 }
1297
1298 if (!AtIndexSetter) {
1299 if (!receiverIdType) {
1300 S.Diag(BaseExpr->getExprLoc(),
1301 diag::err_objc_subscript_method_not_found)
1302 << BaseExpr->getType() << 1 << arrayRef;
1303 return false;
1304 }
1305 AtIndexSetter =
1306 S.LookupInstanceMethodInGlobalPool(AtIndexSetterSelector,
1307 RefExpr->getSourceRange(),
1308 true, false);
1309 }
1310
1311 bool err = false;
1312 if (AtIndexSetter && arrayRef) {
1313 QualType T = AtIndexSetter->param_begin()[1]->getType();
1314 if (!T->isIntegralOrEnumerationType()) {
1315 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1316 diag::err_objc_subscript_index_type) << T;
1317 S.Diag(AtIndexSetter->param_begin()[1]->getLocation(),
1318 diag::note_parameter_type) << T;
1319 err = true;
1320 }
1321 T = AtIndexSetter->param_begin()[0]->getType();
1322 if (!T->isObjCObjectPointerType()) {
1323 S.Diag(RefExpr->getBaseExpr()->getExprLoc(),
1324 diag::err_objc_subscript_object_type) << T << arrayRef;
1325 S.Diag(AtIndexSetter->param_begin()[0]->getLocation(),
1326 diag::note_parameter_type) << T;
1327 err = true;
1328 }
1329 }
1330 else if (AtIndexSetter && !arrayRef)
1331 for (unsigned i=0; i <2; i++) {
1332 QualType T = AtIndexSetter->param_begin()[i]->getType();
1333 if (!T->isObjCObjectPointerType()) {
1334 if (i == 1)
1335 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1336 diag::err_objc_subscript_key_type) << T;
1337 else
1338 S.Diag(RefExpr->getBaseExpr()->getExprLoc(),
1339 diag::err_objc_subscript_dic_object_type) << T;
1340 S.Diag(AtIndexSetter->param_begin()[i]->getLocation(),
1341 diag::note_parameter_type) << T;
1342 err = true;
1343 }
1344 }
1345
1346 return !err;
1347}
1348
1349// Get the object at "Index" position in the container.
1350// [BaseExpr objectAtIndexedSubscript : IndexExpr];
1351ExprResult ObjCSubscriptOpBuilder::buildGet() {
1352 if (!findAtIndexGetter())
1353 return ExprError();
1354
1355 QualType receiverType = InstanceBase->getType();
1356
1357 // Build a message-send.
1358 ExprResult msg;
1359 Expr *Index = InstanceKey;
1360
1361 // Arguments.
1362 Expr *args[] = { Index };
1363 assert(InstanceBase);
1364 msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType,
1365 GenericLoc,
1366 AtIndexGetterSelector, AtIndexGetter,
1367 MultiExprArg(args, 1));
1368 return msg;
1369}
1370
1371/// Store into the container the "op" object at "Index"'ed location
1372/// by building this messaging expression:
1373/// - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index;
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00001374/// \param captureSetValueAsResult If true, capture the actual
Ted Kremeneke65b0862012-03-06 20:05:56 +00001375/// value being set as the value of the property operation.
1376ExprResult ObjCSubscriptOpBuilder::buildSet(Expr *op, SourceLocation opcLoc,
1377 bool captureSetValueAsResult) {
1378 if (!findAtIndexSetter())
1379 return ExprError();
1380
1381 QualType receiverType = InstanceBase->getType();
1382 Expr *Index = InstanceKey;
1383
1384 // Arguments.
1385 Expr *args[] = { op, Index };
1386
1387 // Build a message-send.
1388 ExprResult msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType,
1389 GenericLoc,
1390 AtIndexSetterSelector,
1391 AtIndexSetter,
1392 MultiExprArg(args, 2));
1393
1394 if (!msg.isInvalid() && captureSetValueAsResult) {
1395 ObjCMessageExpr *msgExpr =
1396 cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit());
1397 Expr *arg = msgExpr->getArg(0);
Fariborz Jahanian15dde892014-03-06 00:34:05 +00001398 if (CanCaptureValue(arg))
Eli Friedman00fa4292012-11-13 23:16:33 +00001399 msgExpr->setArg(0, captureValueAsResult(arg));
Ted Kremeneke65b0862012-03-06 20:05:56 +00001400 }
1401
1402 return msg;
1403}
1404
John McCallfe96e0b2011-11-06 09:01:30 +00001405//===----------------------------------------------------------------------===//
John McCall5e77d762013-04-16 07:28:30 +00001406// MSVC __declspec(property) references
1407//===----------------------------------------------------------------------===//
1408
1409Expr *MSPropertyOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
1410 Expr *NewBase = capture(RefExpr->getBaseExpr());
1411
1412 syntacticBase =
1413 MSPropertyRefRebuilder(S, NewBase).rebuild(syntacticBase);
1414
1415 return syntacticBase;
1416}
1417
1418ExprResult MSPropertyOpBuilder::buildGet() {
1419 if (!RefExpr->getPropertyDecl()->hasGetter()) {
Aaron Ballman213cf412013-12-26 16:35:04 +00001420 S.Diag(RefExpr->getMemberLoc(), diag::err_no_accessor_for_property)
Aaron Ballman1bda4592014-01-03 01:09:27 +00001421 << 0 /* getter */ << RefExpr->getPropertyDecl();
John McCall5e77d762013-04-16 07:28:30 +00001422 return ExprError();
1423 }
1424
1425 UnqualifiedId GetterName;
1426 IdentifierInfo *II = RefExpr->getPropertyDecl()->getGetterId();
1427 GetterName.setIdentifier(II, RefExpr->getMemberLoc());
1428 CXXScopeSpec SS;
1429 SS.Adopt(RefExpr->getQualifierLoc());
1430 ExprResult GetterExpr = S.ActOnMemberAccessExpr(
1431 S.getCurScope(), RefExpr->getBaseExpr(), SourceLocation(),
1432 RefExpr->isArrow() ? tok::arrow : tok::period, SS, SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001433 GetterName, nullptr, true);
John McCall5e77d762013-04-16 07:28:30 +00001434 if (GetterExpr.isInvalid()) {
Aaron Ballman9e35bfe2013-12-26 15:46:38 +00001435 S.Diag(RefExpr->getMemberLoc(),
Aaron Ballman213cf412013-12-26 16:35:04 +00001436 diag::error_cannot_find_suitable_accessor) << 0 /* getter */
Aaron Ballman1bda4592014-01-03 01:09:27 +00001437 << RefExpr->getPropertyDecl();
John McCall5e77d762013-04-16 07:28:30 +00001438 return ExprError();
1439 }
1440
1441 MultiExprArg ArgExprs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001442 return S.ActOnCallExpr(S.getCurScope(), GetterExpr.get(),
John McCall5e77d762013-04-16 07:28:30 +00001443 RefExpr->getSourceRange().getBegin(), ArgExprs,
1444 RefExpr->getSourceRange().getEnd());
1445}
1446
1447ExprResult MSPropertyOpBuilder::buildSet(Expr *op, SourceLocation sl,
1448 bool captureSetValueAsResult) {
1449 if (!RefExpr->getPropertyDecl()->hasSetter()) {
Aaron Ballman213cf412013-12-26 16:35:04 +00001450 S.Diag(RefExpr->getMemberLoc(), diag::err_no_accessor_for_property)
Aaron Ballman1bda4592014-01-03 01:09:27 +00001451 << 1 /* setter */ << RefExpr->getPropertyDecl();
John McCall5e77d762013-04-16 07:28:30 +00001452 return ExprError();
1453 }
1454
1455 UnqualifiedId SetterName;
1456 IdentifierInfo *II = RefExpr->getPropertyDecl()->getSetterId();
1457 SetterName.setIdentifier(II, RefExpr->getMemberLoc());
1458 CXXScopeSpec SS;
1459 SS.Adopt(RefExpr->getQualifierLoc());
1460 ExprResult SetterExpr = S.ActOnMemberAccessExpr(
1461 S.getCurScope(), RefExpr->getBaseExpr(), SourceLocation(),
1462 RefExpr->isArrow() ? tok::arrow : tok::period, SS, SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001463 SetterName, nullptr, true);
John McCall5e77d762013-04-16 07:28:30 +00001464 if (SetterExpr.isInvalid()) {
Aaron Ballman9e35bfe2013-12-26 15:46:38 +00001465 S.Diag(RefExpr->getMemberLoc(),
Aaron Ballman213cf412013-12-26 16:35:04 +00001466 diag::error_cannot_find_suitable_accessor) << 1 /* setter */
Aaron Ballman1bda4592014-01-03 01:09:27 +00001467 << RefExpr->getPropertyDecl();
John McCall5e77d762013-04-16 07:28:30 +00001468 return ExprError();
1469 }
1470
1471 SmallVector<Expr*, 1> ArgExprs;
1472 ArgExprs.push_back(op);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001473 return S.ActOnCallExpr(S.getCurScope(), SetterExpr.get(),
John McCall5e77d762013-04-16 07:28:30 +00001474 RefExpr->getSourceRange().getBegin(), ArgExprs,
1475 op->getSourceRange().getEnd());
1476}
1477
1478//===----------------------------------------------------------------------===//
John McCallfe96e0b2011-11-06 09:01:30 +00001479// General Sema routines.
1480//===----------------------------------------------------------------------===//
1481
1482ExprResult Sema::checkPseudoObjectRValue(Expr *E) {
1483 Expr *opaqueRef = E->IgnoreParens();
1484 if (ObjCPropertyRefExpr *refExpr
1485 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1486 ObjCPropertyOpBuilder builder(*this, refExpr);
1487 return builder.buildRValueOperation(E);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001488 }
1489 else if (ObjCSubscriptRefExpr *refExpr
1490 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1491 ObjCSubscriptOpBuilder builder(*this, refExpr);
1492 return builder.buildRValueOperation(E);
John McCall5e77d762013-04-16 07:28:30 +00001493 } else if (MSPropertyRefExpr *refExpr
1494 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1495 MSPropertyOpBuilder builder(*this, refExpr);
1496 return builder.buildRValueOperation(E);
John McCallfe96e0b2011-11-06 09:01:30 +00001497 } else {
1498 llvm_unreachable("unknown pseudo-object kind!");
1499 }
1500}
1501
1502/// Check an increment or decrement of a pseudo-object expression.
1503ExprResult Sema::checkPseudoObjectIncDec(Scope *Sc, SourceLocation opcLoc,
1504 UnaryOperatorKind opcode, Expr *op) {
1505 // Do nothing if the operand is dependent.
1506 if (op->isTypeDependent())
1507 return new (Context) UnaryOperator(op, opcode, Context.DependentTy,
1508 VK_RValue, OK_Ordinary, opcLoc);
1509
1510 assert(UnaryOperator::isIncrementDecrementOp(opcode));
1511 Expr *opaqueRef = op->IgnoreParens();
1512 if (ObjCPropertyRefExpr *refExpr
1513 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1514 ObjCPropertyOpBuilder builder(*this, refExpr);
1515 return builder.buildIncDecOperation(Sc, opcLoc, opcode, op);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001516 } else if (isa<ObjCSubscriptRefExpr>(opaqueRef)) {
1517 Diag(opcLoc, diag::err_illegal_container_subscripting_op);
1518 return ExprError();
John McCall5e77d762013-04-16 07:28:30 +00001519 } else if (MSPropertyRefExpr *refExpr
1520 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1521 MSPropertyOpBuilder builder(*this, refExpr);
1522 return builder.buildIncDecOperation(Sc, opcLoc, opcode, op);
John McCallfe96e0b2011-11-06 09:01:30 +00001523 } else {
1524 llvm_unreachable("unknown pseudo-object kind!");
1525 }
1526}
1527
1528ExprResult Sema::checkPseudoObjectAssignment(Scope *S, SourceLocation opcLoc,
1529 BinaryOperatorKind opcode,
1530 Expr *LHS, Expr *RHS) {
1531 // Do nothing if either argument is dependent.
1532 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1533 return new (Context) BinaryOperator(LHS, RHS, opcode, Context.DependentTy,
Lang Hames5de91cc2012-10-02 04:45:10 +00001534 VK_RValue, OK_Ordinary, opcLoc, false);
John McCallfe96e0b2011-11-06 09:01:30 +00001535
1536 // Filter out non-overload placeholder types in the RHS.
John McCalld5c98ae2011-11-15 01:35:18 +00001537 if (RHS->getType()->isNonOverloadPlaceholderType()) {
1538 ExprResult result = CheckPlaceholderExpr(RHS);
1539 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001540 RHS = result.get();
John McCallfe96e0b2011-11-06 09:01:30 +00001541 }
1542
1543 Expr *opaqueRef = LHS->IgnoreParens();
1544 if (ObjCPropertyRefExpr *refExpr
1545 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1546 ObjCPropertyOpBuilder builder(*this, refExpr);
1547 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001548 } else if (ObjCSubscriptRefExpr *refExpr
1549 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1550 ObjCSubscriptOpBuilder builder(*this, refExpr);
1551 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
John McCall5e77d762013-04-16 07:28:30 +00001552 } else if (MSPropertyRefExpr *refExpr
1553 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1554 MSPropertyOpBuilder builder(*this, refExpr);
1555 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
John McCallfe96e0b2011-11-06 09:01:30 +00001556 } else {
1557 llvm_unreachable("unknown pseudo-object kind!");
1558 }
1559}
John McCalle9290822011-11-30 04:42:31 +00001560
1561/// Given a pseudo-object reference, rebuild it without the opaque
1562/// values. Basically, undo the behavior of rebuildAndCaptureObject.
1563/// This should never operate in-place.
1564static Expr *stripOpaqueValuesFromPseudoObjectRef(Sema &S, Expr *E) {
1565 Expr *opaqueRef = E->IgnoreParens();
1566 if (ObjCPropertyRefExpr *refExpr
1567 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
Douglas Gregoraa0df2d2012-04-13 16:05:42 +00001568 // Class and super property references don't have opaque values in them.
1569 if (refExpr->isClassReceiver() || refExpr->isSuperReceiver())
1570 return E;
1571
1572 assert(refExpr->isObjectReceiver() && "Unknown receiver kind?");
1573 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBase());
1574 return ObjCPropertyRefRebuilder(S, baseOVE->getSourceExpr()).rebuild(E);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001575 } else if (ObjCSubscriptRefExpr *refExpr
1576 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1577 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBaseExpr());
1578 OpaqueValueExpr *keyOVE = cast<OpaqueValueExpr>(refExpr->getKeyExpr());
1579 return ObjCSubscriptRefRebuilder(S, baseOVE->getSourceExpr(),
1580 keyOVE->getSourceExpr()).rebuild(E);
John McCall5e77d762013-04-16 07:28:30 +00001581 } else if (MSPropertyRefExpr *refExpr
1582 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1583 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBaseExpr());
1584 return MSPropertyRefRebuilder(S, baseOVE->getSourceExpr()).rebuild(E);
John McCalle9290822011-11-30 04:42:31 +00001585 } else {
1586 llvm_unreachable("unknown pseudo-object kind!");
1587 }
1588}
1589
1590/// Given a pseudo-object expression, recreate what it looks like
1591/// syntactically without the attendant OpaqueValueExprs.
1592///
1593/// This is a hack which should be removed when TreeTransform is
1594/// capable of rebuilding a tree without stripping implicit
1595/// operations.
1596Expr *Sema::recreateSyntacticForm(PseudoObjectExpr *E) {
1597 Expr *syntax = E->getSyntacticForm();
1598 if (UnaryOperator *uop = dyn_cast<UnaryOperator>(syntax)) {
1599 Expr *op = stripOpaqueValuesFromPseudoObjectRef(*this, uop->getSubExpr());
1600 return new (Context) UnaryOperator(op, uop->getOpcode(), uop->getType(),
1601 uop->getValueKind(), uop->getObjectKind(),
1602 uop->getOperatorLoc());
1603 } else if (CompoundAssignOperator *cop
1604 = dyn_cast<CompoundAssignOperator>(syntax)) {
1605 Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, cop->getLHS());
1606 Expr *rhs = cast<OpaqueValueExpr>(cop->getRHS())->getSourceExpr();
1607 return new (Context) CompoundAssignOperator(lhs, rhs, cop->getOpcode(),
1608 cop->getType(),
1609 cop->getValueKind(),
1610 cop->getObjectKind(),
1611 cop->getComputationLHSType(),
1612 cop->getComputationResultType(),
Lang Hames5de91cc2012-10-02 04:45:10 +00001613 cop->getOperatorLoc(), false);
John McCalle9290822011-11-30 04:42:31 +00001614 } else if (BinaryOperator *bop = dyn_cast<BinaryOperator>(syntax)) {
1615 Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, bop->getLHS());
1616 Expr *rhs = cast<OpaqueValueExpr>(bop->getRHS())->getSourceExpr();
1617 return new (Context) BinaryOperator(lhs, rhs, bop->getOpcode(),
1618 bop->getType(), bop->getValueKind(),
1619 bop->getObjectKind(),
Lang Hames5de91cc2012-10-02 04:45:10 +00001620 bop->getOperatorLoc(), false);
John McCalle9290822011-11-30 04:42:31 +00001621 } else {
1622 assert(syntax->hasPlaceholderType(BuiltinType::PseudoObject));
1623 return stripOpaqueValuesFromPseudoObjectRef(*this, syntax);
1624 }
1625}