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