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