SemaExprMember.cpp 74 KB

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