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