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