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