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