SemaExprMember.cpp revision 224145
1//===--- SemaExprMember.cpp - Semantic Analysis for Expressions -----------===//
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 member access expressions.
11//
12//===----------------------------------------------------------------------===//
13#include "clang/Sema/SemaInternal.h"
14#include "clang/Sema/Lookup.h"
15#include "clang/Sema/Scope.h"
16#include "clang/AST/DeclCXX.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/ExprObjC.h"
21#include "clang/Lex/Preprocessor.h"
22
23using namespace clang;
24using namespace sema;
25
26/// Determines if the given class is provably not derived from all of
27/// the prospective base classes.
28static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
29                                     CXXRecordDecl *Record,
30                            const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
31  if (Bases.count(Record->getCanonicalDecl()))
32    return false;
33
34  RecordDecl *RD = Record->getDefinition();
35  if (!RD) return false;
36  Record = cast<CXXRecordDecl>(RD);
37
38  for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
39         E = Record->bases_end(); I != E; ++I) {
40    CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
41    CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
42    if (!BaseRT) return false;
43
44    CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
45    if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
46      return false;
47  }
48
49  return true;
50}
51
52enum IMAKind {
53  /// The reference is definitely not an instance member access.
54  IMA_Static,
55
56  /// The reference may be an implicit instance member access.
57  IMA_Mixed,
58
59  /// The reference may be to an instance member, but it is invalid if
60  /// so, because the context is not an instance method.
61  IMA_Mixed_StaticContext,
62
63  /// The reference may be to an instance member, but it is invalid if
64  /// so, because the context is from an unrelated class.
65  IMA_Mixed_Unrelated,
66
67  /// The reference is definitely an implicit instance member access.
68  IMA_Instance,
69
70  /// The reference may be to an unresolved using declaration.
71  IMA_Unresolved,
72
73  /// The reference may be to an unresolved using declaration and the
74  /// context is not an instance method.
75  IMA_Unresolved_StaticContext,
76
77  /// All possible referrents are instance members and the current
78  /// context is not an instance method.
79  IMA_Error_StaticContext,
80
81  /// All possible referrents are instance members of an unrelated
82  /// class.
83  IMA_Error_Unrelated
84};
85
86/// The given lookup names class member(s) and is not being used for
87/// an address-of-member expression.  Classify the type of access
88/// according to whether it's possible that this reference names an
89/// instance member.  This is best-effort; it is okay to
90/// conservatively answer "yes", in which case some errors will simply
91/// not be caught until template-instantiation.
92static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
93                                            Scope *CurScope,
94                                            const LookupResult &R) {
95  assert(!R.empty() && (*R.begin())->isCXXClassMember());
96
97  DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
98
99  bool isStaticContext =
100    (!isa<CXXMethodDecl>(DC) ||
101     cast<CXXMethodDecl>(DC)->isStatic());
102
103  // C++0x [expr.prim]p4:
104  //   Otherwise, if a member-declarator declares a non-static data member
105  // of a class X, the expression this is a prvalue of type "pointer to X"
106  // within the optional brace-or-equal-initializer.
107  if (CurScope->getFlags() & Scope::ThisScope)
108    isStaticContext = false;
109
110  if (R.isUnresolvableResult())
111    return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
112
113  // Collect all the declaring classes of instance members we find.
114  bool hasNonInstance = false;
115  bool hasField = false;
116  llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
117  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
118    NamedDecl *D = *I;
119
120    if (D->isCXXInstanceMember()) {
121      if (dyn_cast<FieldDecl>(D))
122        hasField = true;
123
124      CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
125      Classes.insert(R->getCanonicalDecl());
126    }
127    else
128      hasNonInstance = true;
129  }
130
131  // If we didn't find any instance members, it can't be an implicit
132  // member reference.
133  if (Classes.empty())
134    return IMA_Static;
135
136  // If the current context is not an instance method, it can't be
137  // an implicit member reference.
138  if (isStaticContext) {
139    if (hasNonInstance)
140        return IMA_Mixed_StaticContext;
141
142    if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
143      // C++0x [expr.prim.general]p10:
144      //   An id-expression that denotes a non-static data member or non-static
145      //   member function of a class can only be used:
146      //   (...)
147      //   - if that id-expression denotes a non-static data member and it
148      //     appears in an unevaluated operand.
149      const Sema::ExpressionEvaluationContextRecord& record
150        = SemaRef.ExprEvalContexts.back();
151      bool isUnevaluatedExpression = (record.Context == Sema::Unevaluated);
152      if (isUnevaluatedExpression)
153        return IMA_Mixed_StaticContext;
154    }
155
156    return IMA_Error_StaticContext;
157  }
158
159  CXXRecordDecl *contextClass;
160  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
161    contextClass = MD->getParent()->getCanonicalDecl();
162  else
163    contextClass = cast<CXXRecordDecl>(DC);
164
165  // [class.mfct.non-static]p3:
166  // ...is used in the body of a non-static member function of class X,
167  // if name lookup (3.4.1) resolves the name in the id-expression to a
168  // non-static non-type member of some class C [...]
169  // ...if C is not X or a base class of X, the class member access expression
170  // is ill-formed.
171  if (R.getNamingClass() &&
172      contextClass != R.getNamingClass()->getCanonicalDecl() &&
173      contextClass->isProvablyNotDerivedFrom(R.getNamingClass()))
174    return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
175
176  // If we can prove that the current context is unrelated to all the
177  // declaring classes, it can't be an implicit member reference (in
178  // which case it's an error if any of those members are selected).
179  if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
180    return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
181
182  return (hasNonInstance ? IMA_Mixed : IMA_Instance);
183}
184
185/// Diagnose a reference to a field with no object available.
186static void DiagnoseInstanceReference(Sema &SemaRef,
187                                      const CXXScopeSpec &SS,
188                                      NamedDecl *rep,
189                                      const DeclarationNameInfo &nameInfo) {
190  SourceLocation Loc = nameInfo.getLoc();
191  SourceRange Range(Loc);
192  if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
193
194  if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
195    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
196      if (MD->isStatic()) {
197        // "invalid use of member 'x' in static member function"
198        SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
199        << Range << nameInfo.getName();
200        return;
201      }
202    }
203
204    SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
205    << nameInfo.getName() << Range;
206    return;
207  }
208
209  SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
210}
211
212/// Builds an expression which might be an implicit member expression.
213ExprResult
214Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
215                                      LookupResult &R,
216                                const TemplateArgumentListInfo *TemplateArgs) {
217  switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) {
218  case IMA_Instance:
219    return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
220
221  case IMA_Mixed:
222  case IMA_Mixed_Unrelated:
223  case IMA_Unresolved:
224    return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
225
226  case IMA_Static:
227  case IMA_Mixed_StaticContext:
228  case IMA_Unresolved_StaticContext:
229    if (TemplateArgs)
230      return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
231    return BuildDeclarationNameExpr(SS, R, false);
232
233  case IMA_Error_StaticContext:
234  case IMA_Error_Unrelated:
235    DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
236                              R.getLookupNameInfo());
237    return ExprError();
238  }
239
240  llvm_unreachable("unexpected instance member access kind");
241  return ExprError();
242}
243
244/// Check an ext-vector component access expression.
245///
246/// VK should be set in advance to the value kind of the base
247/// expression.
248static QualType
249CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
250                        SourceLocation OpLoc, const IdentifierInfo *CompName,
251                        SourceLocation CompLoc) {
252  // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
253  // see FIXME there.
254  //
255  // FIXME: This logic can be greatly simplified by splitting it along
256  // halving/not halving and reworking the component checking.
257  const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
258
259  // The vector accessor can't exceed the number of elements.
260  const char *compStr = CompName->getNameStart();
261
262  // This flag determines whether or not the component is one of the four
263  // special names that indicate a subset of exactly half the elements are
264  // to be selected.
265  bool HalvingSwizzle = false;
266
267  // This flag determines whether or not CompName has an 's' char prefix,
268  // indicating that it is a string of hex values to be used as vector indices.
269  bool HexSwizzle = *compStr == 's' || *compStr == 'S';
270
271  bool HasRepeated = false;
272  bool HasIndex[16] = {};
273
274  int Idx;
275
276  // Check that we've found one of the special components, or that the component
277  // names must come from the same set.
278  if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
279      !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
280    HalvingSwizzle = true;
281  } else if (!HexSwizzle &&
282             (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
283    do {
284      if (HasIndex[Idx]) HasRepeated = true;
285      HasIndex[Idx] = true;
286      compStr++;
287    } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
288  } else {
289    if (HexSwizzle) compStr++;
290    while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
291      if (HasIndex[Idx]) HasRepeated = true;
292      HasIndex[Idx] = true;
293      compStr++;
294    }
295  }
296
297  if (!HalvingSwizzle && *compStr) {
298    // We didn't get to the end of the string. This means the component names
299    // didn't come from the same set *or* we encountered an illegal name.
300    S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
301      << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
302    return QualType();
303  }
304
305  // Ensure no component accessor exceeds the width of the vector type it
306  // operates on.
307  if (!HalvingSwizzle) {
308    compStr = CompName->getNameStart();
309
310    if (HexSwizzle)
311      compStr++;
312
313    while (*compStr) {
314      if (!vecType->isAccessorWithinNumElements(*compStr++)) {
315        S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
316          << baseType << SourceRange(CompLoc);
317        return QualType();
318      }
319    }
320  }
321
322  // The component accessor looks fine - now we need to compute the actual type.
323  // The vector type is implied by the component accessor. For example,
324  // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
325  // vec4.s0 is a float, vec4.s23 is a vec3, etc.
326  // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
327  unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
328                                     : CompName->getLength();
329  if (HexSwizzle)
330    CompSize--;
331
332  if (CompSize == 1)
333    return vecType->getElementType();
334
335  if (HasRepeated) VK = VK_RValue;
336
337  QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
338  // Now look up the TypeDefDecl from the vector type. Without this,
339  // diagostics look bad. We want extended vector types to appear built-in.
340  for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
341    if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
342      return S.Context.getTypedefType(S.ExtVectorDecls[i]);
343  }
344  return VT; // should never get here (a typedef type should always be found).
345}
346
347static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
348                                                IdentifierInfo *Member,
349                                                const Selector &Sel,
350                                                ASTContext &Context) {
351  if (Member)
352    if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
353      return PD;
354  if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
355    return OMD;
356
357  for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
358       E = PDecl->protocol_end(); I != E; ++I) {
359    if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
360                                                           Context))
361      return D;
362  }
363  return 0;
364}
365
366static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
367                                      IdentifierInfo *Member,
368                                      const Selector &Sel,
369                                      ASTContext &Context) {
370  // Check protocols on qualified interfaces.
371  Decl *GDecl = 0;
372  for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
373       E = QIdTy->qual_end(); I != E; ++I) {
374    if (Member)
375      if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
376        GDecl = PD;
377        break;
378      }
379    // Also must look for a getter or setter name which uses property syntax.
380    if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
381      GDecl = OMD;
382      break;
383    }
384  }
385  if (!GDecl) {
386    for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
387         E = QIdTy->qual_end(); I != E; ++I) {
388      // Search in the protocol-qualifier list of current protocol.
389      GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
390                                                       Context);
391      if (GDecl)
392        return GDecl;
393    }
394  }
395  return GDecl;
396}
397
398ExprResult
399Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
400                               bool IsArrow, SourceLocation OpLoc,
401                               const CXXScopeSpec &SS,
402                               NamedDecl *FirstQualifierInScope,
403                               const DeclarationNameInfo &NameInfo,
404                               const TemplateArgumentListInfo *TemplateArgs) {
405  // Even in dependent contexts, try to diagnose base expressions with
406  // obviously wrong types, e.g.:
407  //
408  // T* t;
409  // t.f;
410  //
411  // In Obj-C++, however, the above expression is valid, since it could be
412  // accessing the 'f' property if T is an Obj-C interface. The extra check
413  // allows this, while still reporting an error if T is a struct pointer.
414  if (!IsArrow) {
415    const PointerType *PT = BaseType->getAs<PointerType>();
416    if (PT && (!getLangOptions().ObjC1 ||
417               PT->getPointeeType()->isRecordType())) {
418      assert(BaseExpr && "cannot happen with implicit member accesses");
419      Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
420        << BaseType << BaseExpr->getSourceRange();
421      return ExprError();
422    }
423  }
424
425  assert(BaseType->isDependentType() ||
426         NameInfo.getName().isDependentName() ||
427         isDependentScopeSpecifier(SS));
428
429  // Get the type being accessed in BaseType.  If this is an arrow, the BaseExpr
430  // must have pointer type, and the accessed type is the pointee.
431  return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
432                                                   IsArrow, OpLoc,
433                                               SS.getWithLocInContext(Context),
434                                                   FirstQualifierInScope,
435                                                   NameInfo, TemplateArgs));
436}
437
438/// We know that the given qualified member reference points only to
439/// declarations which do not belong to the static type of the base
440/// expression.  Diagnose the problem.
441static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
442                                             Expr *BaseExpr,
443                                             QualType BaseType,
444                                             const CXXScopeSpec &SS,
445                                             NamedDecl *rep,
446                                       const DeclarationNameInfo &nameInfo) {
447  // If this is an implicit member access, use a different set of
448  // diagnostics.
449  if (!BaseExpr)
450    return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
451
452  SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
453    << SS.getRange() << rep << BaseType;
454}
455
456// Check whether the declarations we found through a nested-name
457// specifier in a member expression are actually members of the base
458// type.  The restriction here is:
459//
460//   C++ [expr.ref]p2:
461//     ... In these cases, the id-expression shall name a
462//     member of the class or of one of its base classes.
463//
464// So it's perfectly legitimate for the nested-name specifier to name
465// an unrelated class, and for us to find an overload set including
466// decls from classes which are not superclasses, as long as the decl
467// we actually pick through overload resolution is from a superclass.
468bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
469                                         QualType BaseType,
470                                         const CXXScopeSpec &SS,
471                                         const LookupResult &R) {
472  const RecordType *BaseRT = BaseType->getAs<RecordType>();
473  if (!BaseRT) {
474    // We can't check this yet because the base type is still
475    // dependent.
476    assert(BaseType->isDependentType());
477    return false;
478  }
479  CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
480
481  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
482    // If this is an implicit member reference and we find a
483    // non-instance member, it's not an error.
484    if (!BaseExpr && !(*I)->isCXXInstanceMember())
485      return false;
486
487    // Note that we use the DC of the decl, not the underlying decl.
488    DeclContext *DC = (*I)->getDeclContext();
489    while (DC->isTransparentContext())
490      DC = DC->getParent();
491
492    if (!DC->isRecord())
493      continue;
494
495    llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
496    MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
497
498    if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
499      return false;
500  }
501
502  DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
503                                   R.getRepresentativeDecl(),
504                                   R.getLookupNameInfo());
505  return true;
506}
507
508static bool
509LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
510                         SourceRange BaseRange, const RecordType *RTy,
511                         SourceLocation OpLoc, CXXScopeSpec &SS,
512                         bool HasTemplateArgs) {
513  RecordDecl *RDecl = RTy->getDecl();
514  if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
515                              SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
516                                    << BaseRange))
517    return true;
518
519  if (HasTemplateArgs) {
520    // LookupTemplateName doesn't expect these both to exist simultaneously.
521    QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
522
523    bool MOUS;
524    SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
525    return false;
526  }
527
528  DeclContext *DC = RDecl;
529  if (SS.isSet()) {
530    // If the member name was a qualified-id, look into the
531    // nested-name-specifier.
532    DC = SemaRef.computeDeclContext(SS, false);
533
534    if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
535      SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
536        << SS.getRange() << DC;
537      return true;
538    }
539
540    assert(DC && "Cannot handle non-computable dependent contexts in lookup");
541
542    if (!isa<TypeDecl>(DC)) {
543      SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
544        << DC << SS.getRange();
545      return true;
546    }
547  }
548
549  // The record definition is complete, now look up the member.
550  SemaRef.LookupQualifiedName(R, DC);
551
552  if (!R.empty())
553    return false;
554
555  // We didn't find anything with the given name, so try to correct
556  // for typos.
557  DeclarationName Name = R.getLookupName();
558  TypoCorrection Corrected = SemaRef.CorrectTypo(R.getLookupNameInfo(),
559                                                 R.getLookupKind(), NULL,
560                                                 &SS, DC, false,
561                                                 Sema::CTC_MemberLookup);
562  NamedDecl *ND = Corrected.getCorrectionDecl();
563  R.clear();
564  if (ND && (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))) {
565    std::string CorrectedStr(
566        Corrected.getAsString(SemaRef.getLangOptions()));
567    std::string CorrectedQuotedStr(
568        Corrected.getQuoted(SemaRef.getLangOptions()));
569    R.setLookupName(Corrected.getCorrection());
570    R.addDecl(ND);
571    SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
572      << Name << DC << CorrectedQuotedStr << SS.getRange()
573      << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
574    SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
575      << ND->getDeclName();
576  }
577
578  return false;
579}
580
581ExprResult
582Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
583                               SourceLocation OpLoc, bool IsArrow,
584                               CXXScopeSpec &SS,
585                               NamedDecl *FirstQualifierInScope,
586                               const DeclarationNameInfo &NameInfo,
587                               const TemplateArgumentListInfo *TemplateArgs) {
588  if (BaseType->isDependentType() ||
589      (SS.isSet() && isDependentScopeSpecifier(SS)))
590    return ActOnDependentMemberExpr(Base, BaseType,
591                                    IsArrow, OpLoc,
592                                    SS, FirstQualifierInScope,
593                                    NameInfo, TemplateArgs);
594
595  LookupResult R(*this, NameInfo, LookupMemberName);
596
597  // Implicit member accesses.
598  if (!Base) {
599    QualType RecordTy = BaseType;
600    if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
601    if (LookupMemberExprInRecord(*this, R, SourceRange(),
602                                 RecordTy->getAs<RecordType>(),
603                                 OpLoc, SS, TemplateArgs != 0))
604      return ExprError();
605
606  // Explicit member accesses.
607  } else {
608    ExprResult BaseResult = Owned(Base);
609    ExprResult Result =
610      LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
611                       SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
612
613    if (BaseResult.isInvalid())
614      return ExprError();
615    Base = BaseResult.take();
616
617    if (Result.isInvalid()) {
618      Owned(Base);
619      return ExprError();
620    }
621
622    if (Result.get())
623      return move(Result);
624
625    // LookupMemberExpr can modify Base, and thus change BaseType
626    BaseType = Base->getType();
627  }
628
629  return BuildMemberReferenceExpr(Base, BaseType,
630                                  OpLoc, IsArrow, SS, FirstQualifierInScope,
631                                  R, TemplateArgs);
632}
633
634static ExprResult
635BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
636                        const CXXScopeSpec &SS, FieldDecl *Field,
637                        DeclAccessPair FoundDecl,
638                        const DeclarationNameInfo &MemberNameInfo);
639
640ExprResult
641Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
642                                               SourceLocation loc,
643                                               IndirectFieldDecl *indirectField,
644                                               Expr *baseObjectExpr,
645                                               SourceLocation opLoc) {
646  // First, build the expression that refers to the base object.
647
648  bool baseObjectIsPointer = false;
649  Qualifiers baseQuals;
650
651  // Case 1:  the base of the indirect field is not a field.
652  VarDecl *baseVariable = indirectField->getVarDecl();
653  CXXScopeSpec EmptySS;
654  if (baseVariable) {
655    assert(baseVariable->getType()->isRecordType());
656
657    // In principle we could have a member access expression that
658    // accesses an anonymous struct/union that's a static member of
659    // the base object's class.  However, under the current standard,
660    // static data members cannot be anonymous structs or unions.
661    // Supporting this is as easy as building a MemberExpr here.
662    assert(!baseObjectExpr && "anonymous struct/union is static data member?");
663
664    DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
665
666    ExprResult result
667      = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
668    if (result.isInvalid()) return ExprError();
669
670    baseObjectExpr = result.take();
671    baseObjectIsPointer = false;
672    baseQuals = baseObjectExpr->getType().getQualifiers();
673
674    // Case 2: the base of the indirect field is a field and the user
675    // wrote a member expression.
676  } else if (baseObjectExpr) {
677    // The caller provided the base object expression. Determine
678    // whether its a pointer and whether it adds any qualifiers to the
679    // anonymous struct/union fields we're looking into.
680    QualType objectType = baseObjectExpr->getType();
681
682    if (const PointerType *ptr = objectType->getAs<PointerType>()) {
683      baseObjectIsPointer = true;
684      objectType = ptr->getPointeeType();
685    } else {
686      baseObjectIsPointer = false;
687    }
688    baseQuals = objectType.getQualifiers();
689
690    // Case 3: the base of the indirect field is a field and we should
691    // build an implicit member access.
692  } else {
693    // We've found a member of an anonymous struct/union that is
694    // inside a non-anonymous struct/union, so in a well-formed
695    // program our base object expression is "this".
696    QualType ThisTy = getAndCaptureCurrentThisType();
697    if (ThisTy.isNull()) {
698      Diag(loc, diag::err_invalid_member_use_in_static_method)
699        << indirectField->getDeclName();
700      return ExprError();
701    }
702
703    // Our base object expression is "this".
704    baseObjectExpr
705      = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
706    baseObjectIsPointer = true;
707    baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
708  }
709
710  // Build the implicit member references to the field of the
711  // anonymous struct/union.
712  Expr *result = baseObjectExpr;
713  IndirectFieldDecl::chain_iterator
714  FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
715
716  // Build the first member access in the chain with full information.
717  if (!baseVariable) {
718    FieldDecl *field = cast<FieldDecl>(*FI);
719
720    // FIXME: use the real found-decl info!
721    DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
722
723    // Make a nameInfo that properly uses the anonymous name.
724    DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
725
726    result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
727                                     EmptySS, field, foundDecl,
728                                     memberNameInfo).take();
729    baseObjectIsPointer = false;
730
731    // FIXME: check qualified member access
732  }
733
734  // In all cases, we should now skip the first declaration in the chain.
735  ++FI;
736
737  while (FI != FEnd) {
738    FieldDecl *field = cast<FieldDecl>(*FI++);
739
740    // FIXME: these are somewhat meaningless
741    DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
742    DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
743
744    result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
745                                     (FI == FEnd? SS : EmptySS), field,
746                                     foundDecl, memberNameInfo).take();
747  }
748
749  return Owned(result);
750}
751
752/// \brief Build a MemberExpr AST node.
753static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
754                                   const CXXScopeSpec &SS, ValueDecl *Member,
755                                   DeclAccessPair FoundDecl,
756                                   const DeclarationNameInfo &MemberNameInfo,
757                                   QualType Ty,
758                                   ExprValueKind VK, ExprObjectKind OK,
759                                   const TemplateArgumentListInfo *TemplateArgs = 0) {
760  return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
761                            Member, FoundDecl, MemberNameInfo,
762                            TemplateArgs, Ty, VK, OK);
763}
764
765ExprResult
766Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
767                               SourceLocation OpLoc, bool IsArrow,
768                               const CXXScopeSpec &SS,
769                               NamedDecl *FirstQualifierInScope,
770                               LookupResult &R,
771                         const TemplateArgumentListInfo *TemplateArgs,
772                               bool SuppressQualifierCheck) {
773  QualType BaseType = BaseExprType;
774  if (IsArrow) {
775    assert(BaseType->isPointerType());
776    BaseType = BaseType->getAs<PointerType>()->getPointeeType();
777  }
778  R.setBaseObjectType(BaseType);
779
780  const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
781  DeclarationName MemberName = MemberNameInfo.getName();
782  SourceLocation MemberLoc = MemberNameInfo.getLoc();
783
784  if (R.isAmbiguous())
785    return ExprError();
786
787  if (R.empty()) {
788    // Rederive where we looked up.
789    DeclContext *DC = (SS.isSet()
790                       ? computeDeclContext(SS, false)
791                       : BaseType->getAs<RecordType>()->getDecl());
792
793    Diag(R.getNameLoc(), diag::err_no_member)
794      << MemberName << DC
795      << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
796    return ExprError();
797  }
798
799  // Diagnose lookups that find only declarations from a non-base
800  // type.  This is possible for either qualified lookups (which may
801  // have been qualified with an unrelated type) or implicit member
802  // expressions (which were found with unqualified lookup and thus
803  // may have come from an enclosing scope).  Note that it's okay for
804  // lookup to find declarations from a non-base type as long as those
805  // aren't the ones picked by overload resolution.
806  if ((SS.isSet() || !BaseExpr ||
807       (isa<CXXThisExpr>(BaseExpr) &&
808        cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
809      !SuppressQualifierCheck &&
810      CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
811    return ExprError();
812
813  // Construct an unresolved result if we in fact got an unresolved
814  // result.
815  if (R.isOverloadedResult() || R.isUnresolvableResult()) {
816    // Suppress any lookup-related diagnostics; we'll do these when we
817    // pick a member.
818    R.suppressDiagnostics();
819
820    UnresolvedMemberExpr *MemExpr
821      = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
822                                     BaseExpr, BaseExprType,
823                                     IsArrow, OpLoc,
824                                     SS.getWithLocInContext(Context),
825                                     MemberNameInfo,
826                                     TemplateArgs, R.begin(), R.end());
827
828    return Owned(MemExpr);
829  }
830
831  assert(R.isSingleResult());
832  DeclAccessPair FoundDecl = R.begin().getPair();
833  NamedDecl *MemberDecl = R.getFoundDecl();
834
835  // FIXME: diagnose the presence of template arguments now.
836
837  // If the decl being referenced had an error, return an error for this
838  // sub-expr without emitting another error, in order to avoid cascading
839  // error cases.
840  if (MemberDecl->isInvalidDecl())
841    return ExprError();
842
843  // Handle the implicit-member-access case.
844  if (!BaseExpr) {
845    // If this is not an instance member, convert to a non-member access.
846    if (!MemberDecl->isCXXInstanceMember())
847      return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
848
849    SourceLocation Loc = R.getNameLoc();
850    if (SS.getRange().isValid())
851      Loc = SS.getRange().getBegin();
852    BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
853  }
854
855  bool ShouldCheckUse = true;
856  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
857    // Don't diagnose the use of a virtual member function unless it's
858    // explicitly qualified.
859    if (MD->isVirtual() && !SS.isSet())
860      ShouldCheckUse = false;
861  }
862
863  // Check the use of this member.
864  if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
865    Owned(BaseExpr);
866    return ExprError();
867  }
868
869  // Perform a property load on the base regardless of whether we
870  // actually need it for the declaration.
871  if (BaseExpr->getObjectKind() == OK_ObjCProperty) {
872    ExprResult Result = ConvertPropertyForRValue(BaseExpr);
873    if (Result.isInvalid())
874      return ExprError();
875    BaseExpr = Result.take();
876  }
877
878  if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
879    return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
880                                   SS, FD, FoundDecl, MemberNameInfo);
881
882  if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
883    // We may have found a field within an anonymous union or struct
884    // (C++ [class.union]).
885    return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
886                                                    BaseExpr, OpLoc);
887
888  if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
889    MarkDeclarationReferenced(MemberLoc, Var);
890    return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
891                                 Var, FoundDecl, MemberNameInfo,
892                                 Var->getType().getNonReferenceType(),
893                                 VK_LValue, OK_Ordinary));
894  }
895
896  if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
897    ExprValueKind valueKind;
898    QualType type;
899    if (MemberFn->isInstance()) {
900      valueKind = VK_RValue;
901      type = Context.BoundMemberTy;
902    } else {
903      valueKind = VK_LValue;
904      type = MemberFn->getType();
905    }
906
907    MarkDeclarationReferenced(MemberLoc, MemberDecl);
908    return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
909                                 MemberFn, FoundDecl, MemberNameInfo,
910                                 type, valueKind, OK_Ordinary));
911  }
912  assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
913
914  if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
915    MarkDeclarationReferenced(MemberLoc, MemberDecl);
916    return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
917                                 Enum, FoundDecl, MemberNameInfo,
918                                 Enum->getType(), VK_RValue, OK_Ordinary));
919  }
920
921  Owned(BaseExpr);
922
923  // We found something that we didn't expect. Complain.
924  if (isa<TypeDecl>(MemberDecl))
925    Diag(MemberLoc, diag::err_typecheck_member_reference_type)
926      << MemberName << BaseType << int(IsArrow);
927  else
928    Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
929      << MemberName << BaseType << int(IsArrow);
930
931  Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
932    << MemberName;
933  R.suppressDiagnostics();
934  return ExprError();
935}
936
937/// Given that normal member access failed on the given expression,
938/// and given that the expression's type involves builtin-id or
939/// builtin-Class, decide whether substituting in the redefinition
940/// types would be profitable.  The redefinition type is whatever
941/// this translation unit tried to typedef to id/Class;  we store
942/// it to the side and then re-use it in places like this.
943static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
944  const ObjCObjectPointerType *opty
945    = base.get()->getType()->getAs<ObjCObjectPointerType>();
946  if (!opty) return false;
947
948  const ObjCObjectType *ty = opty->getObjectType();
949
950  QualType redef;
951  if (ty->isObjCId()) {
952    redef = S.Context.ObjCIdRedefinitionType;
953  } else if (ty->isObjCClass()) {
954    redef = S.Context.ObjCClassRedefinitionType;
955  } else {
956    return false;
957  }
958
959  // Do the substitution as long as the redefinition type isn't just a
960  // possibly-qualified pointer to builtin-id or builtin-Class again.
961  opty = redef->getAs<ObjCObjectPointerType>();
962  if (opty && !opty->getObjectType()->getInterface() != 0)
963    return false;
964
965  base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
966  return true;
967}
968
969/// Look up the given member of the given non-type-dependent
970/// expression.  This can return in one of two ways:
971///  * If it returns a sentinel null-but-valid result, the caller will
972///    assume that lookup was performed and the results written into
973///    the provided structure.  It will take over from there.
974///  * Otherwise, the returned expression will be produced in place of
975///    an ordinary member expression.
976///
977/// The ObjCImpDecl bit is a gross hack that will need to be properly
978/// fixed for ObjC++.
979ExprResult
980Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
981                       bool &IsArrow, SourceLocation OpLoc,
982                       CXXScopeSpec &SS,
983                       Decl *ObjCImpDecl, bool HasTemplateArgs) {
984  assert(BaseExpr.get() && "no base expression");
985
986  // Perform default conversions.
987  BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
988
989  if (IsArrow) {
990    BaseExpr = DefaultLvalueConversion(BaseExpr.take());
991    if (BaseExpr.isInvalid())
992      return ExprError();
993  }
994
995  QualType BaseType = BaseExpr.get()->getType();
996  assert(!BaseType->isDependentType());
997
998  DeclarationName MemberName = R.getLookupName();
999  SourceLocation MemberLoc = R.getNameLoc();
1000
1001  // For later type-checking purposes, turn arrow accesses into dot
1002  // accesses.  The only access type we support that doesn't follow
1003  // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1004  // and those never use arrows, so this is unaffected.
1005  if (IsArrow) {
1006    if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1007      BaseType = Ptr->getPointeeType();
1008    else if (const ObjCObjectPointerType *Ptr
1009               = BaseType->getAs<ObjCObjectPointerType>())
1010      BaseType = Ptr->getPointeeType();
1011    else if (BaseType->isRecordType()) {
1012      // Recover from arrow accesses to records, e.g.:
1013      //   struct MyRecord foo;
1014      //   foo->bar
1015      // This is actually well-formed in C++ if MyRecord has an
1016      // overloaded operator->, but that should have been dealt with
1017      // by now.
1018      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1019        << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1020        << FixItHint::CreateReplacement(OpLoc, ".");
1021      IsArrow = false;
1022    } else if (BaseType == Context.BoundMemberTy) {
1023      goto fail;
1024    } else {
1025      Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1026        << BaseType << BaseExpr.get()->getSourceRange();
1027      return ExprError();
1028    }
1029  }
1030
1031  // Handle field access to simple records.
1032  if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
1033    if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
1034                                 RTy, OpLoc, SS, HasTemplateArgs))
1035      return ExprError();
1036
1037    // Returning valid-but-null is how we indicate to the caller that
1038    // the lookup result was filled in.
1039    return Owned((Expr*) 0);
1040  }
1041
1042  // Handle ivar access to Objective-C objects.
1043  if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
1044    IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1045
1046    // There are three cases for the base type:
1047    //   - builtin id (qualified or unqualified)
1048    //   - builtin Class (qualified or unqualified)
1049    //   - an interface
1050    ObjCInterfaceDecl *IDecl = OTy->getInterface();
1051    if (!IDecl) {
1052      if (getLangOptions().ObjCAutoRefCount &&
1053          (OTy->isObjCId() || OTy->isObjCClass()))
1054        goto fail;
1055      // There's an implicit 'isa' ivar on all objects.
1056      // But we only actually find it this way on objects of type 'id',
1057      // apparently.
1058      if (OTy->isObjCId() && Member->isStr("isa"))
1059        return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
1060                                               Context.getObjCClassType()));
1061
1062      if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1063        return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1064                                ObjCImpDecl, HasTemplateArgs);
1065      goto fail;
1066    }
1067
1068    ObjCInterfaceDecl *ClassDeclared;
1069    ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1070
1071    if (!IV) {
1072      // Attempt to correct for typos in ivar names.
1073      LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
1074                       LookupMemberName);
1075      TypoCorrection Corrected = CorrectTypo(
1076          R.getLookupNameInfo(), LookupMemberName, NULL, NULL, IDecl, false,
1077          IsArrow ? CTC_ObjCIvarLookup : CTC_ObjCPropertyLookup);
1078      if ((IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>())) {
1079        Diag(R.getNameLoc(),
1080             diag::err_typecheck_member_reference_ivar_suggest)
1081          << IDecl->getDeclName() << MemberName << IV->getDeclName()
1082          << FixItHint::CreateReplacement(R.getNameLoc(),
1083                                          IV->getNameAsString());
1084        Diag(IV->getLocation(), diag::note_previous_decl)
1085          << IV->getDeclName();
1086      } else {
1087        if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
1088          Diag(MemberLoc,
1089          diag::err_property_found_suggest)
1090          << Member << BaseExpr.get()->getType()
1091          << FixItHint::CreateReplacement(OpLoc, ".");
1092          return ExprError();
1093        }
1094        Res.clear();
1095        Res.setLookupName(Member);
1096
1097        Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1098          << IDecl->getDeclName() << MemberName
1099          << BaseExpr.get()->getSourceRange();
1100        return ExprError();
1101      }
1102    }
1103
1104    // If the decl being referenced had an error, return an error for this
1105    // sub-expr without emitting another error, in order to avoid cascading
1106    // error cases.
1107    if (IV->isInvalidDecl())
1108      return ExprError();
1109
1110    // Check whether we can reference this field.
1111    if (DiagnoseUseOfDecl(IV, MemberLoc))
1112      return ExprError();
1113    if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1114        IV->getAccessControl() != ObjCIvarDecl::Package) {
1115      ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1116      if (ObjCMethodDecl *MD = getCurMethodDecl())
1117        ClassOfMethodDecl =  MD->getClassInterface();
1118      else if (ObjCImpDecl && getCurFunctionDecl()) {
1119        // Case of a c-function declared inside an objc implementation.
1120        // FIXME: For a c-style function nested inside an objc implementation
1121        // class, there is no implementation context available, so we pass
1122        // down the context as argument to this routine. Ideally, this context
1123        // need be passed down in the AST node and somehow calculated from the
1124        // AST for a function decl.
1125        if (ObjCImplementationDecl *IMPD =
1126              dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1127          ClassOfMethodDecl = IMPD->getClassInterface();
1128        else if (ObjCCategoryImplDecl* CatImplClass =
1129                   dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1130          ClassOfMethodDecl = CatImplClass->getClassInterface();
1131      }
1132
1133      if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1134        if (ClassDeclared != IDecl ||
1135            ClassOfMethodDecl != ClassDeclared)
1136          Diag(MemberLoc, diag::error_private_ivar_access)
1137            << IV->getDeclName();
1138      } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1139        // @protected
1140        Diag(MemberLoc, diag::error_protected_ivar_access)
1141          << IV->getDeclName();
1142    }
1143    if (getLangOptions().ObjCAutoRefCount) {
1144      Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1145      if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1146        if (UO->getOpcode() == UO_Deref)
1147          BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1148
1149      if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
1150        if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
1151          Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
1152    }
1153
1154    return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1155                                               MemberLoc, BaseExpr.take(),
1156                                               IsArrow));
1157  }
1158
1159  // Objective-C property access.
1160  const ObjCObjectPointerType *OPT;
1161  if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
1162    // This actually uses the base as an r-value.
1163    BaseExpr = DefaultLvalueConversion(BaseExpr.take());
1164    if (BaseExpr.isInvalid())
1165      return ExprError();
1166
1167    assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
1168
1169    IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1170
1171    const ObjCObjectType *OT = OPT->getObjectType();
1172
1173    // id, with and without qualifiers.
1174    if (OT->isObjCId()) {
1175      // Check protocols on qualified interfaces.
1176      Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1177      if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
1178        if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1179          // Check the use of this declaration
1180          if (DiagnoseUseOfDecl(PD, MemberLoc))
1181            return ExprError();
1182
1183          QualType T = PD->getType();
1184          if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
1185            T = getMessageSendResultType(BaseType, Getter, false, false);
1186
1187          return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
1188                                                         VK_LValue,
1189                                                         OK_ObjCProperty,
1190                                                         MemberLoc,
1191                                                         BaseExpr.take()));
1192        }
1193
1194        if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1195          // Check the use of this method.
1196          if (DiagnoseUseOfDecl(OMD, MemberLoc))
1197            return ExprError();
1198          Selector SetterSel =
1199            SelectorTable::constructSetterName(PP.getIdentifierTable(),
1200                                               PP.getSelectorTable(), Member);
1201          ObjCMethodDecl *SMD = 0;
1202          if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
1203                                                     SetterSel, Context))
1204            SMD = dyn_cast<ObjCMethodDecl>(SDecl);
1205          QualType PType = getMessageSendResultType(BaseType, OMD, false,
1206                                                    false);
1207
1208          ExprValueKind VK = VK_LValue;
1209          if (!getLangOptions().CPlusPlus && PType.isCForbiddenLValueType())
1210            VK = VK_RValue;
1211          ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
1212
1213          return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
1214                                                         VK, OK,
1215                                                         MemberLoc, BaseExpr.take()));
1216        }
1217      }
1218      // Use of id.member can only be for a property reference. Do not
1219      // use the 'id' redefinition in this case.
1220      if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1221        return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1222                                ObjCImpDecl, HasTemplateArgs);
1223
1224      return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1225                         << MemberName << BaseType);
1226    }
1227
1228    // 'Class', unqualified only.
1229    if (OT->isObjCClass()) {
1230      // Only works in a method declaration (??!).
1231      ObjCMethodDecl *MD = getCurMethodDecl();
1232      if (!MD) {
1233        if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1234          return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1235                                  ObjCImpDecl, HasTemplateArgs);
1236
1237        goto fail;
1238      }
1239
1240      // Also must look for a getter name which uses property syntax.
1241      Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1242      ObjCInterfaceDecl *IFace = MD->getClassInterface();
1243      ObjCMethodDecl *Getter;
1244      if ((Getter = IFace->lookupClassMethod(Sel))) {
1245        // Check the use of this method.
1246        if (DiagnoseUseOfDecl(Getter, MemberLoc))
1247          return ExprError();
1248      } else
1249        Getter = IFace->lookupPrivateMethod(Sel, false);
1250      // If we found a getter then this may be a valid dot-reference, we
1251      // will look for the matching setter, in case it is needed.
1252      Selector SetterSel =
1253        SelectorTable::constructSetterName(PP.getIdentifierTable(),
1254                                           PP.getSelectorTable(), Member);
1255      ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1256      if (!Setter) {
1257        // If this reference is in an @implementation, also check for 'private'
1258        // methods.
1259        Setter = IFace->lookupPrivateMethod(SetterSel, false);
1260      }
1261      // Look through local category implementations associated with the class.
1262      if (!Setter)
1263        Setter = IFace->getCategoryClassMethod(SetterSel);
1264
1265      if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1266        return ExprError();
1267
1268      if (Getter || Setter) {
1269        QualType PType;
1270
1271        ExprValueKind VK = VK_LValue;
1272        if (Getter) {
1273          PType = getMessageSendResultType(QualType(OT, 0), Getter, true,
1274                                           false);
1275          if (!getLangOptions().CPlusPlus && PType.isCForbiddenLValueType())
1276            VK = VK_RValue;
1277        } else {
1278          // Get the expression type from Setter's incoming parameter.
1279          PType = (*(Setter->param_end() -1))->getType();
1280        }
1281        ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
1282
1283        // FIXME: we must check that the setter has property type.
1284        return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1285                                                       PType, VK, OK,
1286                                                       MemberLoc, BaseExpr.take()));
1287      }
1288
1289      if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1290        return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1291                                ObjCImpDecl, HasTemplateArgs);
1292
1293      return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1294                         << MemberName << BaseType);
1295    }
1296
1297    // Normal property access.
1298    return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc,
1299                                     MemberName, MemberLoc,
1300                                     SourceLocation(), QualType(), false);
1301  }
1302
1303  // Handle 'field access' to vectors, such as 'V.xx'.
1304  if (BaseType->isExtVectorType()) {
1305    // FIXME: this expr should store IsArrow.
1306    IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1307    ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
1308    QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
1309                                           Member, MemberLoc);
1310    if (ret.isNull())
1311      return ExprError();
1312
1313    return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
1314                                                    *Member, MemberLoc));
1315  }
1316
1317  // Adjust builtin-sel to the appropriate redefinition type if that's
1318  // not just a pointer to builtin-sel again.
1319  if (IsArrow &&
1320      BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
1321      !Context.ObjCSelRedefinitionType->isObjCSelType()) {
1322    BaseExpr = ImpCastExprToType(BaseExpr.take(), Context.ObjCSelRedefinitionType,
1323                                 CK_BitCast);
1324    return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1325                            ObjCImpDecl, HasTemplateArgs);
1326  }
1327
1328  // Failure cases.
1329 fail:
1330
1331  // Recover from dot accesses to pointers, e.g.:
1332  //   type *foo;
1333  //   foo.bar
1334  // This is actually well-formed in two cases:
1335  //   - 'type' is an Objective C type
1336  //   - 'bar' is a pseudo-destructor name which happens to refer to
1337  //     the appropriate pointer type
1338  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1339    if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1340        MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1341      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1342        << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1343          << FixItHint::CreateReplacement(OpLoc, "->");
1344
1345      // Recurse as an -> access.
1346      IsArrow = true;
1347      return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1348                              ObjCImpDecl, HasTemplateArgs);
1349    }
1350  }
1351
1352  // If the user is trying to apply -> or . to a function name, it's probably
1353  // because they forgot parentheses to call that function.
1354  QualType ZeroArgCallTy;
1355  UnresolvedSet<4> Overloads;
1356  if (isExprCallable(*BaseExpr.get(), ZeroArgCallTy, Overloads)) {
1357    if (ZeroArgCallTy.isNull()) {
1358      Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
1359          << (Overloads.size() > 1) << 0 << BaseExpr.get()->getSourceRange();
1360      UnresolvedSet<2> PlausibleOverloads;
1361      for (OverloadExpr::decls_iterator It = Overloads.begin(),
1362           DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
1363        const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
1364        QualType OverloadResultTy = OverloadDecl->getResultType();
1365        if ((!IsArrow && OverloadResultTy->isRecordType()) ||
1366            (IsArrow && OverloadResultTy->isPointerType() &&
1367             OverloadResultTy->getPointeeType()->isRecordType()))
1368          PlausibleOverloads.addDecl(It.getDecl());
1369      }
1370      NoteOverloads(PlausibleOverloads, BaseExpr.get()->getExprLoc());
1371      return ExprError();
1372    }
1373    if ((!IsArrow && ZeroArgCallTy->isRecordType()) ||
1374        (IsArrow && ZeroArgCallTy->isPointerType() &&
1375         ZeroArgCallTy->getPointeeType()->isRecordType())) {
1376      // At this point, we know BaseExpr looks like it's potentially callable
1377      // with 0 arguments, and that it returns something of a reasonable type,
1378      // so we can emit a fixit and carry on pretending that BaseExpr was
1379      // actually a CallExpr.
1380      SourceLocation ParenInsertionLoc =
1381          PP.getLocForEndOfToken(BaseExpr.get()->getLocEnd());
1382      Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
1383          << (Overloads.size() > 1) << 1 << BaseExpr.get()->getSourceRange()
1384          << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
1385      // FIXME: Try this before emitting the fixit, and suppress diagnostics
1386      // while doing so.
1387      ExprResult NewBase =
1388          ActOnCallExpr(0, BaseExpr.take(), ParenInsertionLoc,
1389                        MultiExprArg(*this, 0, 0),
1390                        ParenInsertionLoc.getFileLocWithOffset(1));
1391      if (NewBase.isInvalid())
1392        return ExprError();
1393      BaseExpr = NewBase;
1394      BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
1395      return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1396                              ObjCImpDecl, HasTemplateArgs);
1397    }
1398  }
1399
1400  Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
1401    << BaseType << BaseExpr.get()->getSourceRange();
1402
1403  return ExprError();
1404}
1405
1406/// The main callback when the parser finds something like
1407///   expression . [nested-name-specifier] identifier
1408///   expression -> [nested-name-specifier] identifier
1409/// where 'identifier' encompasses a fairly broad spectrum of
1410/// possibilities, including destructor and operator references.
1411///
1412/// \param OpKind either tok::arrow or tok::period
1413/// \param HasTrailingLParen whether the next token is '(', which
1414///   is used to diagnose mis-uses of special members that can
1415///   only be called
1416/// \param ObjCImpDecl the current ObjC @implementation decl;
1417///   this is an ugly hack around the fact that ObjC @implementations
1418///   aren't properly put in the context chain
1419ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1420                                       SourceLocation OpLoc,
1421                                       tok::TokenKind OpKind,
1422                                       CXXScopeSpec &SS,
1423                                       UnqualifiedId &Id,
1424                                       Decl *ObjCImpDecl,
1425                                       bool HasTrailingLParen) {
1426  if (SS.isSet() && SS.isInvalid())
1427    return ExprError();
1428
1429  // Warn about the explicit constructor calls Microsoft extension.
1430  if (getLangOptions().Microsoft &&
1431      Id.getKind() == UnqualifiedId::IK_ConstructorName)
1432    Diag(Id.getSourceRange().getBegin(),
1433         diag::ext_ms_explicit_constructor_call);
1434
1435  TemplateArgumentListInfo TemplateArgsBuffer;
1436
1437  // Decompose the name into its component parts.
1438  DeclarationNameInfo NameInfo;
1439  const TemplateArgumentListInfo *TemplateArgs;
1440  DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1441                         NameInfo, TemplateArgs);
1442
1443  DeclarationName Name = NameInfo.getName();
1444  bool IsArrow = (OpKind == tok::arrow);
1445
1446  NamedDecl *FirstQualifierInScope
1447    = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
1448                       static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
1449
1450  // This is a postfix expression, so get rid of ParenListExprs.
1451  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1452  if (Result.isInvalid()) return ExprError();
1453  Base = Result.take();
1454
1455  if (Base->getType()->isDependentType() || Name.isDependentName() ||
1456      isDependentScopeSpecifier(SS)) {
1457    Result = ActOnDependentMemberExpr(Base, Base->getType(),
1458                                      IsArrow, OpLoc,
1459                                      SS, FirstQualifierInScope,
1460                                      NameInfo, TemplateArgs);
1461  } else {
1462    LookupResult R(*this, NameInfo, LookupMemberName);
1463    ExprResult BaseResult = Owned(Base);
1464    Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
1465                              SS, ObjCImpDecl, TemplateArgs != 0);
1466    if (BaseResult.isInvalid())
1467      return ExprError();
1468    Base = BaseResult.take();
1469
1470    if (Result.isInvalid()) {
1471      Owned(Base);
1472      return ExprError();
1473    }
1474
1475    if (Result.get()) {
1476      // The only way a reference to a destructor can be used is to
1477      // immediately call it, which falls into this case.  If the
1478      // next token is not a '(', produce a diagnostic and build the
1479      // call now.
1480      if (!HasTrailingLParen &&
1481          Id.getKind() == UnqualifiedId::IK_DestructorName)
1482        return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
1483
1484      return move(Result);
1485    }
1486
1487    Result = BuildMemberReferenceExpr(Base, Base->getType(),
1488                                      OpLoc, IsArrow, SS, FirstQualifierInScope,
1489                                      R, TemplateArgs);
1490  }
1491
1492  return move(Result);
1493}
1494
1495static ExprResult
1496BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1497                        const CXXScopeSpec &SS, FieldDecl *Field,
1498                        DeclAccessPair FoundDecl,
1499                        const DeclarationNameInfo &MemberNameInfo) {
1500  // x.a is an l-value if 'a' has a reference type. Otherwise:
1501  // x.a is an l-value/x-value/pr-value if the base is (and note
1502  //   that *x is always an l-value), except that if the base isn't
1503  //   an ordinary object then we must have an rvalue.
1504  ExprValueKind VK = VK_LValue;
1505  ExprObjectKind OK = OK_Ordinary;
1506  if (!IsArrow) {
1507    if (BaseExpr->getObjectKind() == OK_Ordinary)
1508      VK = BaseExpr->getValueKind();
1509    else
1510      VK = VK_RValue;
1511  }
1512  if (VK != VK_RValue && Field->isBitField())
1513    OK = OK_BitField;
1514
1515  // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1516  QualType MemberType = Field->getType();
1517  if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1518    MemberType = Ref->getPointeeType();
1519    VK = VK_LValue;
1520  } else {
1521    QualType BaseType = BaseExpr->getType();
1522    if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1523
1524    Qualifiers BaseQuals = BaseType.getQualifiers();
1525
1526    // GC attributes are never picked up by members.
1527    BaseQuals.removeObjCGCAttr();
1528
1529    // CVR attributes from the base are picked up by members,
1530    // except that 'mutable' members don't pick up 'const'.
1531    if (Field->isMutable()) BaseQuals.removeConst();
1532
1533    Qualifiers MemberQuals
1534    = S.Context.getCanonicalType(MemberType).getQualifiers();
1535
1536    // TR 18037 does not allow fields to be declared with address spaces.
1537    assert(!MemberQuals.hasAddressSpace());
1538
1539    Qualifiers Combined = BaseQuals + MemberQuals;
1540    if (Combined != MemberQuals)
1541      MemberType = S.Context.getQualifiedType(MemberType, Combined);
1542  }
1543
1544  S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
1545  ExprResult Base =
1546  S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1547                                  FoundDecl, Field);
1548  if (Base.isInvalid())
1549    return ExprError();
1550  return S.Owned(BuildMemberExpr(S.Context, Base.take(), IsArrow, SS,
1551                                 Field, FoundDecl, MemberNameInfo,
1552                                 MemberType, VK, OK));
1553}
1554
1555/// Builds an implicit member access expression.  The current context
1556/// is known to be an instance method, and the given unqualified lookup
1557/// set is known to contain only instance members, at least one of which
1558/// is from an appropriate type.
1559ExprResult
1560Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1561                              LookupResult &R,
1562                              const TemplateArgumentListInfo *TemplateArgs,
1563                              bool IsKnownInstance) {
1564  assert(!R.empty() && !R.isAmbiguous());
1565
1566  SourceLocation loc = R.getNameLoc();
1567
1568  // We may have found a field within an anonymous union or struct
1569  // (C++ [class.union]).
1570  // FIXME: template-ids inside anonymous structs?
1571  if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
1572    return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
1573
1574  // If this is known to be an instance access, go ahead and build an
1575  // implicit 'this' expression now.
1576  // 'this' expression now.
1577  QualType ThisTy = getAndCaptureCurrentThisType();
1578  assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1579
1580  Expr *baseExpr = 0; // null signifies implicit access
1581  if (IsKnownInstance) {
1582    SourceLocation Loc = R.getNameLoc();
1583    if (SS.getRange().isValid())
1584      Loc = SS.getRange().getBegin();
1585    baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1586  }
1587
1588  return BuildMemberReferenceExpr(baseExpr, ThisTy,
1589                                  /*OpLoc*/ SourceLocation(),
1590                                  /*IsArrow*/ true,
1591                                  SS,
1592                                  /*FirstQualifierInScope*/ 0,
1593                                  R, TemplateArgs);
1594}
1595