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