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