[DFAJumpThreading] Remove incoming StartBlock from all phis when unfolding select...
[llvm-project.git] / clang / lib / Sema / SemaExprMember.cpp
blobbd85b548c0dd602e79317e06aab23a48af8958a0
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.
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"
25 using namespace clang;
26 using namespace sema;
28 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> BaseSet;
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());
37 return BaseIsNotInSet(Record) && Record->forallBases(BaseIsNotInSet);
40 enum IMAKind {
41 /// The reference is definitely not an instance member access.
42 IMA_Static,
44 /// The reference may be an implicit instance member access.
45 IMA_Mixed,
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,
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,
55 /// The reference is definitely an implicit instance member access.
56 IMA_Instance,
58 /// The reference may be to an unresolved using declaration.
59 IMA_Unresolved,
61 /// The reference is a contextually-permitted abstract member reference.
62 IMA_Abstract,
64 /// The reference may be to an unresolved using declaration and the
65 /// context is not an instance method.
66 IMA_Unresolved_StaticOrExplicitContext,
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,
73 /// All possible referrents are instance members and the current
74 /// context is not an instance method.
75 IMA_Error_StaticOrExplicitContext,
77 /// All possible referrents are instance members of an unrelated
78 /// class.
79 IMA_Error_Unrelated
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());
92 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
94 bool isStaticOrExplicitContext =
95 SemaRef.CXXThisTypeOverride.isNull() &&
96 (!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic() ||
97 cast<CXXMethodDecl>(DC)->isExplicitObjectMemberFunction());
99 if (R.isUnresolvableResult())
100 return isStaticOrExplicitContext ? IMA_Unresolved_StaticOrExplicitContext
101 : IMA_Unresolved;
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();
111 if (D->isCXXInstanceMember()) {
112 isField |= isa<FieldDecl>(D) || isa<MSPropertyDecl>(D) ||
113 isa<IndirectFieldDecl>(D);
115 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
116 Classes.insert(R->getCanonicalDecl());
117 } else
118 hasNonInstance = true;
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;
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.
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;
144 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
145 AbstractInstanceResult = IMA_Abstract;
146 break;
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;
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;
162 return AbstractInstanceResult ? AbstractInstanceResult
163 : IMA_Error_StaticOrExplicitContext;
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;
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());
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;
199 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
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());
211 // Look through using shadow decls and aliases.
212 Rep = Rep->getUnderlyingDecl();
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());
219 bool InStaticMethod = Method && Method->isStatic();
220 bool InExplicitObjectMethod =
221 Method && Method->isExplicitObjectMemberFunction();
222 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
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(".");
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 const auto *Callee = dyn_cast<CXXMethodDecl>(Rep);
257 auto Diag = SemaRef.Diag(Loc, diag::err_member_call_without_object)
258 << Range << Callee->isExplicitObjectMemberFunction();
259 if (!Replacement.empty())
260 Diag << FixItHint::CreateInsertion(Loc, Replacement);
264 /// Builds an expression which might be an implicit member expression.
265 ExprResult Sema::BuildPossibleImplicitMemberExpr(
266 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
267 const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
268 UnresolvedLookupExpr *AsULE) {
269 switch (ClassifyImplicitMemberAccess(*this, R)) {
270 case IMA_Instance:
271 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true, S);
273 case IMA_Mixed:
274 case IMA_Mixed_Unrelated:
275 case IMA_Unresolved:
276 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false,
279 case IMA_Field_Uneval_Context:
280 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
281 << R.getLookupNameInfo().getName();
282 [[fallthrough]];
283 case IMA_Static:
284 case IMA_Abstract:
285 case IMA_Mixed_StaticOrExplicitContext:
286 case IMA_Unresolved_StaticOrExplicitContext:
287 if (TemplateArgs || TemplateKWLoc.isValid())
288 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
289 return AsULE ? AsULE : BuildDeclarationNameExpr(SS, R, false);
291 case IMA_Error_StaticOrExplicitContext:
292 case IMA_Error_Unrelated:
293 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
294 R.getLookupNameInfo());
295 return ExprError();
298 llvm_unreachable("unexpected instance member access kind");
301 /// Determine whether input char is from rgba component set.
302 static bool
303 IsRGBA(char c) {
304 switch (c) {
305 case 'r':
306 case 'g':
307 case 'b':
308 case 'a':
309 return true;
310 default:
311 return false;
315 // OpenCL v1.1, s6.1.7
316 // The component swizzle length must be in accordance with the acceptable
317 // vector sizes.
318 static bool IsValidOpenCLComponentSwizzleLength(unsigned len)
320 return (len >= 1 && len <= 4) || len == 8 || len == 16;
323 /// Check an ext-vector component access expression.
325 /// VK should be set in advance to the value kind of the base
326 /// expression.
327 static QualType
328 CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
329 SourceLocation OpLoc, const IdentifierInfo *CompName,
330 SourceLocation CompLoc) {
331 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
332 // see FIXME there.
334 // FIXME: This logic can be greatly simplified by splitting it along
335 // halving/not halving and reworking the component checking.
336 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
338 // The vector accessor can't exceed the number of elements.
339 const char *compStr = CompName->getNameStart();
341 // This flag determines whether or not the component is one of the four
342 // special names that indicate a subset of exactly half the elements are
343 // to be selected.
344 bool HalvingSwizzle = false;
346 // This flag determines whether or not CompName has an 's' char prefix,
347 // indicating that it is a string of hex values to be used as vector indices.
348 bool HexSwizzle = (*compStr == 's' || *compStr == 'S') && compStr[1];
350 bool HasRepeated = false;
351 bool HasIndex[16] = {};
353 int Idx;
355 // Check that we've found one of the special components, or that the component
356 // names must come from the same set.
357 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
358 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
359 HalvingSwizzle = true;
360 } else if (!HexSwizzle &&
361 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
362 bool HasRGBA = IsRGBA(*compStr);
363 do {
364 // Ensure that xyzw and rgba components don't intermingle.
365 if (HasRGBA != IsRGBA(*compStr))
366 break;
367 if (HasIndex[Idx]) HasRepeated = true;
368 HasIndex[Idx] = true;
369 compStr++;
370 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
372 // Emit a warning if an rgba selector is used earlier than OpenCL C 3.0.
373 if (HasRGBA || (*compStr && IsRGBA(*compStr))) {
374 if (S.getLangOpts().OpenCL &&
375 S.getLangOpts().getOpenCLCompatibleVersion() < 300) {
376 const char *DiagBegin = HasRGBA ? CompName->getNameStart() : compStr;
377 S.Diag(OpLoc, diag::ext_opencl_ext_vector_type_rgba_selector)
378 << StringRef(DiagBegin, 1) << SourceRange(CompLoc);
381 } else {
382 if (HexSwizzle) compStr++;
383 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
384 if (HasIndex[Idx]) HasRepeated = true;
385 HasIndex[Idx] = true;
386 compStr++;
390 if (!HalvingSwizzle && *compStr) {
391 // We didn't get to the end of the string. This means the component names
392 // didn't come from the same set *or* we encountered an illegal name.
393 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
394 << StringRef(compStr, 1) << SourceRange(CompLoc);
395 return QualType();
398 // Ensure no component accessor exceeds the width of the vector type it
399 // operates on.
400 if (!HalvingSwizzle) {
401 compStr = CompName->getNameStart();
403 if (HexSwizzle)
404 compStr++;
406 while (*compStr) {
407 if (!vecType->isAccessorWithinNumElements(*compStr++, HexSwizzle)) {
408 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
409 << baseType << SourceRange(CompLoc);
410 return QualType();
415 // OpenCL mode requires swizzle length to be in accordance with accepted
416 // sizes. Clang however supports arbitrary lengths for other languages.
417 if (S.getLangOpts().OpenCL && !HalvingSwizzle) {
418 unsigned SwizzleLength = CompName->getLength();
420 if (HexSwizzle)
421 SwizzleLength--;
423 if (IsValidOpenCLComponentSwizzleLength(SwizzleLength) == false) {
424 S.Diag(OpLoc, diag::err_opencl_ext_vector_component_invalid_length)
425 << SwizzleLength << SourceRange(CompLoc);
426 return QualType();
430 // The component accessor looks fine - now we need to compute the actual type.
431 // The vector type is implied by the component accessor. For example,
432 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
433 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
434 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
435 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
436 : CompName->getLength();
437 if (HexSwizzle)
438 CompSize--;
440 if (CompSize == 1)
441 return vecType->getElementType();
443 if (HasRepeated)
444 VK = VK_PRValue;
446 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
447 // Now look up the TypeDefDecl from the vector type. Without this,
448 // diagostics look bad. We want extended vector types to appear built-in.
449 for (Sema::ExtVectorDeclsType::iterator
450 I = S.ExtVectorDecls.begin(S.getExternalSource()),
451 E = S.ExtVectorDecls.end();
452 I != E; ++I) {
453 if ((*I)->getUnderlyingType() == VT)
454 return S.Context.getTypedefType(*I);
457 return VT; // should never get here (a typedef type should always be found).
460 static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
461 IdentifierInfo *Member,
462 const Selector &Sel,
463 ASTContext &Context) {
464 if (Member)
465 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(
466 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance))
467 return PD;
468 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
469 return OMD;
471 for (const auto *I : PDecl->protocols()) {
472 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel,
473 Context))
474 return D;
476 return nullptr;
479 static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
480 IdentifierInfo *Member,
481 const Selector &Sel,
482 ASTContext &Context) {
483 // Check protocols on qualified interfaces.
484 Decl *GDecl = nullptr;
485 for (const auto *I : QIdTy->quals()) {
486 if (Member)
487 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
488 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
489 GDecl = PD;
490 break;
492 // Also must look for a getter or setter name which uses property syntax.
493 if (ObjCMethodDecl *OMD = I->getInstanceMethod(Sel)) {
494 GDecl = OMD;
495 break;
498 if (!GDecl) {
499 for (const auto *I : QIdTy->quals()) {
500 // Search in the protocol-qualifier list of current protocol.
501 GDecl = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel, Context);
502 if (GDecl)
503 return GDecl;
506 return GDecl;
509 ExprResult
510 Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
511 bool IsArrow, SourceLocation OpLoc,
512 const CXXScopeSpec &SS,
513 SourceLocation TemplateKWLoc,
514 NamedDecl *FirstQualifierInScope,
515 const DeclarationNameInfo &NameInfo,
516 const TemplateArgumentListInfo *TemplateArgs) {
517 // Even in dependent contexts, try to diagnose base expressions with
518 // obviously wrong types, e.g.:
520 // T* t;
521 // t.f;
523 // In Obj-C++, however, the above expression is valid, since it could be
524 // accessing the 'f' property if T is an Obj-C interface. The extra check
525 // allows this, while still reporting an error if T is a struct pointer.
526 if (!IsArrow) {
527 const PointerType *PT = BaseType->getAs<PointerType>();
528 if (PT && (!getLangOpts().ObjC ||
529 PT->getPointeeType()->isRecordType())) {
530 assert(BaseExpr && "cannot happen with implicit member accesses");
531 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
532 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
533 return ExprError();
537 assert(BaseType->isDependentType() || NameInfo.getName().isDependentName() ||
538 isDependentScopeSpecifier(SS) ||
539 (TemplateArgs && llvm::any_of(TemplateArgs->arguments(),
540 [](const TemplateArgumentLoc &Arg) {
541 return Arg.getArgument().isDependent();
542 })));
544 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
545 // must have pointer type, and the accessed type is the pointee.
546 return CXXDependentScopeMemberExpr::Create(
547 Context, BaseExpr, BaseType, IsArrow, OpLoc,
548 SS.getWithLocInContext(Context), TemplateKWLoc, FirstQualifierInScope,
549 NameInfo, TemplateArgs);
552 /// We know that the given qualified member reference points only to
553 /// declarations which do not belong to the static type of the base
554 /// expression. Diagnose the problem.
555 static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
556 Expr *BaseExpr,
557 QualType BaseType,
558 const CXXScopeSpec &SS,
559 NamedDecl *rep,
560 const DeclarationNameInfo &nameInfo) {
561 // If this is an implicit member access, use a different set of
562 // diagnostics.
563 if (!BaseExpr)
564 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
566 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
567 << SS.getRange() << rep << BaseType;
570 // Check whether the declarations we found through a nested-name
571 // specifier in a member expression are actually members of the base
572 // type. The restriction here is:
574 // C++ [expr.ref]p2:
575 // ... In these cases, the id-expression shall name a
576 // member of the class or of one of its base classes.
578 // So it's perfectly legitimate for the nested-name specifier to name
579 // an unrelated class, and for us to find an overload set including
580 // decls from classes which are not superclasses, as long as the decl
581 // we actually pick through overload resolution is from a superclass.
582 bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
583 QualType BaseType,
584 const CXXScopeSpec &SS,
585 const LookupResult &R) {
586 CXXRecordDecl *BaseRecord =
587 cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType));
588 if (!BaseRecord) {
589 // We can't check this yet because the base type is still
590 // dependent.
591 assert(BaseType->isDependentType());
592 return false;
595 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
596 // If this is an implicit member reference and we find a
597 // non-instance member, it's not an error.
598 if (!BaseExpr && !(*I)->isCXXInstanceMember())
599 return false;
601 // Note that we use the DC of the decl, not the underlying decl.
602 DeclContext *DC = (*I)->getDeclContext()->getNonTransparentContext();
603 if (!DC->isRecord())
604 continue;
606 CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
607 if (BaseRecord->getCanonicalDecl() == MemberRecord ||
608 !BaseRecord->isProvablyNotDerivedFrom(MemberRecord))
609 return false;
612 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
613 R.getRepresentativeDecl(),
614 R.getLookupNameInfo());
615 return true;
618 namespace {
620 // Callback to only accept typo corrections that are either a ValueDecl or a
621 // FunctionTemplateDecl and are declared in the current record or, for a C++
622 // classes, one of its base classes.
623 class RecordMemberExprValidatorCCC final : public CorrectionCandidateCallback {
624 public:
625 explicit RecordMemberExprValidatorCCC(const RecordType *RTy)
626 : Record(RTy->getDecl()) {
627 // Don't add bare keywords to the consumer since they will always fail
628 // validation by virtue of not being associated with any decls.
629 WantTypeSpecifiers = false;
630 WantExpressionKeywords = false;
631 WantCXXNamedCasts = false;
632 WantFunctionLikeCasts = false;
633 WantRemainingKeywords = false;
636 bool ValidateCandidate(const TypoCorrection &candidate) override {
637 NamedDecl *ND = candidate.getCorrectionDecl();
638 // Don't accept candidates that cannot be member functions, constants,
639 // variables, or templates.
640 if (!ND || !(isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)))
641 return false;
643 // Accept candidates that occur in the current record.
644 if (Record->containsDecl(ND))
645 return true;
647 if (const auto *RD = dyn_cast<CXXRecordDecl>(Record)) {
648 // Accept candidates that occur in any of the current class' base classes.
649 for (const auto &BS : RD->bases()) {
650 if (const auto *BSTy = BS.getType()->getAs<RecordType>()) {
651 if (BSTy->getDecl()->containsDecl(ND))
652 return true;
657 return false;
660 std::unique_ptr<CorrectionCandidateCallback> clone() override {
661 return std::make_unique<RecordMemberExprValidatorCCC>(*this);
664 private:
665 const RecordDecl *const Record;
670 static bool LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
671 Expr *BaseExpr,
672 const RecordType *RTy,
673 SourceLocation OpLoc, bool IsArrow,
674 CXXScopeSpec &SS, bool HasTemplateArgs,
675 SourceLocation TemplateKWLoc,
676 TypoExpr *&TE) {
677 SourceRange BaseRange = BaseExpr ? BaseExpr->getSourceRange() : SourceRange();
678 RecordDecl *RDecl = RTy->getDecl();
679 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
680 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
681 diag::err_typecheck_incomplete_tag,
682 BaseRange))
683 return true;
685 if (HasTemplateArgs || TemplateKWLoc.isValid()) {
686 // LookupTemplateName doesn't expect these both to exist simultaneously.
687 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
689 bool MOUS;
690 return SemaRef.LookupTemplateName(R, nullptr, SS, ObjectType, false, MOUS,
691 TemplateKWLoc);
694 DeclContext *DC = RDecl;
695 if (SS.isSet()) {
696 // If the member name was a qualified-id, look into the
697 // nested-name-specifier.
698 DC = SemaRef.computeDeclContext(SS, false);
700 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
701 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
702 << SS.getRange() << DC;
703 return true;
706 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
708 if (!isa<TypeDecl>(DC)) {
709 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
710 << DC << SS.getRange();
711 return true;
715 // The record definition is complete, now look up the member.
716 SemaRef.LookupQualifiedName(R, DC, SS);
718 if (!R.empty())
719 return false;
721 DeclarationName Typo = R.getLookupName();
722 SourceLocation TypoLoc = R.getNameLoc();
724 struct QueryState {
725 Sema &SemaRef;
726 DeclarationNameInfo NameInfo;
727 Sema::LookupNameKind LookupKind;
728 Sema::RedeclarationKind Redecl;
730 QueryState Q = {R.getSema(), R.getLookupNameInfo(), R.getLookupKind(),
731 R.redeclarationKind()};
732 RecordMemberExprValidatorCCC CCC(RTy);
733 TE = SemaRef.CorrectTypoDelayed(
734 R.getLookupNameInfo(), R.getLookupKind(), nullptr, &SS, CCC,
735 [=, &SemaRef](const TypoCorrection &TC) {
736 if (TC) {
737 assert(!TC.isKeyword() &&
738 "Got a keyword as a correction for a member!");
739 bool DroppedSpecifier =
740 TC.WillReplaceSpecifier() &&
741 Typo.getAsString() == TC.getAsString(SemaRef.getLangOpts());
742 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
743 << Typo << DC << DroppedSpecifier
744 << SS.getRange());
745 } else {
746 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << DC << BaseRange;
749 [=](Sema &SemaRef, TypoExpr *TE, TypoCorrection TC) mutable {
750 LookupResult R(Q.SemaRef, Q.NameInfo, Q.LookupKind, Q.Redecl);
751 R.clear(); // Ensure there's no decls lingering in the shared state.
752 R.suppressDiagnostics();
753 R.setLookupName(TC.getCorrection());
754 for (NamedDecl *ND : TC)
755 R.addDecl(ND);
756 R.resolveKind();
757 return SemaRef.BuildMemberReferenceExpr(
758 BaseExpr, BaseExpr->getType(), OpLoc, IsArrow, SS, SourceLocation(),
759 nullptr, R, nullptr, nullptr);
761 Sema::CTK_ErrorRecovery, DC);
763 return false;
766 static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
767 ExprResult &BaseExpr, bool &IsArrow,
768 SourceLocation OpLoc, CXXScopeSpec &SS,
769 Decl *ObjCImpDecl, bool HasTemplateArgs,
770 SourceLocation TemplateKWLoc);
772 ExprResult
773 Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
774 SourceLocation OpLoc, bool IsArrow,
775 CXXScopeSpec &SS,
776 SourceLocation TemplateKWLoc,
777 NamedDecl *FirstQualifierInScope,
778 const DeclarationNameInfo &NameInfo,
779 const TemplateArgumentListInfo *TemplateArgs,
780 const Scope *S,
781 ActOnMemberAccessExtraArgs *ExtraArgs) {
782 if (BaseType->isDependentType() ||
783 (SS.isSet() && isDependentScopeSpecifier(SS)))
784 return ActOnDependentMemberExpr(Base, BaseType,
785 IsArrow, OpLoc,
786 SS, TemplateKWLoc, FirstQualifierInScope,
787 NameInfo, TemplateArgs);
789 LookupResult R(*this, NameInfo, LookupMemberName);
791 // Implicit member accesses.
792 if (!Base) {
793 TypoExpr *TE = nullptr;
794 QualType RecordTy = BaseType;
795 if (IsArrow) RecordTy = RecordTy->castAs<PointerType>()->getPointeeType();
796 if (LookupMemberExprInRecord(
797 *this, R, nullptr, RecordTy->castAs<RecordType>(), OpLoc, IsArrow,
798 SS, TemplateArgs != nullptr, TemplateKWLoc, TE))
799 return ExprError();
800 if (TE)
801 return TE;
803 // Explicit member accesses.
804 } else {
805 ExprResult BaseResult = Base;
806 ExprResult Result =
807 LookupMemberExpr(*this, R, BaseResult, IsArrow, OpLoc, SS,
808 ExtraArgs ? ExtraArgs->ObjCImpDecl : nullptr,
809 TemplateArgs != nullptr, TemplateKWLoc);
811 if (BaseResult.isInvalid())
812 return ExprError();
813 Base = BaseResult.get();
815 if (Result.isInvalid())
816 return ExprError();
818 if (Result.get())
819 return Result;
821 // LookupMemberExpr can modify Base, and thus change BaseType
822 BaseType = Base->getType();
825 return BuildMemberReferenceExpr(Base, BaseType,
826 OpLoc, IsArrow, SS, TemplateKWLoc,
827 FirstQualifierInScope, R, TemplateArgs, S,
828 false, ExtraArgs);
831 ExprResult
832 Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
833 SourceLocation loc,
834 IndirectFieldDecl *indirectField,
835 DeclAccessPair foundDecl,
836 Expr *baseObjectExpr,
837 SourceLocation opLoc) {
838 // First, build the expression that refers to the base object.
840 // Case 1: the base of the indirect field is not a field.
841 VarDecl *baseVariable = indirectField->getVarDecl();
842 CXXScopeSpec EmptySS;
843 if (baseVariable) {
844 assert(baseVariable->getType()->isRecordType());
846 // In principle we could have a member access expression that
847 // accesses an anonymous struct/union that's a static member of
848 // the base object's class. However, under the current standard,
849 // static data members cannot be anonymous structs or unions.
850 // Supporting this is as easy as building a MemberExpr here.
851 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
853 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
855 ExprResult result
856 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
857 if (result.isInvalid()) return ExprError();
859 baseObjectExpr = result.get();
862 assert((baseVariable || baseObjectExpr) &&
863 "referencing anonymous struct/union without a base variable or "
864 "expression");
866 // Build the implicit member references to the field of the
867 // anonymous struct/union.
868 Expr *result = baseObjectExpr;
869 IndirectFieldDecl::chain_iterator
870 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
872 // Case 2: the base of the indirect field is a field and the user
873 // wrote a member expression.
874 if (!baseVariable) {
875 FieldDecl *field = cast<FieldDecl>(*FI);
877 bool baseObjectIsPointer = baseObjectExpr->getType()->isPointerType();
879 // Make a nameInfo that properly uses the anonymous name.
880 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
882 // Build the first member access in the chain with full information.
883 result =
884 BuildFieldReferenceExpr(result, baseObjectIsPointer, SourceLocation(),
885 SS, field, foundDecl, memberNameInfo)
886 .get();
887 if (!result)
888 return ExprError();
891 // In all cases, we should now skip the first declaration in the chain.
892 ++FI;
894 while (FI != FEnd) {
895 FieldDecl *field = cast<FieldDecl>(*FI++);
897 // FIXME: these are somewhat meaningless
898 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
899 DeclAccessPair fakeFoundDecl =
900 DeclAccessPair::make(field, field->getAccess());
902 result =
903 BuildFieldReferenceExpr(result, /*isarrow*/ false, SourceLocation(),
904 (FI == FEnd ? SS : EmptySS), field,
905 fakeFoundDecl, memberNameInfo)
906 .get();
909 return result;
912 static ExprResult
913 BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
914 const CXXScopeSpec &SS,
915 MSPropertyDecl *PD,
916 const DeclarationNameInfo &NameInfo) {
917 // Property names are always simple identifiers and therefore never
918 // require any interesting additional storage.
919 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
920 S.Context.PseudoObjectTy, VK_LValue,
921 SS.getWithLocInContext(S.Context),
922 NameInfo.getLoc());
925 MemberExpr *Sema::BuildMemberExpr(
926 Expr *Base, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec *SS,
927 SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl,
928 bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo,
929 QualType Ty, ExprValueKind VK, ExprObjectKind OK,
930 const TemplateArgumentListInfo *TemplateArgs) {
931 NestedNameSpecifierLoc NNS =
932 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
933 return BuildMemberExpr(Base, IsArrow, OpLoc, NNS, TemplateKWLoc, Member,
934 FoundDecl, HadMultipleCandidates, MemberNameInfo, Ty,
935 VK, OK, TemplateArgs);
938 MemberExpr *Sema::BuildMemberExpr(
939 Expr *Base, bool IsArrow, SourceLocation OpLoc, NestedNameSpecifierLoc NNS,
940 SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl,
941 bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo,
942 QualType Ty, ExprValueKind VK, ExprObjectKind OK,
943 const TemplateArgumentListInfo *TemplateArgs) {
944 assert((!IsArrow || Base->isPRValue()) &&
945 "-> base must be a pointer prvalue");
946 MemberExpr *E =
947 MemberExpr::Create(Context, Base, IsArrow, OpLoc, NNS, TemplateKWLoc,
948 Member, FoundDecl, MemberNameInfo, TemplateArgs, Ty,
949 VK, OK, getNonOdrUseReasonInCurrentContext(Member));
950 E->setHadMultipleCandidates(HadMultipleCandidates);
951 MarkMemberReferenced(E);
953 // C++ [except.spec]p17:
954 // An exception-specification is considered to be needed when:
955 // - in an expression the function is the unique lookup result or the
956 // selected member of a set of overloaded functions
957 if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
958 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
959 if (auto *NewFPT = ResolveExceptionSpec(MemberNameInfo.getLoc(), FPT))
960 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
964 return E;
967 /// Determine if the given scope is within a function-try-block handler.
968 static bool IsInFnTryBlockHandler(const Scope *S) {
969 // Walk the scope stack until finding a FnTryCatchScope, or leave the
970 // function scope. If a FnTryCatchScope is found, check whether the TryScope
971 // flag is set. If it is not, it's a function-try-block handler.
972 for (; S != S->getFnParent(); S = S->getParent()) {
973 if (S->isFnTryCatchScope())
974 return (S->getFlags() & Scope::TryScope) != Scope::TryScope;
976 return false;
979 ExprResult
980 Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
981 SourceLocation OpLoc, bool IsArrow,
982 const CXXScopeSpec &SS,
983 SourceLocation TemplateKWLoc,
984 NamedDecl *FirstQualifierInScope,
985 LookupResult &R,
986 const TemplateArgumentListInfo *TemplateArgs,
987 const Scope *S,
988 bool SuppressQualifierCheck,
989 ActOnMemberAccessExtraArgs *ExtraArgs) {
990 QualType BaseType = BaseExprType;
991 if (IsArrow) {
992 assert(BaseType->isPointerType());
993 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
995 R.setBaseObjectType(BaseType);
997 // C++1z [expr.ref]p2:
998 // For the first option (dot) the first expression shall be a glvalue [...]
999 if (!IsArrow && BaseExpr && BaseExpr->isPRValue()) {
1000 ExprResult Converted = TemporaryMaterializationConversion(BaseExpr);
1001 if (Converted.isInvalid())
1002 return ExprError();
1003 BaseExpr = Converted.get();
1006 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
1007 DeclarationName MemberName = MemberNameInfo.getName();
1008 SourceLocation MemberLoc = MemberNameInfo.getLoc();
1010 if (R.isAmbiguous())
1011 return ExprError();
1013 // [except.handle]p10: Referring to any non-static member or base class of an
1014 // object in the handler for a function-try-block of a constructor or
1015 // destructor for that object results in undefined behavior.
1016 const auto *FD = getCurFunctionDecl();
1017 if (S && BaseExpr && FD &&
1018 (isa<CXXDestructorDecl>(FD) || isa<CXXConstructorDecl>(FD)) &&
1019 isa<CXXThisExpr>(BaseExpr->IgnoreImpCasts()) &&
1020 IsInFnTryBlockHandler(S))
1021 Diag(MemberLoc, diag::warn_cdtor_function_try_handler_mem_expr)
1022 << isa<CXXDestructorDecl>(FD);
1024 if (R.empty()) {
1025 // Rederive where we looked up.
1026 DeclContext *DC = (SS.isSet()
1027 ? computeDeclContext(SS, false)
1028 : BaseType->castAs<RecordType>()->getDecl());
1030 if (ExtraArgs) {
1031 ExprResult RetryExpr;
1032 if (!IsArrow && BaseExpr) {
1033 SFINAETrap Trap(*this, true);
1034 ParsedType ObjectType;
1035 bool MayBePseudoDestructor = false;
1036 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
1037 OpLoc, tok::arrow, ObjectType,
1038 MayBePseudoDestructor);
1039 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
1040 CXXScopeSpec TempSS(SS);
1041 RetryExpr = ActOnMemberAccessExpr(
1042 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
1043 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl);
1045 if (Trap.hasErrorOccurred())
1046 RetryExpr = ExprError();
1048 if (RetryExpr.isUsable()) {
1049 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
1050 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
1051 return RetryExpr;
1055 Diag(R.getNameLoc(), diag::err_no_member)
1056 << MemberName << DC
1057 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
1058 return ExprError();
1061 // Diagnose lookups that find only declarations from a non-base
1062 // type. This is possible for either qualified lookups (which may
1063 // have been qualified with an unrelated type) or implicit member
1064 // expressions (which were found with unqualified lookup and thus
1065 // may have come from an enclosing scope). Note that it's okay for
1066 // lookup to find declarations from a non-base type as long as those
1067 // aren't the ones picked by overload resolution.
1068 if ((SS.isSet() || !BaseExpr ||
1069 (isa<CXXThisExpr>(BaseExpr) &&
1070 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
1071 !SuppressQualifierCheck &&
1072 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
1073 return ExprError();
1075 // Construct an unresolved result if we in fact got an unresolved
1076 // result.
1077 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
1078 // Suppress any lookup-related diagnostics; we'll do these when we
1079 // pick a member.
1080 R.suppressDiagnostics();
1082 UnresolvedMemberExpr *MemExpr
1083 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
1084 BaseExpr, BaseExprType,
1085 IsArrow, OpLoc,
1086 SS.getWithLocInContext(Context),
1087 TemplateKWLoc, MemberNameInfo,
1088 TemplateArgs, R.begin(), R.end());
1090 return MemExpr;
1093 assert(R.isSingleResult());
1094 DeclAccessPair FoundDecl = R.begin().getPair();
1095 NamedDecl *MemberDecl = R.getFoundDecl();
1097 // FIXME: diagnose the presence of template arguments now.
1099 // If the decl being referenced had an error, return an error for this
1100 // sub-expr without emitting another error, in order to avoid cascading
1101 // error cases.
1102 if (MemberDecl->isInvalidDecl())
1103 return ExprError();
1105 // Handle the implicit-member-access case.
1106 if (!BaseExpr) {
1107 // If this is not an instance member, convert to a non-member access.
1108 if (!MemberDecl->isCXXInstanceMember()) {
1109 // We might have a variable template specialization (or maybe one day a
1110 // member concept-id).
1111 if (TemplateArgs || TemplateKWLoc.isValid())
1112 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/false, TemplateArgs);
1114 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl,
1115 FoundDecl, TemplateArgs);
1117 SourceLocation Loc = R.getNameLoc();
1118 if (SS.getRange().isValid())
1119 Loc = SS.getRange().getBegin();
1120 BaseExpr = BuildCXXThisExpr(Loc, BaseExprType, /*IsImplicit=*/true);
1123 // Check the use of this member.
1124 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1125 return ExprError();
1127 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
1128 return BuildFieldReferenceExpr(BaseExpr, IsArrow, OpLoc, SS, FD, FoundDecl,
1129 MemberNameInfo);
1131 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
1132 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
1133 MemberNameInfo);
1135 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
1136 // We may have found a field within an anonymous union or struct
1137 // (C++ [class.union]).
1138 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
1139 FoundDecl, BaseExpr,
1140 OpLoc);
1142 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
1143 return BuildMemberExpr(BaseExpr, IsArrow, OpLoc, &SS, TemplateKWLoc, Var,
1144 FoundDecl, /*HadMultipleCandidates=*/false,
1145 MemberNameInfo, Var->getType().getNonReferenceType(),
1146 VK_LValue, OK_Ordinary);
1149 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1150 ExprValueKind valueKind;
1151 QualType type;
1152 if (MemberFn->isInstance()) {
1153 valueKind = VK_PRValue;
1154 type = Context.BoundMemberTy;
1155 } else {
1156 valueKind = VK_LValue;
1157 type = MemberFn->getType();
1160 return BuildMemberExpr(BaseExpr, IsArrow, OpLoc, &SS, TemplateKWLoc,
1161 MemberFn, FoundDecl, /*HadMultipleCandidates=*/false,
1162 MemberNameInfo, type, valueKind, OK_Ordinary);
1164 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
1166 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
1167 return BuildMemberExpr(BaseExpr, IsArrow, OpLoc, &SS, TemplateKWLoc, Enum,
1168 FoundDecl, /*HadMultipleCandidates=*/false,
1169 MemberNameInfo, Enum->getType(), VK_PRValue,
1170 OK_Ordinary);
1173 if (VarTemplateDecl *VarTempl = dyn_cast<VarTemplateDecl>(MemberDecl)) {
1174 if (!TemplateArgs) {
1175 diagnoseMissingTemplateArguments(TemplateName(VarTempl), MemberLoc);
1176 return ExprError();
1179 DeclResult VDecl = CheckVarTemplateId(VarTempl, TemplateKWLoc,
1180 MemberNameInfo.getLoc(), *TemplateArgs);
1181 if (VDecl.isInvalid())
1182 return ExprError();
1184 // Non-dependent member, but dependent template arguments.
1185 if (!VDecl.get())
1186 return ActOnDependentMemberExpr(
1187 BaseExpr, BaseExpr->getType(), IsArrow, OpLoc, SS, TemplateKWLoc,
1188 FirstQualifierInScope, MemberNameInfo, TemplateArgs);
1190 VarDecl *Var = cast<VarDecl>(VDecl.get());
1191 if (!Var->getTemplateSpecializationKind())
1192 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation, MemberLoc);
1194 return BuildMemberExpr(BaseExpr, IsArrow, OpLoc, &SS, TemplateKWLoc, Var,
1195 FoundDecl, /*HadMultipleCandidates=*/false,
1196 MemberNameInfo, Var->getType().getNonReferenceType(),
1197 VK_LValue, OK_Ordinary, TemplateArgs);
1200 // We found something that we didn't expect. Complain.
1201 if (isa<TypeDecl>(MemberDecl))
1202 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1203 << MemberName << BaseType << int(IsArrow);
1204 else
1205 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1206 << MemberName << BaseType << int(IsArrow);
1208 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
1209 << MemberName;
1210 R.suppressDiagnostics();
1211 return ExprError();
1214 /// Given that normal member access failed on the given expression,
1215 /// and given that the expression's type involves builtin-id or
1216 /// builtin-Class, decide whether substituting in the redefinition
1217 /// types would be profitable. The redefinition type is whatever
1218 /// this translation unit tried to typedef to id/Class; we store
1219 /// it to the side and then re-use it in places like this.
1220 static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1221 const ObjCObjectPointerType *opty
1222 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1223 if (!opty) return false;
1225 const ObjCObjectType *ty = opty->getObjectType();
1227 QualType redef;
1228 if (ty->isObjCId()) {
1229 redef = S.Context.getObjCIdRedefinitionType();
1230 } else if (ty->isObjCClass()) {
1231 redef = S.Context.getObjCClassRedefinitionType();
1232 } else {
1233 return false;
1236 // Do the substitution as long as the redefinition type isn't just a
1237 // possibly-qualified pointer to builtin-id or builtin-Class again.
1238 opty = redef->getAs<ObjCObjectPointerType>();
1239 if (opty && !opty->getObjectType()->getInterface())
1240 return false;
1242 base = S.ImpCastExprToType(base.get(), redef, CK_BitCast);
1243 return true;
1246 static bool isRecordType(QualType T) {
1247 return T->isRecordType();
1249 static bool isPointerToRecordType(QualType T) {
1250 if (const PointerType *PT = T->getAs<PointerType>())
1251 return PT->getPointeeType()->isRecordType();
1252 return false;
1255 /// Perform conversions on the LHS of a member access expression.
1256 ExprResult
1257 Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
1258 if (IsArrow && !Base->getType()->isFunctionType())
1259 return DefaultFunctionArrayLvalueConversion(Base);
1261 return CheckPlaceholderExpr(Base);
1264 /// Look up the given member of the given non-type-dependent
1265 /// expression. This can return in one of two ways:
1266 /// * If it returns a sentinel null-but-valid result, the caller will
1267 /// assume that lookup was performed and the results written into
1268 /// the provided structure. It will take over from there.
1269 /// * Otherwise, the returned expression will be produced in place of
1270 /// an ordinary member expression.
1272 /// The ObjCImpDecl bit is a gross hack that will need to be properly
1273 /// fixed for ObjC++.
1274 static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
1275 ExprResult &BaseExpr, bool &IsArrow,
1276 SourceLocation OpLoc, CXXScopeSpec &SS,
1277 Decl *ObjCImpDecl, bool HasTemplateArgs,
1278 SourceLocation TemplateKWLoc) {
1279 assert(BaseExpr.get() && "no base expression");
1281 // Perform default conversions.
1282 BaseExpr = S.PerformMemberExprBaseConversion(BaseExpr.get(), IsArrow);
1283 if (BaseExpr.isInvalid())
1284 return ExprError();
1286 QualType BaseType = BaseExpr.get()->getType();
1287 assert(!BaseType->isDependentType());
1289 DeclarationName MemberName = R.getLookupName();
1290 SourceLocation MemberLoc = R.getNameLoc();
1292 // For later type-checking purposes, turn arrow accesses into dot
1293 // accesses. The only access type we support that doesn't follow
1294 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1295 // and those never use arrows, so this is unaffected.
1296 if (IsArrow) {
1297 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1298 BaseType = Ptr->getPointeeType();
1299 else if (const ObjCObjectPointerType *Ptr
1300 = BaseType->getAs<ObjCObjectPointerType>())
1301 BaseType = Ptr->getPointeeType();
1302 else if (BaseType->isRecordType()) {
1303 // Recover from arrow accesses to records, e.g.:
1304 // struct MyRecord foo;
1305 // foo->bar
1306 // This is actually well-formed in C++ if MyRecord has an
1307 // overloaded operator->, but that should have been dealt with
1308 // by now--or a diagnostic message already issued if a problem
1309 // was encountered while looking for the overloaded operator->.
1310 if (!S.getLangOpts().CPlusPlus) {
1311 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1312 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1313 << FixItHint::CreateReplacement(OpLoc, ".");
1315 IsArrow = false;
1316 } else if (BaseType->isFunctionType()) {
1317 goto fail;
1318 } else {
1319 S.Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1320 << BaseType << BaseExpr.get()->getSourceRange();
1321 return ExprError();
1325 // If the base type is an atomic type, this access is undefined behavior per
1326 // C11 6.5.2.3p5. Instead of giving a typecheck error, we'll warn the user
1327 // about the UB and recover by converting the atomic lvalue into a non-atomic
1328 // lvalue. Because this is inherently unsafe as an atomic operation, the
1329 // warning defaults to an error.
1330 if (const auto *ATy = BaseType->getAs<AtomicType>()) {
1331 S.DiagRuntimeBehavior(OpLoc, nullptr,
1332 S.PDiag(diag::warn_atomic_member_access));
1333 BaseType = ATy->getValueType().getUnqualifiedType();
1334 BaseExpr = ImplicitCastExpr::Create(
1335 S.Context, IsArrow ? S.Context.getPointerType(BaseType) : BaseType,
1336 CK_AtomicToNonAtomic, BaseExpr.get(), nullptr,
1337 BaseExpr.get()->getValueKind(), FPOptionsOverride());
1340 // Handle field access to simple records.
1341 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
1342 TypoExpr *TE = nullptr;
1343 if (LookupMemberExprInRecord(S, R, BaseExpr.get(), RTy, OpLoc, IsArrow, SS,
1344 HasTemplateArgs, TemplateKWLoc, TE))
1345 return ExprError();
1347 // Returning valid-but-null is how we indicate to the caller that
1348 // the lookup result was filled in. If typo correction was attempted and
1349 // failed, the lookup result will have been cleared--that combined with the
1350 // valid-but-null ExprResult will trigger the appropriate diagnostics.
1351 return ExprResult(TE);
1354 // Handle ivar access to Objective-C objects.
1355 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
1356 if (!SS.isEmpty() && !SS.isInvalid()) {
1357 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1358 << 1 << SS.getScopeRep()
1359 << FixItHint::CreateRemoval(SS.getRange());
1360 SS.clear();
1363 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1365 // There are three cases for the base type:
1366 // - builtin id (qualified or unqualified)
1367 // - builtin Class (qualified or unqualified)
1368 // - an interface
1369 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1370 if (!IDecl) {
1371 if (S.getLangOpts().ObjCAutoRefCount &&
1372 (OTy->isObjCId() || OTy->isObjCClass()))
1373 goto fail;
1374 // There's an implicit 'isa' ivar on all objects.
1375 // But we only actually find it this way on objects of type 'id',
1376 // apparently.
1377 if (OTy->isObjCId() && Member->isStr("isa"))
1378 return new (S.Context) ObjCIsaExpr(BaseExpr.get(), IsArrow, MemberLoc,
1379 OpLoc, S.Context.getObjCClassType());
1380 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1381 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1382 ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
1383 goto fail;
1386 if (S.RequireCompleteType(OpLoc, BaseType,
1387 diag::err_typecheck_incomplete_tag,
1388 BaseExpr.get()))
1389 return ExprError();
1391 ObjCInterfaceDecl *ClassDeclared = nullptr;
1392 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1394 if (!IV) {
1395 // Attempt to correct for typos in ivar names.
1396 DeclFilterCCC<ObjCIvarDecl> Validator{};
1397 Validator.IsObjCIvarLookup = IsArrow;
1398 if (TypoCorrection Corrected = S.CorrectTypo(
1399 R.getLookupNameInfo(), Sema::LookupMemberName, nullptr, nullptr,
1400 Validator, Sema::CTK_ErrorRecovery, IDecl)) {
1401 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
1402 S.diagnoseTypo(
1403 Corrected,
1404 S.PDiag(diag::err_typecheck_member_reference_ivar_suggest)
1405 << IDecl->getDeclName() << MemberName);
1407 // Figure out the class that declares the ivar.
1408 assert(!ClassDeclared);
1410 Decl *D = cast<Decl>(IV->getDeclContext());
1411 if (auto *Category = dyn_cast<ObjCCategoryDecl>(D))
1412 D = Category->getClassInterface();
1414 if (auto *Implementation = dyn_cast<ObjCImplementationDecl>(D))
1415 ClassDeclared = Implementation->getClassInterface();
1416 else if (auto *Interface = dyn_cast<ObjCInterfaceDecl>(D))
1417 ClassDeclared = Interface;
1419 assert(ClassDeclared && "cannot query interface");
1420 } else {
1421 if (IsArrow &&
1422 IDecl->FindPropertyDeclaration(
1423 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
1424 S.Diag(MemberLoc, diag::err_property_found_suggest)
1425 << Member << BaseExpr.get()->getType()
1426 << FixItHint::CreateReplacement(OpLoc, ".");
1427 return ExprError();
1430 S.Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1431 << IDecl->getDeclName() << MemberName
1432 << BaseExpr.get()->getSourceRange();
1433 return ExprError();
1437 assert(ClassDeclared);
1439 // If the decl being referenced had an error, return an error for this
1440 // sub-expr without emitting another error, in order to avoid cascading
1441 // error cases.
1442 if (IV->isInvalidDecl())
1443 return ExprError();
1445 // Check whether we can reference this field.
1446 if (S.DiagnoseUseOfDecl(IV, MemberLoc))
1447 return ExprError();
1448 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1449 IV->getAccessControl() != ObjCIvarDecl::Package) {
1450 ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
1451 if (ObjCMethodDecl *MD = S.getCurMethodDecl())
1452 ClassOfMethodDecl = MD->getClassInterface();
1453 else if (ObjCImpDecl && S.getCurFunctionDecl()) {
1454 // Case of a c-function declared inside an objc implementation.
1455 // FIXME: For a c-style function nested inside an objc implementation
1456 // class, there is no implementation context available, so we pass
1457 // down the context as argument to this routine. Ideally, this context
1458 // need be passed down in the AST node and somehow calculated from the
1459 // AST for a function decl.
1460 if (ObjCImplementationDecl *IMPD =
1461 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1462 ClassOfMethodDecl = IMPD->getClassInterface();
1463 else if (ObjCCategoryImplDecl* CatImplClass =
1464 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1465 ClassOfMethodDecl = CatImplClass->getClassInterface();
1467 if (!S.getLangOpts().DebuggerSupport) {
1468 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1469 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1470 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
1471 S.Diag(MemberLoc, diag::err_private_ivar_access)
1472 << IV->getDeclName();
1473 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1474 // @protected
1475 S.Diag(MemberLoc, diag::err_protected_ivar_access)
1476 << IV->getDeclName();
1479 bool warn = true;
1480 if (S.getLangOpts().ObjCWeak) {
1481 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1482 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1483 if (UO->getOpcode() == UO_Deref)
1484 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1486 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
1487 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1488 S.Diag(DE->getLocation(), diag::err_arc_weak_ivar_access);
1489 warn = false;
1492 if (warn) {
1493 if (ObjCMethodDecl *MD = S.getCurMethodDecl()) {
1494 ObjCMethodFamily MF = MD->getMethodFamily();
1495 warn = (MF != OMF_init && MF != OMF_dealloc &&
1496 MF != OMF_finalize &&
1497 !S.IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
1499 if (warn)
1500 S.Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
1503 ObjCIvarRefExpr *Result = new (S.Context) ObjCIvarRefExpr(
1504 IV, IV->getUsageType(BaseType), MemberLoc, OpLoc, BaseExpr.get(),
1505 IsArrow);
1507 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1508 if (!S.isUnevaluatedContext() &&
1509 !S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, MemberLoc))
1510 S.getCurFunction()->recordUseOfWeak(Result);
1513 return Result;
1516 // Objective-C property access.
1517 const ObjCObjectPointerType *OPT;
1518 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
1519 if (!SS.isEmpty() && !SS.isInvalid()) {
1520 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1521 << 0 << SS.getScopeRep() << FixItHint::CreateRemoval(SS.getRange());
1522 SS.clear();
1525 // This actually uses the base as an r-value.
1526 BaseExpr = S.DefaultLvalueConversion(BaseExpr.get());
1527 if (BaseExpr.isInvalid())
1528 return ExprError();
1530 assert(S.Context.hasSameUnqualifiedType(BaseType,
1531 BaseExpr.get()->getType()));
1533 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1535 const ObjCObjectType *OT = OPT->getObjectType();
1537 // id, with and without qualifiers.
1538 if (OT->isObjCId()) {
1539 // Check protocols on qualified interfaces.
1540 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
1541 if (Decl *PMDecl =
1542 FindGetterSetterNameDecl(OPT, Member, Sel, S.Context)) {
1543 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1544 // Check the use of this declaration
1545 if (S.DiagnoseUseOfDecl(PD, MemberLoc))
1546 return ExprError();
1548 return new (S.Context)
1549 ObjCPropertyRefExpr(PD, S.Context.PseudoObjectTy, VK_LValue,
1550 OK_ObjCProperty, MemberLoc, BaseExpr.get());
1553 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1554 Selector SetterSel =
1555 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1556 S.PP.getSelectorTable(),
1557 Member);
1558 ObjCMethodDecl *SMD = nullptr;
1559 if (Decl *SDecl = FindGetterSetterNameDecl(OPT,
1560 /*Property id*/ nullptr,
1561 SetterSel, S.Context))
1562 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
1564 return new (S.Context)
1565 ObjCPropertyRefExpr(OMD, SMD, S.Context.PseudoObjectTy, VK_LValue,
1566 OK_ObjCProperty, MemberLoc, BaseExpr.get());
1569 // Use of id.member can only be for a property reference. Do not
1570 // use the 'id' redefinition in this case.
1571 if (IsArrow && ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1572 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1573 ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
1575 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
1576 << MemberName << BaseType);
1579 // 'Class', unqualified only.
1580 if (OT->isObjCClass()) {
1581 // Only works in a method declaration (??!).
1582 ObjCMethodDecl *MD = S.getCurMethodDecl();
1583 if (!MD) {
1584 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1585 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1586 ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
1588 goto fail;
1591 // Also must look for a getter name which uses property syntax.
1592 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
1593 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1594 if (!IFace)
1595 goto fail;
1597 ObjCMethodDecl *Getter;
1598 if ((Getter = IFace->lookupClassMethod(Sel))) {
1599 // Check the use of this method.
1600 if (S.DiagnoseUseOfDecl(Getter, MemberLoc))
1601 return ExprError();
1602 } else
1603 Getter = IFace->lookupPrivateMethod(Sel, false);
1604 // If we found a getter then this may be a valid dot-reference, we
1605 // will look for the matching setter, in case it is needed.
1606 Selector SetterSel =
1607 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1608 S.PP.getSelectorTable(),
1609 Member);
1610 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1611 if (!Setter) {
1612 // If this reference is in an @implementation, also check for 'private'
1613 // methods.
1614 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1617 if (Setter && S.DiagnoseUseOfDecl(Setter, MemberLoc))
1618 return ExprError();
1620 if (Getter || Setter) {
1621 return new (S.Context) ObjCPropertyRefExpr(
1622 Getter, Setter, S.Context.PseudoObjectTy, VK_LValue,
1623 OK_ObjCProperty, MemberLoc, BaseExpr.get());
1626 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1627 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1628 ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
1630 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
1631 << MemberName << BaseType);
1634 // Normal property access.
1635 return S.HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc, MemberName,
1636 MemberLoc, SourceLocation(), QualType(),
1637 false);
1640 if (BaseType->isExtVectorBoolType()) {
1641 // We disallow element access for ext_vector_type bool. There is no way to
1642 // materialize a reference to a vector element as a pointer (each element is
1643 // one bit in the vector).
1644 S.Diag(R.getNameLoc(), diag::err_ext_vector_component_name_illegal)
1645 << MemberName
1646 << (BaseExpr.get() ? BaseExpr.get()->getSourceRange() : SourceRange());
1647 return ExprError();
1650 // Handle 'field access' to vectors, such as 'V.xx'.
1651 if (BaseType->isExtVectorType()) {
1652 // FIXME: this expr should store IsArrow.
1653 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1654 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
1655 QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
1656 Member, MemberLoc);
1657 if (ret.isNull())
1658 return ExprError();
1659 Qualifiers BaseQ =
1660 S.Context.getCanonicalType(BaseExpr.get()->getType()).getQualifiers();
1661 ret = S.Context.getQualifiedType(ret, BaseQ);
1663 return new (S.Context)
1664 ExtVectorElementExpr(ret, VK, BaseExpr.get(), *Member, MemberLoc);
1667 // Adjust builtin-sel to the appropriate redefinition type if that's
1668 // not just a pointer to builtin-sel again.
1669 if (IsArrow && BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
1670 !S.Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1671 BaseExpr = S.ImpCastExprToType(
1672 BaseExpr.get(), S.Context.getObjCSelRedefinitionType(), CK_BitCast);
1673 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1674 ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
1677 // Failure cases.
1678 fail:
1680 // Recover from dot accesses to pointers, e.g.:
1681 // type *foo;
1682 // foo.bar
1683 // This is actually well-formed in two cases:
1684 // - 'type' is an Objective C type
1685 // - 'bar' is a pseudo-destructor name which happens to refer to
1686 // the appropriate pointer type
1687 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1688 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1689 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1690 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1691 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1692 << FixItHint::CreateReplacement(OpLoc, "->");
1694 if (S.isSFINAEContext())
1695 return ExprError();
1697 // Recurse as an -> access.
1698 IsArrow = true;
1699 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1700 ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
1704 // If the user is trying to apply -> or . to a function name, it's probably
1705 // because they forgot parentheses to call that function.
1706 if (S.tryToRecoverWithCall(
1707 BaseExpr, S.PDiag(diag::err_member_reference_needs_call),
1708 /*complain*/ false,
1709 IsArrow ? &isPointerToRecordType : &isRecordType)) {
1710 if (BaseExpr.isInvalid())
1711 return ExprError();
1712 BaseExpr = S.DefaultFunctionArrayConversion(BaseExpr.get());
1713 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1714 ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
1717 S.Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
1718 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
1720 return ExprError();
1723 /// The main callback when the parser finds something like
1724 /// expression . [nested-name-specifier] identifier
1725 /// expression -> [nested-name-specifier] identifier
1726 /// where 'identifier' encompasses a fairly broad spectrum of
1727 /// possibilities, including destructor and operator references.
1729 /// \param OpKind either tok::arrow or tok::period
1730 /// \param ObjCImpDecl the current Objective-C \@implementation
1731 /// decl; this is an ugly hack around the fact that Objective-C
1732 /// \@implementations aren't properly put in the context chain
1733 ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1734 SourceLocation OpLoc,
1735 tok::TokenKind OpKind,
1736 CXXScopeSpec &SS,
1737 SourceLocation TemplateKWLoc,
1738 UnqualifiedId &Id,
1739 Decl *ObjCImpDecl) {
1740 if (SS.isSet() && SS.isInvalid())
1741 return ExprError();
1743 // Warn about the explicit constructor calls Microsoft extension.
1744 if (getLangOpts().MicrosoftExt &&
1745 Id.getKind() == UnqualifiedIdKind::IK_ConstructorName)
1746 Diag(Id.getSourceRange().getBegin(),
1747 diag::ext_ms_explicit_constructor_call);
1749 TemplateArgumentListInfo TemplateArgsBuffer;
1751 // Decompose the name into its component parts.
1752 DeclarationNameInfo NameInfo;
1753 const TemplateArgumentListInfo *TemplateArgs;
1754 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1755 NameInfo, TemplateArgs);
1757 DeclarationName Name = NameInfo.getName();
1758 bool IsArrow = (OpKind == tok::arrow);
1760 if (getLangOpts().HLSL && IsArrow)
1761 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 2);
1763 NamedDecl *FirstQualifierInScope
1764 = (!SS.isSet() ? nullptr : FindFirstQualifierInScope(S, SS.getScopeRep()));
1766 // This is a postfix expression, so get rid of ParenListExprs.
1767 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1768 if (Result.isInvalid()) return ExprError();
1769 Base = Result.get();
1771 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1772 isDependentScopeSpecifier(SS)) {
1773 return ActOnDependentMemberExpr(Base, Base->getType(), IsArrow, OpLoc, SS,
1774 TemplateKWLoc, FirstQualifierInScope,
1775 NameInfo, TemplateArgs);
1778 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl};
1779 ExprResult Res = BuildMemberReferenceExpr(
1780 Base, Base->getType(), OpLoc, IsArrow, SS, TemplateKWLoc,
1781 FirstQualifierInScope, NameInfo, TemplateArgs, S, &ExtraArgs);
1783 if (!Res.isInvalid() && isa<MemberExpr>(Res.get()))
1784 CheckMemberAccessOfNoDeref(cast<MemberExpr>(Res.get()));
1786 return Res;
1789 void Sema::CheckMemberAccessOfNoDeref(const MemberExpr *E) {
1790 if (isUnevaluatedContext())
1791 return;
1793 QualType ResultTy = E->getType();
1795 // Member accesses have four cases:
1796 // 1: non-array member via "->": dereferences
1797 // 2: non-array member via ".": nothing interesting happens
1798 // 3: array member access via "->": nothing interesting happens
1799 // (this returns an array lvalue and does not actually dereference memory)
1800 // 4: array member access via ".": *adds* a layer of indirection
1801 if (ResultTy->isArrayType()) {
1802 if (!E->isArrow()) {
1803 // This might be something like:
1804 // (*structPtr).arrayMember
1805 // which behaves roughly like:
1806 // &(*structPtr).pointerMember
1807 // in that the apparent dereference in the base expression does not
1808 // actually happen.
1809 CheckAddressOfNoDeref(E->getBase());
1811 } else if (E->isArrow()) {
1812 if (const auto *Ptr = dyn_cast<PointerType>(
1813 E->getBase()->getType().getDesugaredType(Context))) {
1814 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
1815 ExprEvalContexts.back().PossibleDerefs.insert(E);
1820 ExprResult
1821 Sema::BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
1822 SourceLocation OpLoc, const CXXScopeSpec &SS,
1823 FieldDecl *Field, DeclAccessPair FoundDecl,
1824 const DeclarationNameInfo &MemberNameInfo) {
1825 // x.a is an l-value if 'a' has a reference type. Otherwise:
1826 // x.a is an l-value/x-value/pr-value if the base is (and note
1827 // that *x is always an l-value), except that if the base isn't
1828 // an ordinary object then we must have an rvalue.
1829 ExprValueKind VK = VK_LValue;
1830 ExprObjectKind OK = OK_Ordinary;
1831 if (!IsArrow) {
1832 if (BaseExpr->getObjectKind() == OK_Ordinary)
1833 VK = BaseExpr->getValueKind();
1834 else
1835 VK = VK_PRValue;
1837 if (VK != VK_PRValue && Field->isBitField())
1838 OK = OK_BitField;
1840 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1841 QualType MemberType = Field->getType();
1842 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1843 MemberType = Ref->getPointeeType();
1844 VK = VK_LValue;
1845 } else {
1846 QualType BaseType = BaseExpr->getType();
1847 if (IsArrow) BaseType = BaseType->castAs<PointerType>()->getPointeeType();
1849 Qualifiers BaseQuals = BaseType.getQualifiers();
1851 // GC attributes are never picked up by members.
1852 BaseQuals.removeObjCGCAttr();
1854 // CVR attributes from the base are picked up by members,
1855 // except that 'mutable' members don't pick up 'const'.
1856 if (Field->isMutable()) BaseQuals.removeConst();
1858 Qualifiers MemberQuals =
1859 Context.getCanonicalType(MemberType).getQualifiers();
1861 assert(!MemberQuals.hasAddressSpace());
1863 Qualifiers Combined = BaseQuals + MemberQuals;
1864 if (Combined != MemberQuals)
1865 MemberType = Context.getQualifiedType(MemberType, Combined);
1867 // Pick up NoDeref from the base in case we end up using AddrOf on the
1868 // result. E.g. the expression
1869 // &someNoDerefPtr->pointerMember
1870 // should be a noderef pointer again.
1871 if (BaseType->hasAttr(attr::NoDeref))
1872 MemberType =
1873 Context.getAttributedType(attr::NoDeref, MemberType, MemberType);
1876 auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1877 if (!(CurMethod && CurMethod->isDefaulted()))
1878 UnusedPrivateFields.remove(Field);
1880 ExprResult Base = PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1881 FoundDecl, Field);
1882 if (Base.isInvalid())
1883 return ExprError();
1885 // Build a reference to a private copy for non-static data members in
1886 // non-static member functions, privatized by OpenMP constructs.
1887 if (getLangOpts().OpenMP && IsArrow &&
1888 !CurContext->isDependentContext() &&
1889 isa<CXXThisExpr>(Base.get()->IgnoreParenImpCasts())) {
1890 if (auto *PrivateCopy = isOpenMPCapturedDecl(Field)) {
1891 return getOpenMPCapturedExpr(PrivateCopy, VK, OK,
1892 MemberNameInfo.getLoc());
1896 return BuildMemberExpr(Base.get(), IsArrow, OpLoc, &SS,
1897 /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl,
1898 /*HadMultipleCandidates=*/false, MemberNameInfo,
1899 MemberType, VK, OK);
1902 /// Builds an implicit member access expression. The current context
1903 /// is known to be an instance method, and the given unqualified lookup
1904 /// set is known to contain only instance members, at least one of which
1905 /// is from an appropriate type.
1906 ExprResult
1907 Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1908 SourceLocation TemplateKWLoc,
1909 LookupResult &R,
1910 const TemplateArgumentListInfo *TemplateArgs,
1911 bool IsKnownInstance, const Scope *S) {
1912 assert(!R.empty() && !R.isAmbiguous());
1914 SourceLocation loc = R.getNameLoc();
1916 // If this is known to be an instance access, go ahead and build an
1917 // implicit 'this' expression now.
1918 QualType ThisTy = getCurrentThisType();
1919 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1921 Expr *baseExpr = nullptr; // null signifies implicit access
1922 if (IsKnownInstance) {
1923 SourceLocation Loc = R.getNameLoc();
1924 if (SS.getRange().isValid())
1925 Loc = SS.getRange().getBegin();
1926 baseExpr = BuildCXXThisExpr(loc, ThisTy, /*IsImplicit=*/true);
1929 return BuildMemberReferenceExpr(
1930 baseExpr, ThisTy,
1931 /*OpLoc=*/SourceLocation(),
1932 /*IsArrow=*/!getLangOpts().HLSL, SS, TemplateKWLoc,
1933 /*FirstQualifierInScope=*/nullptr, R, TemplateArgs, S);