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