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