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