1 //===--- SemaExprMember.cpp - Semantic Analysis for Expressions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis member access expressions.
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"
26 using namespace clang;
29 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> BaseSet;
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());
38 return BaseIsNotInSet(Record) && Record->forallBases(BaseIsNotInSet);
42 /// The reference is definitely not an instance member access.
45 /// The reference may be an implicit instance member access.
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,
52 /// The reference may be to an instance member, but it is invalid if
53 /// so, because the context is from an unrelated class.
56 /// The reference is definitely an implicit instance member access.
59 /// The reference may be to an unresolved using declaration.
62 /// The reference is a contextually-permitted abstract member reference.
65 /// The reference may be to an unresolved using declaration and the
66 /// context is not an instance method.
67 IMA_Unresolved_StaticContext,
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
72 IMA_Field_Uneval_Context,
74 /// All possible referrents are instance members and the current
75 /// context is not an instance method.
76 IMA_Error_StaticContext,
78 /// All possible referrents are instance members of an unrelated
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());
93 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
95 bool isStaticContext = SemaRef.CXXThisTypeOverride.isNull() &&
96 (!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic());
98 if (R.isUnresolvableResult())
99 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
101 // Collect all the declaring classes of instance members we find.
102 bool hasNonInstance = false;
103 bool isField = false;
105 for (NamedDecl *D : R) {
106 // Look through any using decls.
107 D = D->getUnderlyingDecl();
109 if (D->isCXXInstanceMember()) {
110 isField |= isa<FieldDecl>(D) || isa<MSPropertyDecl>(D) ||
111 isa<IndirectFieldDecl>(D);
113 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
114 Classes.insert(R->getCanonicalDecl());
116 hasNonInstance = true;
119 // If we didn't find any instance members, it can't be an implicit
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:
128 // - if that id-expression denotes a non-static data member and it
129 // appears in an unevaluated operand.
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;
141 case Sema::UnevaluatedAbstract:
142 AbstractInstanceResult = IMA_Abstract;
145 case Sema::DiscardedStatement:
146 case Sema::ConstantEvaluated:
147 case Sema::PotentiallyEvaluated:
148 case Sema::PotentiallyEvaluatedIfUsed:
152 // If the current context is not an instance method, it can't be
153 // an implicit member reference.
154 if (isStaticContext) {
156 return IMA_Mixed_StaticContext;
158 return AbstractInstanceResult ? AbstractInstanceResult
159 : IMA_Error_StaticContext;
162 CXXRecordDecl *contextClass;
163 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
164 contextClass = MD->getParent()->getCanonicalDecl();
166 contextClass = cast<CXXRecordDecl>(DC);
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
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.
181 Classes.insert(R.getNamingClass()->getCanonicalDecl());
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 :
192 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
195 /// Diagnose a reference to a field with no object available.
196 static void diagnoseInstanceReference(Sema &SemaRef,
197 const CXXScopeSpec &SS,
199 const DeclarationNameInfo &nameInfo) {
200 SourceLocation Loc = nameInfo.getLoc();
201 SourceRange Range(Loc);
202 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
204 // Look through using shadow decls and aliases.
205 Rep = Rep->getUnderlyingDecl();
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());
212 bool InStaticMethod = Method && Method->isStatic();
213 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
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
223 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
224 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
226 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
227 << nameInfo.getName() << Range;
229 SemaRef.Diag(Loc, diag::err_member_call_without_object)
233 /// Builds an expression which might be an implicit member expression.
235 Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
236 SourceLocation TemplateKWLoc,
238 const TemplateArgumentListInfo *TemplateArgs,
240 switch (ClassifyImplicitMemberAccess(*this, R)) {
242 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true, S);
245 case IMA_Mixed_Unrelated:
247 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false,
250 case IMA_Field_Uneval_Context:
251 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
252 << R.getLookupNameInfo().getName();
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);
262 case IMA_Error_StaticContext:
263 case IMA_Error_Unrelated:
264 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
265 R.getLookupNameInfo());
269 llvm_unreachable("unexpected instance member access kind");
272 /// Determine whether input char is from rgba component set.
286 /// Check an ext-vector component access expression.
288 /// VK should be set in advance to the value kind of the base
291 CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
292 SourceLocation OpLoc, const IdentifierInfo *CompName,
293 SourceLocation CompLoc) {
294 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
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>();
301 // The vector accessor can't exceed the number of elements.
302 const char *compStr = CompName->getNameStart();
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
307 bool HalvingSwizzle = false;
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];
313 bool HasRepeated = false;
314 bool HasIndex[16] = {};
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);
327 // Ensure that xyzw and rgba components don't intermingle.
328 if (HasRGBA != IsRGBA(*compStr))
330 if (HasIndex[Idx]) HasRepeated = true;
331 HasIndex[Idx] = true;
333 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
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);
345 if (HexSwizzle) compStr++;
346 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
347 if (HasIndex[Idx]) HasRepeated = true;
348 HasIndex[Idx] = true;
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);
361 // Ensure no component accessor exceeds the width of the vector type it
363 if (!HalvingSwizzle) {
364 compStr = CompName->getNameStart();
370 if (!vecType->isAccessorWithinNumElements(*compStr++, HexSwizzle)) {
371 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
372 << baseType << SourceRange(CompLoc);
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();
389 return vecType->getElementType();
391 if (HasRepeated) VK = VK_RValue;
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();
400 if ((*I)->getUnderlyingType() == VT)
401 return S.Context.getTypedefType(*I);
404 return VT; // should never get here (a typedef type should always be found).
407 static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
408 IdentifierInfo *Member,
410 ASTContext &Context) {
412 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(
413 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance))
415 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
418 for (const auto *I : PDecl->protocols()) {
419 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel,
426 static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
427 IdentifierInfo *Member,
429 ASTContext &Context) {
430 // Check protocols on qualified interfaces.
431 Decl *GDecl = nullptr;
432 for (const auto *I : QIdTy->quals()) {
434 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
435 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
439 // Also must look for a getter or setter name which uses property syntax.
440 if (ObjCMethodDecl *OMD = I->getInstanceMethod(Sel)) {
446 for (const auto *I : QIdTy->quals()) {
447 // Search in the protocol-qualifier list of current protocol.
448 GDecl = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel, Context);
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.:
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.
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();
484 assert(BaseType->isDependentType() ||
485 NameInfo.getName().isDependentName() ||
486 isDependentScopeSpecifier(SS));
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);
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,
502 const CXXScopeSpec &SS,
504 const DeclarationNameInfo &nameInfo) {
505 // If this is an implicit member access, use a different set of
508 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
510 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
511 << SS.getRange() << rep << BaseType;
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:
519 // ... In these cases, the id-expression shall name a
520 // member of the class or of one of its base classes.
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,
528 const CXXScopeSpec &SS,
529 const LookupResult &R) {
530 CXXRecordDecl *BaseRecord =
531 cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType));
533 // We can't check this yet because the base type is still
535 assert(BaseType->isDependentType());
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())
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();
553 CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
554 if (BaseRecord->getCanonicalDecl() == MemberRecord ||
555 !BaseRecord->isProvablyNotDerivedFrom(MemberRecord))
559 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
560 R.getRepresentativeDecl(),
561 R.getLookupNameInfo());
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 {
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;
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)))
590 // Accept candidates that occur in the current record.
591 if (Record->containsDecl(ND))
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))
609 const RecordDecl *const Record;
614 static bool LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
616 const RecordType *RTy,
617 SourceLocation OpLoc, bool IsArrow,
618 CXXScopeSpec &SS, bool HasTemplateArgs,
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,
628 if (HasTemplateArgs) {
629 // LookupTemplateName doesn't expect these both to exist simultaneously.
630 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
633 SemaRef.LookupTemplateName(R, nullptr, SS, ObjectType, false, MOUS);
637 DeclContext *DC = RDecl;
639 // If the member name was a qualified-id, look into the
640 // nested-name-specifier.
641 DC = SemaRef.computeDeclContext(SS, false);
643 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
644 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
645 << SS.getRange() << DC;
649 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
651 if (!isa<TypeDecl>(DC)) {
652 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
653 << DC << SS.getRange();
658 // The record definition is complete, now look up the member.
659 SemaRef.LookupQualifiedName(R, DC, SS);
664 DeclarationName Typo = R.getLookupName();
665 SourceLocation TypoLoc = R.getNameLoc();
669 DeclarationNameInfo NameInfo;
670 Sema::LookupNameKind LookupKind;
671 Sema::RedeclarationKind Redecl;
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) {
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
690 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << DC << BaseRange;
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)
701 return SemaRef.BuildMemberReferenceExpr(
702 BaseExpr, BaseExpr->getType(), OpLoc, IsArrow, SS, SourceLocation(),
703 nullptr, R, nullptr, nullptr);
705 Sema::CTK_ErrorRecovery, DC);
710 static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
711 ExprResult &BaseExpr, bool &IsArrow,
712 SourceLocation OpLoc, CXXScopeSpec &SS,
713 Decl *ObjCImpDecl, bool HasTemplateArgs);
716 Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
717 SourceLocation OpLoc, bool IsArrow,
719 SourceLocation TemplateKWLoc,
720 NamedDecl *FirstQualifierInScope,
721 const DeclarationNameInfo &NameInfo,
722 const TemplateArgumentListInfo *TemplateArgs,
724 ActOnMemberAccessExtraArgs *ExtraArgs) {
725 if (BaseType->isDependentType() ||
726 (SS.isSet() && isDependentScopeSpecifier(SS)))
727 return ActOnDependentMemberExpr(Base, BaseType,
729 SS, TemplateKWLoc, FirstQualifierInScope,
730 NameInfo, TemplateArgs);
732 LookupResult R(*this, NameInfo, LookupMemberName);
734 // Implicit member accesses.
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))
746 // Explicit member accesses.
748 ExprResult BaseResult = Base;
749 ExprResult Result = LookupMemberExpr(
750 *this, R, BaseResult, IsArrow, OpLoc, SS,
751 ExtraArgs ? ExtraArgs->ObjCImpDecl : nullptr,
752 TemplateArgs != nullptr);
754 if (BaseResult.isInvalid())
756 Base = BaseResult.get();
758 if (Result.isInvalid())
764 // LookupMemberExpr can modify Base, and thus change BaseType
765 BaseType = Base->getType();
768 return BuildMemberReferenceExpr(Base, BaseType,
769 OpLoc, IsArrow, SS, TemplateKWLoc,
770 FirstQualifierInScope, R, TemplateArgs, S,
775 Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
777 IndirectFieldDecl *indirectField,
778 DeclAccessPair foundDecl,
779 Expr *baseObjectExpr,
780 SourceLocation opLoc) {
781 // First, build the expression that refers to the base object.
783 bool baseObjectIsPointer = false;
784 Qualifiers baseQuals;
786 // Case 1: the base of the indirect field is not a field.
787 VarDecl *baseVariable = indirectField->getVarDecl();
788 CXXScopeSpec EmptySS;
790 assert(baseVariable->getType()->isRecordType());
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?");
799 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
802 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
803 if (result.isInvalid()) return ExprError();
805 baseObjectExpr = result.get();
806 baseObjectIsPointer = false;
807 baseQuals = baseObjectExpr->getType().getQualifiers();
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();
817 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
818 baseObjectIsPointer = true;
819 objectType = ptr->getPointeeType();
821 baseObjectIsPointer = false;
823 baseQuals = objectType.getQualifiers();
825 // Case 3: the base of the indirect field is a field and we should
826 // build an implicit member access.
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();
838 // Our base object expression is "this".
839 CheckCXXThisCapture(loc);
841 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
842 baseObjectIsPointer = true;
843 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
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();
852 // Build the first member access in the chain with full information.
854 FieldDecl *field = cast<FieldDecl>(*FI);
856 // Make a nameInfo that properly uses the anonymous name.
857 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
859 result = BuildFieldReferenceExpr(result, baseObjectIsPointer,
860 SourceLocation(), EmptySS, field,
861 foundDecl, memberNameInfo).get();
865 // FIXME: check qualified member access
868 // In all cases, we should now skip the first declaration in the chain.
872 FieldDecl *field = cast<FieldDecl>(*FI++);
874 // FIXME: these are somewhat meaningless
875 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
876 DeclAccessPair fakeFoundDecl =
877 DeclAccessPair::make(field, field->getAccess());
880 BuildFieldReferenceExpr(result, /*isarrow*/ false, SourceLocation(),
881 (FI == FEnd ? SS : EmptySS), field,
882 fakeFoundDecl, memberNameInfo)
890 BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
891 const CXXScopeSpec &SS,
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),
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);
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;
930 getVarTemplateSpecialization(Sema &S, VarTemplateDecl *VarTempl,
931 const TemplateArgumentListInfo *TemplateArgs,
932 const DeclarationNameInfo &MemberNameInfo,
933 SourceLocation TemplateKWLoc) {
936 S.Diag(MemberNameInfo.getBeginLoc(), diag::err_template_decl_ref)
937 << /*Variable template*/ 1 << MemberNameInfo.getName()
938 << MemberNameInfo.getSourceRange();
940 S.Diag(VarTempl->getLocation(), diag::note_template_decl_here);
944 DeclResult VDecl = S.CheckVarTemplateId(
945 VarTempl, TemplateKWLoc, MemberNameInfo.getLoc(), *TemplateArgs);
946 if (VDecl.isInvalid())
948 VarDecl *Var = cast<VarDecl>(VDecl.get());
949 if (!Var->getTemplateSpecializationKind())
950 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
951 MemberNameInfo.getLoc());
956 Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
957 SourceLocation OpLoc, bool IsArrow,
958 const CXXScopeSpec &SS,
959 SourceLocation TemplateKWLoc,
960 NamedDecl *FirstQualifierInScope,
962 const TemplateArgumentListInfo *TemplateArgs,
964 bool SuppressQualifierCheck,
965 ActOnMemberAccessExtraArgs *ExtraArgs) {
966 QualType BaseType = BaseExprType;
968 assert(BaseType->isPointerType());
969 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
971 R.setBaseObjectType(BaseType);
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())
979 BaseExpr = Converted.get();
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:
990 // static void f(double) { }
993 // auto L = [=](auto a) {
994 // return [](int i) {
995 // return [=](auto b) {
997 // //f(decltype(a){});
1003 // N(5.32); // OK, must not error.
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);
1029 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
1030 DeclarationName MemberName = MemberNameInfo.getName();
1031 SourceLocation MemberLoc = MemberNameInfo.getLoc();
1033 if (R.isAmbiguous())
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);
1048 // Rederive where we looked up.
1049 DeclContext *DC = (SS.isSet()
1050 ? computeDeclContext(SS, false)
1051 : BaseType->getAs<RecordType>()->getDecl());
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);
1068 if (Trap.hasErrorOccurred())
1069 RetryExpr = ExprError();
1071 if (RetryExpr.isUsable()) {
1072 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
1073 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
1078 Diag(R.getNameLoc(), diag::err_no_member)
1080 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
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))
1098 // Construct an unresolved result if we in fact got an unresolved
1100 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
1101 // Suppress any lookup-related diagnostics; we'll do these when we
1103 R.suppressDiagnostics();
1105 UnresolvedMemberExpr *MemExpr
1106 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
1107 BaseExpr, BaseExprType,
1109 SS.getWithLocInContext(Context),
1110 TemplateKWLoc, MemberNameInfo,
1111 TemplateArgs, R.begin(), R.end());
1116 assert(R.isSingleResult());
1117 DeclAccessPair FoundDecl = R.begin().getPair();
1118 NamedDecl *MemberDecl = R.getFoundDecl();
1120 // FIXME: diagnose the presence of template arguments now.
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
1125 if (MemberDecl->isInvalidDecl())
1128 // Handle the implicit-member-access case.
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);
1145 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl,
1146 FoundDecl, TemplateArgs);
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);
1155 // Check the use of this member.
1156 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1159 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
1160 return BuildFieldReferenceExpr(BaseExpr, IsArrow, OpLoc, SS, FD, FoundDecl,
1163 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
1164 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
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,
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,
1181 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1182 ExprValueKind valueKind;
1184 if (MemberFn->isInstance()) {
1185 valueKind = VK_RValue;
1186 type = Context.BoundMemberTy;
1188 valueKind = VK_LValue;
1189 type = MemberFn->getType();
1192 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1193 TemplateKWLoc, MemberFn, FoundDecl, MemberNameInfo,
1194 type, valueKind, OK_Ordinary);
1196 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
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);
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,
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);
1218 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1219 << MemberName << BaseType << int(IsArrow);
1221 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
1223 R.suppressDiagnostics();
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;
1238 const ObjCObjectType *ty = opty->getObjectType();
1241 if (ty->isObjCId()) {
1242 redef = S.Context.getObjCIdRedefinitionType();
1243 } else if (ty->isObjCClass()) {
1244 redef = S.Context.getObjCClassRedefinitionType();
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())
1255 base = S.ImpCastExprToType(base.get(), redef, CK_BitCast);
1259 static bool isRecordType(QualType T) {
1260 return T->isRecordType();
1262 static bool isPointerToRecordType(QualType T) {
1263 if (const PointerType *PT = T->getAs<PointerType>())
1264 return PT->getPointeeType()->isRecordType();
1268 /// Perform conversions on the LHS of a member access expression.
1270 Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
1271 if (IsArrow && !Base->getType()->isFunctionType())
1272 return DefaultFunctionArrayLvalueConversion(Base);
1274 return CheckPlaceholderExpr(Base);
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.
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");
1293 // Perform default conversions.
1294 BaseExpr = S.PerformMemberExprBaseConversion(BaseExpr.get(), IsArrow);
1295 if (BaseExpr.isInvalid())
1298 QualType BaseType = BaseExpr.get()->getType();
1299 assert(!BaseType->isDependentType());
1301 DeclarationName MemberName = R.getLookupName();
1302 SourceLocation MemberLoc = R.getNameLoc();
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.
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;
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, ".");
1328 } else if (BaseType->isFunctionType()) {
1331 S.Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1332 << BaseType << BaseExpr.get()->getSourceRange();
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))
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);
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());
1360 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1362 // There are three cases for the base type:
1363 // - builtin id (qualified or unqualified)
1364 // - builtin Class (qualified or unqualified)
1366 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1368 if (S.getLangOpts().ObjCAutoRefCount &&
1369 (OTy->isObjCId() || OTy->isObjCClass()))
1371 // There's an implicit 'isa' ivar on all objects.
1372 // But we only actually find it this way on objects of type 'id',
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);
1383 if (S.RequireCompleteType(OpLoc, BaseType,
1384 diag::err_typecheck_incomplete_tag,
1388 ObjCInterfaceDecl *ClassDeclared = nullptr;
1389 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
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>();
1401 S.PDiag(diag::err_typecheck_member_reference_ivar_suggest)
1402 << IDecl->getDeclName() << MemberName);
1404 // Figure out the class that declares the ivar.
1405 assert(!ClassDeclared);
1407 Decl *D = cast<Decl>(IV->getDeclContext());
1408 if (auto *Category = dyn_cast<ObjCCategoryDecl>(D))
1409 D = Category->getClassInterface();
1411 if (auto *Implementation = dyn_cast<ObjCImplementationDecl>(D))
1412 ClassDeclared = Implementation->getClassInterface();
1413 else if (auto *Interface = dyn_cast<ObjCInterfaceDecl>(D))
1414 ClassDeclared = Interface;
1416 assert(ClassDeclared && "cannot query interface");
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, ".");
1427 S.Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1428 << IDecl->getDeclName() << MemberName
1429 << BaseExpr.get()->getSourceRange();
1434 assert(ClassDeclared);
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
1439 if (IV->isInvalidDecl())
1442 // Check whether we can reference this field.
1443 if (S.DiagnoseUseOfDecl(IV, MemberLoc))
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();
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))
1472 S.Diag(MemberLoc, diag::err_protected_ivar_access)
1473 << IV->getDeclName();
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();
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);
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));
1497 S.Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
1500 ObjCIvarRefExpr *Result = new (S.Context) ObjCIvarRefExpr(
1501 IV, IV->getUsageType(BaseType), MemberLoc, OpLoc, BaseExpr.get(),
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);
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());
1523 // This actually uses the base as an r-value.
1524 BaseExpr = S.DefaultLvalueConversion(BaseExpr.get());
1525 if (BaseExpr.isInvalid())
1528 assert(S.Context.hasSameUnqualifiedType(BaseType,
1529 BaseExpr.get()->getType()));
1531 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1533 const ObjCObjectType *OT = OPT->getObjectType();
1535 // id, with and without qualifiers.
1536 if (OT->isObjCId()) {
1537 // Check protocols on qualified interfaces.
1538 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
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))
1546 return new (S.Context)
1547 ObjCPropertyRefExpr(PD, S.Context.PseudoObjectTy, VK_LValue,
1548 OK_ObjCProperty, MemberLoc, BaseExpr.get());
1551 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1552 // Check the use of this method.
1553 if (S.DiagnoseUseOfDecl(OMD, MemberLoc))
1555 Selector SetterSel =
1556 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1557 S.PP.getSelectorTable(),
1559 ObjCMethodDecl *SMD = nullptr;
1560 if (Decl *SDecl = FindGetterSetterNameDecl(OPT,
1561 /*Property id*/ nullptr,
1562 SetterSel, S.Context))
1563 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
1565 return new (S.Context)
1566 ObjCPropertyRefExpr(OMD, SMD, S.Context.PseudoObjectTy, VK_LValue,
1567 OK_ObjCProperty, MemberLoc, BaseExpr.get());
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);
1576 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
1577 << MemberName << BaseType);
1580 // 'Class', unqualified only.
1581 if (OT->isObjCClass()) {
1582 // Only works in a method declaration (??!).
1583 ObjCMethodDecl *MD = S.getCurMethodDecl();
1585 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1586 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1587 ObjCImpDecl, HasTemplateArgs);
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))
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(),
1608 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1610 // If this reference is in an @implementation, also check for 'private'
1612 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1615 if (Setter && S.DiagnoseUseOfDecl(Setter, MemberLoc))
1618 if (Getter || Setter) {
1619 return new (S.Context) ObjCPropertyRefExpr(
1620 Getter, Setter, S.Context.PseudoObjectTy, VK_LValue,
1621 OK_ObjCProperty, MemberLoc, BaseExpr.get());
1624 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1625 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1626 ObjCImpDecl, HasTemplateArgs);
1628 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
1629 << MemberName << BaseType);
1632 // Normal property access.
1633 return S.HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc, MemberName,
1634 MemberLoc, SourceLocation(), QualType(),
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();
1646 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(BaseExpr.get()))
1647 VK = POE->getSyntacticForm()->getValueKind();
1649 VK = BaseExpr.get()->getValueKind();
1651 QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
1656 return new (S.Context)
1657 ExtVectorElementExpr(ret, VK, BaseExpr.get(), *Member, MemberLoc);
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);
1673 // Recover from dot accesses to pointers, e.g.:
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, "->");
1687 // Recurse as an -> access.
1689 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1690 ObjCImpDecl, HasTemplateArgs);
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),
1699 IsArrow ? &isPointerToRecordType : &isRecordType)) {
1700 if (BaseExpr.isInvalid())
1702 BaseExpr = S.DefaultFunctionArrayConversion(BaseExpr.get());
1703 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1704 ObjCImpDecl, HasTemplateArgs);
1707 S.Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
1708 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
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.
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,
1727 SourceLocation TemplateKWLoc,
1729 Decl *ObjCImpDecl) {
1730 if (SS.isSet() && SS.isInvalid())
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);
1739 TemplateArgumentListInfo TemplateArgsBuffer;
1741 // Decompose the name into its component parts.
1742 DeclarationNameInfo NameInfo;
1743 const TemplateArgumentListInfo *TemplateArgs;
1744 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1745 NameInfo, TemplateArgs);
1747 DeclarationName Name = NameInfo.getName();
1748 bool IsArrow = (OpKind == tok::arrow);
1750 NamedDecl *FirstQualifierInScope
1751 = (!SS.isSet() ? nullptr : FindFirstQualifierInScope(S, SS.getScopeRep()));
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();
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);
1765 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl};
1766 return BuildMemberReferenceExpr(Base, Base->getType(), OpLoc, IsArrow, SS,
1767 TemplateKWLoc, FirstQualifierInScope,
1768 NameInfo, TemplateArgs, S, &ExtraArgs);
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;
1783 if (BaseExpr->getObjectKind() == OK_Ordinary)
1784 VK = BaseExpr->getValueKind();
1788 if (VK != VK_RValue && Field->isBitField())
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();
1797 QualType BaseType = BaseExpr->getType();
1798 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1800 Qualifiers BaseQuals = BaseType.getQualifiers();
1802 // GC attributes are never picked up by members.
1803 BaseQuals.removeObjCGCAttr();
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();
1809 Qualifiers MemberQuals =
1810 Context.getCanonicalType(MemberType).getQualifiers();
1812 assert(!MemberQuals.hasAddressSpace());
1814 Qualifiers Combined = BaseQuals + MemberQuals;
1815 if (Combined != MemberQuals)
1816 MemberType = Context.getQualifiedType(MemberType, Combined);
1819 UnusedPrivateFields.remove(Field);
1821 ExprResult Base = PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1823 if (Base.isInvalid())
1826 BuildMemberExpr(*this, Context, Base.get(), IsArrow, OpLoc, SS,
1827 /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl,
1828 MemberNameInfo, MemberType, VK, OK);
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);
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.
1846 Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1847 SourceLocation TemplateKWLoc,
1849 const TemplateArgumentListInfo *TemplateArgs,
1850 bool IsKnownInstance, const Scope *S) {
1851 assert(!R.empty() && !R.isAmbiguous());
1853 SourceLocation loc = R.getNameLoc();
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'");
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);
1870 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1871 /*OpLoc*/ SourceLocation(),
1874 /*FirstQualifierInScope*/ nullptr,
1875 R, TemplateArgs, S);