SemaExprMember.cpp 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863
  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::PotentiallyEvaluated:
  123. case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  124. break;
  125. }
  126. // If the current context is not an instance method, it can't be
  127. // an implicit member reference.
  128. if (isStaticContext) {
  129. if (hasNonInstance)
  130. return IMA_Mixed_StaticContext;
  131. return AbstractInstanceResult ? AbstractInstanceResult
  132. : IMA_Error_StaticContext;
  133. }
  134. CXXRecordDecl *contextClass;
  135. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
  136. contextClass = MD->getParent()->getCanonicalDecl();
  137. else
  138. contextClass = cast<CXXRecordDecl>(DC);
  139. // [class.mfct.non-static]p3:
  140. // ...is used in the body of a non-static member function of class X,
  141. // if name lookup (3.4.1) resolves the name in the id-expression to a
  142. // non-static non-type member of some class C [...]
  143. // ...if C is not X or a base class of X, the class member access expression
  144. // is ill-formed.
  145. if (R.getNamingClass() &&
  146. contextClass->getCanonicalDecl() !=
  147. R.getNamingClass()->getCanonicalDecl()) {
  148. // If the naming class is not the current context, this was a qualified
  149. // member name lookup, and it's sufficient to check that we have the naming
  150. // class as a base class.
  151. Classes.clear();
  152. Classes.insert(R.getNamingClass()->getCanonicalDecl());
  153. }
  154. // If we can prove that the current context is unrelated to all the
  155. // declaring classes, it can't be an implicit member reference (in
  156. // which case it's an error if any of those members are selected).
  157. if (isProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
  158. return hasNonInstance ? IMA_Mixed_Unrelated :
  159. AbstractInstanceResult ? AbstractInstanceResult :
  160. IMA_Error_Unrelated;
  161. return (hasNonInstance ? IMA_Mixed : IMA_Instance);
  162. }
  163. /// Diagnose a reference to a field with no object available.
  164. static void diagnoseInstanceReference(Sema &SemaRef,
  165. const CXXScopeSpec &SS,
  166. NamedDecl *Rep,
  167. const DeclarationNameInfo &nameInfo) {
  168. SourceLocation Loc = nameInfo.getLoc();
  169. SourceRange Range(Loc);
  170. if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
  171. // Look through using shadow decls and aliases.
  172. Rep = Rep->getUnderlyingDecl();
  173. DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
  174. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
  175. CXXRecordDecl *ContextClass = Method ? Method->getParent() : nullptr;
  176. CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
  177. bool InStaticMethod = Method && Method->isStatic();
  178. bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
  179. if (IsField && InStaticMethod)
  180. // "invalid use of member 'x' in static member function"
  181. SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
  182. << Range << nameInfo.getName();
  183. else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
  184. !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
  185. // Unqualified lookup in a non-static member function found a member of an
  186. // enclosing class.
  187. SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
  188. << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
  189. else if (IsField)
  190. SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
  191. << nameInfo.getName() << Range;
  192. else
  193. SemaRef.Diag(Loc, diag::err_member_call_without_object)
  194. << Range;
  195. }
  196. /// Builds an expression which might be an implicit member expression.
  197. ExprResult
  198. Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
  199. SourceLocation TemplateKWLoc,
  200. LookupResult &R,
  201. const TemplateArgumentListInfo *TemplateArgs,
  202. const Scope *S) {
  203. switch (ClassifyImplicitMemberAccess(*this, R)) {
  204. case IMA_Instance:
  205. return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true, S);
  206. case IMA_Mixed:
  207. case IMA_Mixed_Unrelated:
  208. case IMA_Unresolved:
  209. return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false,
  210. S);
  211. case IMA_Field_Uneval_Context:
  212. Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
  213. << R.getLookupNameInfo().getName();
  214. LLVM_FALLTHROUGH;
  215. case IMA_Static:
  216. case IMA_Abstract:
  217. case IMA_Mixed_StaticContext:
  218. case IMA_Unresolved_StaticContext:
  219. if (TemplateArgs || TemplateKWLoc.isValid())
  220. return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
  221. return BuildDeclarationNameExpr(SS, R, false);
  222. case IMA_Error_StaticContext:
  223. case IMA_Error_Unrelated:
  224. diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
  225. R.getLookupNameInfo());
  226. return ExprError();
  227. }
  228. llvm_unreachable("unexpected instance member access kind");
  229. }
  230. /// Determine whether input char is from rgba component set.
  231. static bool
  232. IsRGBA(char c) {
  233. switch (c) {
  234. case 'r':
  235. case 'g':
  236. case 'b':
  237. case 'a':
  238. return true;
  239. default:
  240. return false;
  241. }
  242. }
  243. // OpenCL v1.1, s6.1.7
  244. // The component swizzle length must be in accordance with the acceptable
  245. // vector sizes.
  246. static bool IsValidOpenCLComponentSwizzleLength(unsigned len)
  247. {
  248. return (len >= 1 && len <= 4) || len == 8 || len == 16;
  249. }
  250. /// Check an ext-vector component access expression.
  251. ///
  252. /// VK should be set in advance to the value kind of the base
  253. /// expression.
  254. static QualType
  255. CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
  256. SourceLocation OpLoc, const IdentifierInfo *CompName,
  257. SourceLocation CompLoc) {
  258. // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
  259. // see FIXME there.
  260. //
  261. // FIXME: This logic can be greatly simplified by splitting it along
  262. // halving/not halving and reworking the component checking.
  263. const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
  264. // The vector accessor can't exceed the number of elements.
  265. const char *compStr = CompName->getNameStart();
  266. // This flag determines whether or not the component is one of the four
  267. // special names that indicate a subset of exactly half the elements are
  268. // to be selected.
  269. bool HalvingSwizzle = false;
  270. // This flag determines whether or not CompName has an 's' char prefix,
  271. // indicating that it is a string of hex values to be used as vector indices.
  272. bool HexSwizzle = (*compStr == 's' || *compStr == 'S') && compStr[1];
  273. bool HasRepeated = false;
  274. bool HasIndex[16] = {};
  275. int Idx;
  276. // Check that we've found one of the special components, or that the component
  277. // names must come from the same set.
  278. if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
  279. !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
  280. HalvingSwizzle = true;
  281. } else if (!HexSwizzle &&
  282. (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
  283. bool HasRGBA = IsRGBA(*compStr);
  284. do {
  285. // Ensure that xyzw and rgba components don't intermingle.
  286. if (HasRGBA != IsRGBA(*compStr))
  287. break;
  288. if (HasIndex[Idx]) HasRepeated = true;
  289. HasIndex[Idx] = true;
  290. compStr++;
  291. } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
  292. // Emit a warning if an rgba selector is used earlier than OpenCL 2.2
  293. if (HasRGBA || (*compStr && IsRGBA(*compStr))) {
  294. if (S.getLangOpts().OpenCL && S.getLangOpts().OpenCLVersion < 220) {
  295. const char *DiagBegin = HasRGBA ? CompName->getNameStart() : compStr;
  296. S.Diag(OpLoc, diag::ext_opencl_ext_vector_type_rgba_selector)
  297. << StringRef(DiagBegin, 1)
  298. << S.getLangOpts().OpenCLVersion << SourceRange(CompLoc);
  299. }
  300. }
  301. } else {
  302. if (HexSwizzle) compStr++;
  303. while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
  304. if (HasIndex[Idx]) HasRepeated = true;
  305. HasIndex[Idx] = true;
  306. compStr++;
  307. }
  308. }
  309. if (!HalvingSwizzle && *compStr) {
  310. // We didn't get to the end of the string. This means the component names
  311. // didn't come from the same set *or* we encountered an illegal name.
  312. S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
  313. << StringRef(compStr, 1) << SourceRange(CompLoc);
  314. return QualType();
  315. }
  316. // Ensure no component accessor exceeds the width of the vector type it
  317. // operates on.
  318. if (!HalvingSwizzle) {
  319. compStr = CompName->getNameStart();
  320. if (HexSwizzle)
  321. compStr++;
  322. while (*compStr) {
  323. if (!vecType->isAccessorWithinNumElements(*compStr++, HexSwizzle)) {
  324. S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
  325. << baseType << SourceRange(CompLoc);
  326. return QualType();
  327. }
  328. }
  329. }
  330. // OpenCL mode requires swizzle length to be in accordance with accepted
  331. // sizes. Clang however supports arbitrary lengths for other languages.
  332. if (S.getLangOpts().OpenCL && !HalvingSwizzle) {
  333. unsigned SwizzleLength = CompName->getLength();
  334. if (HexSwizzle)
  335. SwizzleLength--;
  336. if (IsValidOpenCLComponentSwizzleLength(SwizzleLength) == false) {
  337. S.Diag(OpLoc, diag::err_opencl_ext_vector_component_invalid_length)
  338. << SwizzleLength << SourceRange(CompLoc);
  339. return QualType();
  340. }
  341. }
  342. // The component accessor looks fine - now we need to compute the actual type.
  343. // The vector type is implied by the component accessor. For example,
  344. // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
  345. // vec4.s0 is a float, vec4.s23 is a vec3, etc.
  346. // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
  347. unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
  348. : CompName->getLength();
  349. if (HexSwizzle)
  350. CompSize--;
  351. if (CompSize == 1)
  352. return vecType->getElementType();
  353. if (HasRepeated) VK = VK_RValue;
  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() ||
  440. NameInfo.getName().isDependentName() ||
  441. isDependentScopeSpecifier(SS));
  442. // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
  443. // must have pointer type, and the accessed type is the pointee.
  444. return CXXDependentScopeMemberExpr::Create(
  445. Context, BaseExpr, BaseType, IsArrow, OpLoc,
  446. SS.getWithLocInContext(Context), TemplateKWLoc, FirstQualifierInScope,
  447. NameInfo, TemplateArgs);
  448. }
  449. /// We know that the given qualified member reference points only to
  450. /// declarations which do not belong to the static type of the base
  451. /// expression. Diagnose the problem.
  452. static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
  453. Expr *BaseExpr,
  454. QualType BaseType,
  455. const CXXScopeSpec &SS,
  456. NamedDecl *rep,
  457. const DeclarationNameInfo &nameInfo) {
  458. // If this is an implicit member access, use a different set of
  459. // diagnostics.
  460. if (!BaseExpr)
  461. return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
  462. SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
  463. << SS.getRange() << rep << BaseType;
  464. }
  465. // Check whether the declarations we found through a nested-name
  466. // specifier in a member expression are actually members of the base
  467. // type. The restriction here is:
  468. //
  469. // C++ [expr.ref]p2:
  470. // ... In these cases, the id-expression shall name a
  471. // member of the class or of one of its base classes.
  472. //
  473. // So it's perfectly legitimate for the nested-name specifier to name
  474. // an unrelated class, and for us to find an overload set including
  475. // decls from classes which are not superclasses, as long as the decl
  476. // we actually pick through overload resolution is from a superclass.
  477. bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
  478. QualType BaseType,
  479. const CXXScopeSpec &SS,
  480. const LookupResult &R) {
  481. CXXRecordDecl *BaseRecord =
  482. cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType));
  483. if (!BaseRecord) {
  484. // We can't check this yet because the base type is still
  485. // dependent.
  486. assert(BaseType->isDependentType());
  487. return false;
  488. }
  489. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  490. // If this is an implicit member reference and we find a
  491. // non-instance member, it's not an error.
  492. if (!BaseExpr && !(*I)->isCXXInstanceMember())
  493. return false;
  494. // Note that we use the DC of the decl, not the underlying decl.
  495. DeclContext *DC = (*I)->getDeclContext();
  496. while (DC->isTransparentContext())
  497. DC = DC->getParent();
  498. if (!DC->isRecord())
  499. continue;
  500. CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
  501. if (BaseRecord->getCanonicalDecl() == MemberRecord ||
  502. !BaseRecord->isProvablyNotDerivedFrom(MemberRecord))
  503. return false;
  504. }
  505. DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
  506. R.getRepresentativeDecl(),
  507. R.getLookupNameInfo());
  508. return true;
  509. }
  510. namespace {
  511. // Callback to only accept typo corrections that are either a ValueDecl or a
  512. // FunctionTemplateDecl and are declared in the current record or, for a C++
  513. // classes, one of its base classes.
  514. class RecordMemberExprValidatorCCC final : public CorrectionCandidateCallback {
  515. public:
  516. explicit RecordMemberExprValidatorCCC(const RecordType *RTy)
  517. : Record(RTy->getDecl()) {
  518. // Don't add bare keywords to the consumer since they will always fail
  519. // validation by virtue of not being associated with any decls.
  520. WantTypeSpecifiers = false;
  521. WantExpressionKeywords = false;
  522. WantCXXNamedCasts = false;
  523. WantFunctionLikeCasts = false;
  524. WantRemainingKeywords = false;
  525. }
  526. bool ValidateCandidate(const TypoCorrection &candidate) override {
  527. NamedDecl *ND = candidate.getCorrectionDecl();
  528. // Don't accept candidates that cannot be member functions, constants,
  529. // variables, or templates.
  530. if (!ND || !(isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)))
  531. return false;
  532. // Accept candidates that occur in the current record.
  533. if (Record->containsDecl(ND))
  534. return true;
  535. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) {
  536. // Accept candidates that occur in any of the current class' base classes.
  537. for (const auto &BS : RD->bases()) {
  538. if (const RecordType *BSTy =
  539. dyn_cast_or_null<RecordType>(BS.getType().getTypePtrOrNull())) {
  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 llvm::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->getAs<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->isRValue()) && "-> base must be a pointer rvalue");
  788. MemberExpr *E =
  789. MemberExpr::Create(Context, Base, IsArrow, OpLoc, NNS, TemplateKWLoc,
  790. Member, FoundDecl, MemberNameInfo, TemplateArgs, Ty,
  791. VK, OK, getNonOdrUseReasonInCurrentContext(Member));
  792. E->setHadMultipleCandidates(HadMultipleCandidates);
  793. MarkMemberReferenced(E);
  794. return E;
  795. }
  796. /// Determine if the given scope is within a function-try-block handler.
  797. static bool IsInFnTryBlockHandler(const Scope *S) {
  798. // Walk the scope stack until finding a FnTryCatchScope, or leave the
  799. // function scope. If a FnTryCatchScope is found, check whether the TryScope
  800. // flag is set. If it is not, it's a function-try-block handler.
  801. for (; S != S->getFnParent(); S = S->getParent()) {
  802. if (S->getFlags() & Scope::FnTryCatchScope)
  803. return (S->getFlags() & Scope::TryScope) != Scope::TryScope;
  804. }
  805. return false;
  806. }
  807. static VarDecl *
  808. getVarTemplateSpecialization(Sema &S, VarTemplateDecl *VarTempl,
  809. const TemplateArgumentListInfo *TemplateArgs,
  810. const DeclarationNameInfo &MemberNameInfo,
  811. SourceLocation TemplateKWLoc) {
  812. if (!TemplateArgs) {
  813. S.diagnoseMissingTemplateArguments(TemplateName(VarTempl),
  814. MemberNameInfo.getBeginLoc());
  815. return nullptr;
  816. }
  817. DeclResult VDecl = S.CheckVarTemplateId(
  818. VarTempl, TemplateKWLoc, MemberNameInfo.getLoc(), *TemplateArgs);
  819. if (VDecl.isInvalid())
  820. return nullptr;
  821. VarDecl *Var = cast<VarDecl>(VDecl.get());
  822. if (!Var->getTemplateSpecializationKind())
  823. Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
  824. MemberNameInfo.getLoc());
  825. return Var;
  826. }
  827. ExprResult
  828. Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
  829. SourceLocation OpLoc, bool IsArrow,
  830. const CXXScopeSpec &SS,
  831. SourceLocation TemplateKWLoc,
  832. NamedDecl *FirstQualifierInScope,
  833. LookupResult &R,
  834. const TemplateArgumentListInfo *TemplateArgs,
  835. const Scope *S,
  836. bool SuppressQualifierCheck,
  837. ActOnMemberAccessExtraArgs *ExtraArgs) {
  838. QualType BaseType = BaseExprType;
  839. if (IsArrow) {
  840. assert(BaseType->isPointerType());
  841. BaseType = BaseType->castAs<PointerType>()->getPointeeType();
  842. }
  843. R.setBaseObjectType(BaseType);
  844. // C++1z [expr.ref]p2:
  845. // For the first option (dot) the first expression shall be a glvalue [...]
  846. if (!IsArrow && BaseExpr && BaseExpr->isRValue()) {
  847. ExprResult Converted = TemporaryMaterializationConversion(BaseExpr);
  848. if (Converted.isInvalid())
  849. return ExprError();
  850. BaseExpr = Converted.get();
  851. }
  852. const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
  853. DeclarationName MemberName = MemberNameInfo.getName();
  854. SourceLocation MemberLoc = MemberNameInfo.getLoc();
  855. if (R.isAmbiguous())
  856. return ExprError();
  857. // [except.handle]p10: Referring to any non-static member or base class of an
  858. // object in the handler for a function-try-block of a constructor or
  859. // destructor for that object results in undefined behavior.
  860. const auto *FD = getCurFunctionDecl();
  861. if (S && BaseExpr && FD &&
  862. (isa<CXXDestructorDecl>(FD) || isa<CXXConstructorDecl>(FD)) &&
  863. isa<CXXThisExpr>(BaseExpr->IgnoreImpCasts()) &&
  864. IsInFnTryBlockHandler(S))
  865. Diag(MemberLoc, diag::warn_cdtor_function_try_handler_mem_expr)
  866. << isa<CXXDestructorDecl>(FD);
  867. if (R.empty()) {
  868. // Rederive where we looked up.
  869. DeclContext *DC = (SS.isSet()
  870. ? computeDeclContext(SS, false)
  871. : BaseType->getAs<RecordType>()->getDecl());
  872. if (ExtraArgs) {
  873. ExprResult RetryExpr;
  874. if (!IsArrow && BaseExpr) {
  875. SFINAETrap Trap(*this, true);
  876. ParsedType ObjectType;
  877. bool MayBePseudoDestructor = false;
  878. RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
  879. OpLoc, tok::arrow, ObjectType,
  880. MayBePseudoDestructor);
  881. if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
  882. CXXScopeSpec TempSS(SS);
  883. RetryExpr = ActOnMemberAccessExpr(
  884. ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
  885. TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl);
  886. }
  887. if (Trap.hasErrorOccurred())
  888. RetryExpr = ExprError();
  889. }
  890. if (RetryExpr.isUsable()) {
  891. Diag(OpLoc, diag::err_no_member_overloaded_arrow)
  892. << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
  893. return RetryExpr;
  894. }
  895. }
  896. Diag(R.getNameLoc(), diag::err_no_member)
  897. << MemberName << DC
  898. << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
  899. return ExprError();
  900. }
  901. // Diagnose lookups that find only declarations from a non-base
  902. // type. This is possible for either qualified lookups (which may
  903. // have been qualified with an unrelated type) or implicit member
  904. // expressions (which were found with unqualified lookup and thus
  905. // may have come from an enclosing scope). Note that it's okay for
  906. // lookup to find declarations from a non-base type as long as those
  907. // aren't the ones picked by overload resolution.
  908. if ((SS.isSet() || !BaseExpr ||
  909. (isa<CXXThisExpr>(BaseExpr) &&
  910. cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
  911. !SuppressQualifierCheck &&
  912. CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
  913. return ExprError();
  914. // Construct an unresolved result if we in fact got an unresolved
  915. // result.
  916. if (R.isOverloadedResult() || R.isUnresolvableResult()) {
  917. // Suppress any lookup-related diagnostics; we'll do these when we
  918. // pick a member.
  919. R.suppressDiagnostics();
  920. UnresolvedMemberExpr *MemExpr
  921. = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
  922. BaseExpr, BaseExprType,
  923. IsArrow, OpLoc,
  924. SS.getWithLocInContext(Context),
  925. TemplateKWLoc, MemberNameInfo,
  926. TemplateArgs, R.begin(), R.end());
  927. return MemExpr;
  928. }
  929. assert(R.isSingleResult());
  930. DeclAccessPair FoundDecl = R.begin().getPair();
  931. NamedDecl *MemberDecl = R.getFoundDecl();
  932. // FIXME: diagnose the presence of template arguments now.
  933. // If the decl being referenced had an error, return an error for this
  934. // sub-expr without emitting another error, in order to avoid cascading
  935. // error cases.
  936. if (MemberDecl->isInvalidDecl())
  937. return ExprError();
  938. // Handle the implicit-member-access case.
  939. if (!BaseExpr) {
  940. // If this is not an instance member, convert to a non-member access.
  941. if (!MemberDecl->isCXXInstanceMember()) {
  942. // If this is a variable template, get the instantiated variable
  943. // declaration corresponding to the supplied template arguments
  944. // (while emitting diagnostics as necessary) that will be referenced
  945. // by this expression.
  946. assert((!TemplateArgs || isa<VarTemplateDecl>(MemberDecl)) &&
  947. "How did we get template arguments here sans a variable template");
  948. if (isa<VarTemplateDecl>(MemberDecl)) {
  949. MemberDecl = getVarTemplateSpecialization(
  950. *this, cast<VarTemplateDecl>(MemberDecl), TemplateArgs,
  951. R.getLookupNameInfo(), TemplateKWLoc);
  952. if (!MemberDecl)
  953. return ExprError();
  954. }
  955. return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl,
  956. FoundDecl, TemplateArgs);
  957. }
  958. SourceLocation Loc = R.getNameLoc();
  959. if (SS.getRange().isValid())
  960. Loc = SS.getRange().getBegin();
  961. BaseExpr = BuildCXXThisExpr(Loc, BaseExprType, /*IsImplicit=*/true);
  962. }
  963. // Check the use of this member.
  964. if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
  965. return ExprError();
  966. if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
  967. return BuildFieldReferenceExpr(BaseExpr, IsArrow, OpLoc, SS, FD, FoundDecl,
  968. MemberNameInfo);
  969. if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
  970. return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
  971. MemberNameInfo);
  972. if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
  973. // We may have found a field within an anonymous union or struct
  974. // (C++ [class.union]).
  975. return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
  976. FoundDecl, BaseExpr,
  977. OpLoc);
  978. if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
  979. return BuildMemberExpr(BaseExpr, IsArrow, OpLoc, &SS, TemplateKWLoc, Var,
  980. FoundDecl, /*HadMultipleCandidates=*/false,
  981. MemberNameInfo, Var->getType().getNonReferenceType(),
  982. VK_LValue, OK_Ordinary);
  983. }
  984. if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
  985. ExprValueKind valueKind;
  986. QualType type;
  987. if (MemberFn->isInstance()) {
  988. valueKind = VK_RValue;
  989. type = Context.BoundMemberTy;
  990. } else {
  991. valueKind = VK_LValue;
  992. type = MemberFn->getType();
  993. }
  994. return BuildMemberExpr(BaseExpr, IsArrow, OpLoc, &SS, TemplateKWLoc,
  995. MemberFn, FoundDecl, /*HadMultipleCandidates=*/false,
  996. MemberNameInfo, type, valueKind, OK_Ordinary);
  997. }
  998. assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
  999. if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
  1000. return BuildMemberExpr(BaseExpr, IsArrow, OpLoc, &SS, TemplateKWLoc, Enum,
  1001. FoundDecl, /*HadMultipleCandidates=*/false,
  1002. MemberNameInfo, Enum->getType(), VK_RValue,
  1003. OK_Ordinary);
  1004. }
  1005. if (VarTemplateDecl *VarTempl = dyn_cast<VarTemplateDecl>(MemberDecl)) {
  1006. if (VarDecl *Var = getVarTemplateSpecialization(
  1007. *this, VarTempl, TemplateArgs, MemberNameInfo, TemplateKWLoc))
  1008. return BuildMemberExpr(
  1009. BaseExpr, IsArrow, OpLoc, &SS, TemplateKWLoc, Var, FoundDecl,
  1010. /*HadMultipleCandidates=*/false, MemberNameInfo,
  1011. Var->getType().getNonReferenceType(), VK_LValue, OK_Ordinary);
  1012. return ExprError();
  1013. }
  1014. // We found something that we didn't expect. Complain.
  1015. if (isa<TypeDecl>(MemberDecl))
  1016. Diag(MemberLoc, diag::err_typecheck_member_reference_type)
  1017. << MemberName << BaseType << int(IsArrow);
  1018. else
  1019. Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
  1020. << MemberName << BaseType << int(IsArrow);
  1021. Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
  1022. << MemberName;
  1023. R.suppressDiagnostics();
  1024. return ExprError();
  1025. }
  1026. /// Given that normal member access failed on the given expression,
  1027. /// and given that the expression's type involves builtin-id or
  1028. /// builtin-Class, decide whether substituting in the redefinition
  1029. /// types would be profitable. The redefinition type is whatever
  1030. /// this translation unit tried to typedef to id/Class; we store
  1031. /// it to the side and then re-use it in places like this.
  1032. static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
  1033. const ObjCObjectPointerType *opty
  1034. = base.get()->getType()->getAs<ObjCObjectPointerType>();
  1035. if (!opty) return false;
  1036. const ObjCObjectType *ty = opty->getObjectType();
  1037. QualType redef;
  1038. if (ty->isObjCId()) {
  1039. redef = S.Context.getObjCIdRedefinitionType();
  1040. } else if (ty->isObjCClass()) {
  1041. redef = S.Context.getObjCClassRedefinitionType();
  1042. } else {
  1043. return false;
  1044. }
  1045. // Do the substitution as long as the redefinition type isn't just a
  1046. // possibly-qualified pointer to builtin-id or builtin-Class again.
  1047. opty = redef->getAs<ObjCObjectPointerType>();
  1048. if (opty && !opty->getObjectType()->getInterface())
  1049. return false;
  1050. base = S.ImpCastExprToType(base.get(), redef, CK_BitCast);
  1051. return true;
  1052. }
  1053. static bool isRecordType(QualType T) {
  1054. return T->isRecordType();
  1055. }
  1056. static bool isPointerToRecordType(QualType T) {
  1057. if (const PointerType *PT = T->getAs<PointerType>())
  1058. return PT->getPointeeType()->isRecordType();
  1059. return false;
  1060. }
  1061. /// Perform conversions on the LHS of a member access expression.
  1062. ExprResult
  1063. Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
  1064. if (IsArrow && !Base->getType()->isFunctionType())
  1065. return DefaultFunctionArrayLvalueConversion(Base);
  1066. return CheckPlaceholderExpr(Base);
  1067. }
  1068. /// Look up the given member of the given non-type-dependent
  1069. /// expression. This can return in one of two ways:
  1070. /// * If it returns a sentinel null-but-valid result, the caller will
  1071. /// assume that lookup was performed and the results written into
  1072. /// the provided structure. It will take over from there.
  1073. /// * Otherwise, the returned expression will be produced in place of
  1074. /// an ordinary member expression.
  1075. ///
  1076. /// The ObjCImpDecl bit is a gross hack that will need to be properly
  1077. /// fixed for ObjC++.
  1078. static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
  1079. ExprResult &BaseExpr, bool &IsArrow,
  1080. SourceLocation OpLoc, CXXScopeSpec &SS,
  1081. Decl *ObjCImpDecl, bool HasTemplateArgs,
  1082. SourceLocation TemplateKWLoc) {
  1083. assert(BaseExpr.get() && "no base expression");
  1084. // Perform default conversions.
  1085. BaseExpr = S.PerformMemberExprBaseConversion(BaseExpr.get(), IsArrow);
  1086. if (BaseExpr.isInvalid())
  1087. return ExprError();
  1088. QualType BaseType = BaseExpr.get()->getType();
  1089. assert(!BaseType->isDependentType());
  1090. DeclarationName MemberName = R.getLookupName();
  1091. SourceLocation MemberLoc = R.getNameLoc();
  1092. // For later type-checking purposes, turn arrow accesses into dot
  1093. // accesses. The only access type we support that doesn't follow
  1094. // the C equivalence "a->b === (*a).b" is ObjC property accesses,
  1095. // and those never use arrows, so this is unaffected.
  1096. if (IsArrow) {
  1097. if (const PointerType *Ptr = BaseType->getAs<PointerType>())
  1098. BaseType = Ptr->getPointeeType();
  1099. else if (const ObjCObjectPointerType *Ptr
  1100. = BaseType->getAs<ObjCObjectPointerType>())
  1101. BaseType = Ptr->getPointeeType();
  1102. else if (BaseType->isRecordType()) {
  1103. // Recover from arrow accesses to records, e.g.:
  1104. // struct MyRecord foo;
  1105. // foo->bar
  1106. // This is actually well-formed in C++ if MyRecord has an
  1107. // overloaded operator->, but that should have been dealt with
  1108. // by now--or a diagnostic message already issued if a problem
  1109. // was encountered while looking for the overloaded operator->.
  1110. if (!S.getLangOpts().CPlusPlus) {
  1111. S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
  1112. << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
  1113. << FixItHint::CreateReplacement(OpLoc, ".");
  1114. }
  1115. IsArrow = false;
  1116. } else if (BaseType->isFunctionType()) {
  1117. goto fail;
  1118. } else {
  1119. S.Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
  1120. << BaseType << BaseExpr.get()->getSourceRange();
  1121. return ExprError();
  1122. }
  1123. }
  1124. // Handle field access to simple records.
  1125. if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
  1126. TypoExpr *TE = nullptr;
  1127. if (LookupMemberExprInRecord(S, R, BaseExpr.get(), RTy, OpLoc, IsArrow, SS,
  1128. HasTemplateArgs, TemplateKWLoc, TE))
  1129. return ExprError();
  1130. // Returning valid-but-null is how we indicate to the caller that
  1131. // the lookup result was filled in. If typo correction was attempted and
  1132. // failed, the lookup result will have been cleared--that combined with the
  1133. // valid-but-null ExprResult will trigger the appropriate diagnostics.
  1134. return ExprResult(TE);
  1135. }
  1136. // Handle ivar access to Objective-C objects.
  1137. if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
  1138. if (!SS.isEmpty() && !SS.isInvalid()) {
  1139. S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
  1140. << 1 << SS.getScopeRep()
  1141. << FixItHint::CreateRemoval(SS.getRange());
  1142. SS.clear();
  1143. }
  1144. IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
  1145. // There are three cases for the base type:
  1146. // - builtin id (qualified or unqualified)
  1147. // - builtin Class (qualified or unqualified)
  1148. // - an interface
  1149. ObjCInterfaceDecl *IDecl = OTy->getInterface();
  1150. if (!IDecl) {
  1151. if (S.getLangOpts().ObjCAutoRefCount &&
  1152. (OTy->isObjCId() || OTy->isObjCClass()))
  1153. goto fail;
  1154. // There's an implicit 'isa' ivar on all objects.
  1155. // But we only actually find it this way on objects of type 'id',
  1156. // apparently.
  1157. if (OTy->isObjCId() && Member->isStr("isa"))
  1158. return new (S.Context) ObjCIsaExpr(BaseExpr.get(), IsArrow, MemberLoc,
  1159. OpLoc, S.Context.getObjCClassType());
  1160. if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
  1161. return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
  1162. ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
  1163. goto fail;
  1164. }
  1165. if (S.RequireCompleteType(OpLoc, BaseType,
  1166. diag::err_typecheck_incomplete_tag,
  1167. BaseExpr.get()))
  1168. return ExprError();
  1169. ObjCInterfaceDecl *ClassDeclared = nullptr;
  1170. ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
  1171. if (!IV) {
  1172. // Attempt to correct for typos in ivar names.
  1173. DeclFilterCCC<ObjCIvarDecl> Validator{};
  1174. Validator.IsObjCIvarLookup = IsArrow;
  1175. if (TypoCorrection Corrected = S.CorrectTypo(
  1176. R.getLookupNameInfo(), Sema::LookupMemberName, nullptr, nullptr,
  1177. Validator, Sema::CTK_ErrorRecovery, IDecl)) {
  1178. IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
  1179. S.diagnoseTypo(
  1180. Corrected,
  1181. S.PDiag(diag::err_typecheck_member_reference_ivar_suggest)
  1182. << IDecl->getDeclName() << MemberName);
  1183. // Figure out the class that declares the ivar.
  1184. assert(!ClassDeclared);
  1185. Decl *D = cast<Decl>(IV->getDeclContext());
  1186. if (auto *Category = dyn_cast<ObjCCategoryDecl>(D))
  1187. D = Category->getClassInterface();
  1188. if (auto *Implementation = dyn_cast<ObjCImplementationDecl>(D))
  1189. ClassDeclared = Implementation->getClassInterface();
  1190. else if (auto *Interface = dyn_cast<ObjCInterfaceDecl>(D))
  1191. ClassDeclared = Interface;
  1192. assert(ClassDeclared && "cannot query interface");
  1193. } else {
  1194. if (IsArrow &&
  1195. IDecl->FindPropertyDeclaration(
  1196. Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
  1197. S.Diag(MemberLoc, diag::err_property_found_suggest)
  1198. << Member << BaseExpr.get()->getType()
  1199. << FixItHint::CreateReplacement(OpLoc, ".");
  1200. return ExprError();
  1201. }
  1202. S.Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
  1203. << IDecl->getDeclName() << MemberName
  1204. << BaseExpr.get()->getSourceRange();
  1205. return ExprError();
  1206. }
  1207. }
  1208. assert(ClassDeclared);
  1209. // If the decl being referenced had an error, return an error for this
  1210. // sub-expr without emitting another error, in order to avoid cascading
  1211. // error cases.
  1212. if (IV->isInvalidDecl())
  1213. return ExprError();
  1214. // Check whether we can reference this field.
  1215. if (S.DiagnoseUseOfDecl(IV, MemberLoc))
  1216. return ExprError();
  1217. if (IV->getAccessControl() != ObjCIvarDecl::Public &&
  1218. IV->getAccessControl() != ObjCIvarDecl::Package) {
  1219. ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
  1220. if (ObjCMethodDecl *MD = S.getCurMethodDecl())
  1221. ClassOfMethodDecl = MD->getClassInterface();
  1222. else if (ObjCImpDecl && S.getCurFunctionDecl()) {
  1223. // Case of a c-function declared inside an objc implementation.
  1224. // FIXME: For a c-style function nested inside an objc implementation
  1225. // class, there is no implementation context available, so we pass
  1226. // down the context as argument to this routine. Ideally, this context
  1227. // need be passed down in the AST node and somehow calculated from the
  1228. // AST for a function decl.
  1229. if (ObjCImplementationDecl *IMPD =
  1230. dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
  1231. ClassOfMethodDecl = IMPD->getClassInterface();
  1232. else if (ObjCCategoryImplDecl* CatImplClass =
  1233. dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
  1234. ClassOfMethodDecl = CatImplClass->getClassInterface();
  1235. }
  1236. if (!S.getLangOpts().DebuggerSupport) {
  1237. if (IV->getAccessControl() == ObjCIvarDecl::Private) {
  1238. if (!declaresSameEntity(ClassDeclared, IDecl) ||
  1239. !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
  1240. S.Diag(MemberLoc, diag::err_private_ivar_access)
  1241. << IV->getDeclName();
  1242. } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
  1243. // @protected
  1244. S.Diag(MemberLoc, diag::err_protected_ivar_access)
  1245. << IV->getDeclName();
  1246. }
  1247. }
  1248. bool warn = true;
  1249. if (S.getLangOpts().ObjCWeak) {
  1250. Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
  1251. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
  1252. if (UO->getOpcode() == UO_Deref)
  1253. BaseExp = UO->getSubExpr()->IgnoreParenCasts();
  1254. if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
  1255. if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
  1256. S.Diag(DE->getLocation(), diag::err_arc_weak_ivar_access);
  1257. warn = false;
  1258. }
  1259. }
  1260. if (warn) {
  1261. if (ObjCMethodDecl *MD = S.getCurMethodDecl()) {
  1262. ObjCMethodFamily MF = MD->getMethodFamily();
  1263. warn = (MF != OMF_init && MF != OMF_dealloc &&
  1264. MF != OMF_finalize &&
  1265. !S.IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
  1266. }
  1267. if (warn)
  1268. S.Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
  1269. }
  1270. ObjCIvarRefExpr *Result = new (S.Context) ObjCIvarRefExpr(
  1271. IV, IV->getUsageType(BaseType), MemberLoc, OpLoc, BaseExpr.get(),
  1272. IsArrow);
  1273. if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
  1274. if (!S.isUnevaluatedContext() &&
  1275. !S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, MemberLoc))
  1276. S.getCurFunction()->recordUseOfWeak(Result);
  1277. }
  1278. return Result;
  1279. }
  1280. // Objective-C property access.
  1281. const ObjCObjectPointerType *OPT;
  1282. if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
  1283. if (!SS.isEmpty() && !SS.isInvalid()) {
  1284. S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
  1285. << 0 << SS.getScopeRep() << FixItHint::CreateRemoval(SS.getRange());
  1286. SS.clear();
  1287. }
  1288. // This actually uses the base as an r-value.
  1289. BaseExpr = S.DefaultLvalueConversion(BaseExpr.get());
  1290. if (BaseExpr.isInvalid())
  1291. return ExprError();
  1292. assert(S.Context.hasSameUnqualifiedType(BaseType,
  1293. BaseExpr.get()->getType()));
  1294. IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
  1295. const ObjCObjectType *OT = OPT->getObjectType();
  1296. // id, with and without qualifiers.
  1297. if (OT->isObjCId()) {
  1298. // Check protocols on qualified interfaces.
  1299. Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
  1300. if (Decl *PMDecl =
  1301. FindGetterSetterNameDecl(OPT, Member, Sel, S.Context)) {
  1302. if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
  1303. // Check the use of this declaration
  1304. if (S.DiagnoseUseOfDecl(PD, MemberLoc))
  1305. return ExprError();
  1306. return new (S.Context)
  1307. ObjCPropertyRefExpr(PD, S.Context.PseudoObjectTy, VK_LValue,
  1308. OK_ObjCProperty, MemberLoc, BaseExpr.get());
  1309. }
  1310. if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
  1311. Selector SetterSel =
  1312. SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
  1313. S.PP.getSelectorTable(),
  1314. Member);
  1315. ObjCMethodDecl *SMD = nullptr;
  1316. if (Decl *SDecl = FindGetterSetterNameDecl(OPT,
  1317. /*Property id*/ nullptr,
  1318. SetterSel, S.Context))
  1319. SMD = dyn_cast<ObjCMethodDecl>(SDecl);
  1320. return new (S.Context)
  1321. ObjCPropertyRefExpr(OMD, SMD, S.Context.PseudoObjectTy, VK_LValue,
  1322. OK_ObjCProperty, MemberLoc, BaseExpr.get());
  1323. }
  1324. }
  1325. // Use of id.member can only be for a property reference. Do not
  1326. // use the 'id' redefinition in this case.
  1327. if (IsArrow && ShouldTryAgainWithRedefinitionType(S, BaseExpr))
  1328. return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
  1329. ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
  1330. return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
  1331. << MemberName << BaseType);
  1332. }
  1333. // 'Class', unqualified only.
  1334. if (OT->isObjCClass()) {
  1335. // Only works in a method declaration (??!).
  1336. ObjCMethodDecl *MD = S.getCurMethodDecl();
  1337. if (!MD) {
  1338. if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
  1339. return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
  1340. ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
  1341. goto fail;
  1342. }
  1343. // Also must look for a getter name which uses property syntax.
  1344. Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
  1345. ObjCInterfaceDecl *IFace = MD->getClassInterface();
  1346. if (!IFace)
  1347. goto fail;
  1348. ObjCMethodDecl *Getter;
  1349. if ((Getter = IFace->lookupClassMethod(Sel))) {
  1350. // Check the use of this method.
  1351. if (S.DiagnoseUseOfDecl(Getter, MemberLoc))
  1352. return ExprError();
  1353. } else
  1354. Getter = IFace->lookupPrivateMethod(Sel, false);
  1355. // If we found a getter then this may be a valid dot-reference, we
  1356. // will look for the matching setter, in case it is needed.
  1357. Selector SetterSel =
  1358. SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
  1359. S.PP.getSelectorTable(),
  1360. Member);
  1361. ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
  1362. if (!Setter) {
  1363. // If this reference is in an @implementation, also check for 'private'
  1364. // methods.
  1365. Setter = IFace->lookupPrivateMethod(SetterSel, false);
  1366. }
  1367. if (Setter && S.DiagnoseUseOfDecl(Setter, MemberLoc))
  1368. return ExprError();
  1369. if (Getter || Setter) {
  1370. return new (S.Context) ObjCPropertyRefExpr(
  1371. Getter, Setter, S.Context.PseudoObjectTy, VK_LValue,
  1372. OK_ObjCProperty, MemberLoc, BaseExpr.get());
  1373. }
  1374. if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
  1375. return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
  1376. ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
  1377. return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
  1378. << MemberName << BaseType);
  1379. }
  1380. // Normal property access.
  1381. return S.HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc, MemberName,
  1382. MemberLoc, SourceLocation(), QualType(),
  1383. false);
  1384. }
  1385. // Handle 'field access' to vectors, such as 'V.xx'.
  1386. if (BaseType->isExtVectorType()) {
  1387. // FIXME: this expr should store IsArrow.
  1388. IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
  1389. ExprValueKind VK;
  1390. if (IsArrow)
  1391. VK = VK_LValue;
  1392. else {
  1393. if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(BaseExpr.get()))
  1394. VK = POE->getSyntacticForm()->getValueKind();
  1395. else
  1396. VK = BaseExpr.get()->getValueKind();
  1397. }
  1398. QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
  1399. Member, MemberLoc);
  1400. if (ret.isNull())
  1401. return ExprError();
  1402. Qualifiers BaseQ =
  1403. S.Context.getCanonicalType(BaseExpr.get()->getType()).getQualifiers();
  1404. ret = S.Context.getQualifiedType(ret, BaseQ);
  1405. return new (S.Context)
  1406. ExtVectorElementExpr(ret, VK, BaseExpr.get(), *Member, MemberLoc);
  1407. }
  1408. // Adjust builtin-sel to the appropriate redefinition type if that's
  1409. // not just a pointer to builtin-sel again.
  1410. if (IsArrow && BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
  1411. !S.Context.getObjCSelRedefinitionType()->isObjCSelType()) {
  1412. BaseExpr = S.ImpCastExprToType(
  1413. BaseExpr.get(), S.Context.getObjCSelRedefinitionType(), CK_BitCast);
  1414. return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
  1415. ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
  1416. }
  1417. // Failure cases.
  1418. fail:
  1419. // Recover from dot accesses to pointers, e.g.:
  1420. // type *foo;
  1421. // foo.bar
  1422. // This is actually well-formed in two cases:
  1423. // - 'type' is an Objective C type
  1424. // - 'bar' is a pseudo-destructor name which happens to refer to
  1425. // the appropriate pointer type
  1426. if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
  1427. if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
  1428. MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
  1429. S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
  1430. << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
  1431. << FixItHint::CreateReplacement(OpLoc, "->");
  1432. // Recurse as an -> access.
  1433. IsArrow = true;
  1434. return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
  1435. ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
  1436. }
  1437. }
  1438. // If the user is trying to apply -> or . to a function name, it's probably
  1439. // because they forgot parentheses to call that function.
  1440. if (S.tryToRecoverWithCall(
  1441. BaseExpr, S.PDiag(diag::err_member_reference_needs_call),
  1442. /*complain*/ false,
  1443. IsArrow ? &isPointerToRecordType : &isRecordType)) {
  1444. if (BaseExpr.isInvalid())
  1445. return ExprError();
  1446. BaseExpr = S.DefaultFunctionArrayConversion(BaseExpr.get());
  1447. return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
  1448. ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
  1449. }
  1450. S.Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
  1451. << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
  1452. return ExprError();
  1453. }
  1454. /// The main callback when the parser finds something like
  1455. /// expression . [nested-name-specifier] identifier
  1456. /// expression -> [nested-name-specifier] identifier
  1457. /// where 'identifier' encompasses a fairly broad spectrum of
  1458. /// possibilities, including destructor and operator references.
  1459. ///
  1460. /// \param OpKind either tok::arrow or tok::period
  1461. /// \param ObjCImpDecl the current Objective-C \@implementation
  1462. /// decl; this is an ugly hack around the fact that Objective-C
  1463. /// \@implementations aren't properly put in the context chain
  1464. ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
  1465. SourceLocation OpLoc,
  1466. tok::TokenKind OpKind,
  1467. CXXScopeSpec &SS,
  1468. SourceLocation TemplateKWLoc,
  1469. UnqualifiedId &Id,
  1470. Decl *ObjCImpDecl) {
  1471. if (SS.isSet() && SS.isInvalid())
  1472. return ExprError();
  1473. // Warn about the explicit constructor calls Microsoft extension.
  1474. if (getLangOpts().MicrosoftExt &&
  1475. Id.getKind() == UnqualifiedIdKind::IK_ConstructorName)
  1476. Diag(Id.getSourceRange().getBegin(),
  1477. diag::ext_ms_explicit_constructor_call);
  1478. TemplateArgumentListInfo TemplateArgsBuffer;
  1479. // Decompose the name into its component parts.
  1480. DeclarationNameInfo NameInfo;
  1481. const TemplateArgumentListInfo *TemplateArgs;
  1482. DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
  1483. NameInfo, TemplateArgs);
  1484. DeclarationName Name = NameInfo.getName();
  1485. bool IsArrow = (OpKind == tok::arrow);
  1486. NamedDecl *FirstQualifierInScope
  1487. = (!SS.isSet() ? nullptr : FindFirstQualifierInScope(S, SS.getScopeRep()));
  1488. // This is a postfix expression, so get rid of ParenListExprs.
  1489. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
  1490. if (Result.isInvalid()) return ExprError();
  1491. Base = Result.get();
  1492. if (Base->getType()->isDependentType() || Name.isDependentName() ||
  1493. isDependentScopeSpecifier(SS)) {
  1494. return ActOnDependentMemberExpr(Base, Base->getType(), IsArrow, OpLoc, SS,
  1495. TemplateKWLoc, FirstQualifierInScope,
  1496. NameInfo, TemplateArgs);
  1497. }
  1498. ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl};
  1499. ExprResult Res = BuildMemberReferenceExpr(
  1500. Base, Base->getType(), OpLoc, IsArrow, SS, TemplateKWLoc,
  1501. FirstQualifierInScope, NameInfo, TemplateArgs, S, &ExtraArgs);
  1502. if (!Res.isInvalid() && isa<MemberExpr>(Res.get()))
  1503. CheckMemberAccessOfNoDeref(cast<MemberExpr>(Res.get()));
  1504. return Res;
  1505. }
  1506. void Sema::CheckMemberAccessOfNoDeref(const MemberExpr *E) {
  1507. QualType ResultTy = E->getType();
  1508. // Do not warn on member accesses to arrays since this returns an array
  1509. // lvalue and does not actually dereference memory.
  1510. if (isa<ArrayType>(ResultTy))
  1511. return;
  1512. if (E->isArrow()) {
  1513. if (const auto *Ptr = dyn_cast<PointerType>(
  1514. E->getBase()->getType().getDesugaredType(Context))) {
  1515. if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
  1516. ExprEvalContexts.back().PossibleDerefs.insert(E);
  1517. }
  1518. }
  1519. }
  1520. ExprResult
  1521. Sema::BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
  1522. SourceLocation OpLoc, const CXXScopeSpec &SS,
  1523. FieldDecl *Field, DeclAccessPair FoundDecl,
  1524. const DeclarationNameInfo &MemberNameInfo) {
  1525. // x.a is an l-value if 'a' has a reference type. Otherwise:
  1526. // x.a is an l-value/x-value/pr-value if the base is (and note
  1527. // that *x is always an l-value), except that if the base isn't
  1528. // an ordinary object then we must have an rvalue.
  1529. ExprValueKind VK = VK_LValue;
  1530. ExprObjectKind OK = OK_Ordinary;
  1531. if (!IsArrow) {
  1532. if (BaseExpr->getObjectKind() == OK_Ordinary)
  1533. VK = BaseExpr->getValueKind();
  1534. else
  1535. VK = VK_RValue;
  1536. }
  1537. if (VK != VK_RValue && Field->isBitField())
  1538. OK = OK_BitField;
  1539. // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
  1540. QualType MemberType = Field->getType();
  1541. if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
  1542. MemberType = Ref->getPointeeType();
  1543. VK = VK_LValue;
  1544. } else {
  1545. QualType BaseType = BaseExpr->getType();
  1546. if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
  1547. Qualifiers BaseQuals = BaseType.getQualifiers();
  1548. // GC attributes are never picked up by members.
  1549. BaseQuals.removeObjCGCAttr();
  1550. // CVR attributes from the base are picked up by members,
  1551. // except that 'mutable' members don't pick up 'const'.
  1552. if (Field->isMutable()) BaseQuals.removeConst();
  1553. Qualifiers MemberQuals =
  1554. Context.getCanonicalType(MemberType).getQualifiers();
  1555. assert(!MemberQuals.hasAddressSpace());
  1556. Qualifiers Combined = BaseQuals + MemberQuals;
  1557. if (Combined != MemberQuals)
  1558. MemberType = Context.getQualifiedType(MemberType, Combined);
  1559. }
  1560. auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
  1561. if (!(CurMethod && CurMethod->isDefaulted()))
  1562. UnusedPrivateFields.remove(Field);
  1563. ExprResult Base = PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
  1564. FoundDecl, Field);
  1565. if (Base.isInvalid())
  1566. return ExprError();
  1567. // Build a reference to a private copy for non-static data members in
  1568. // non-static member functions, privatized by OpenMP constructs.
  1569. if (getLangOpts().OpenMP && IsArrow &&
  1570. !CurContext->isDependentContext() &&
  1571. isa<CXXThisExpr>(Base.get()->IgnoreParenImpCasts())) {
  1572. if (auto *PrivateCopy = isOpenMPCapturedDecl(Field)) {
  1573. return getOpenMPCapturedExpr(PrivateCopy, VK, OK,
  1574. MemberNameInfo.getLoc());
  1575. }
  1576. }
  1577. return BuildMemberExpr(Base.get(), IsArrow, OpLoc, &SS,
  1578. /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl,
  1579. /*HadMultipleCandidates=*/false, MemberNameInfo,
  1580. MemberType, VK, OK);
  1581. }
  1582. /// Builds an implicit member access expression. The current context
  1583. /// is known to be an instance method, and the given unqualified lookup
  1584. /// set is known to contain only instance members, at least one of which
  1585. /// is from an appropriate type.
  1586. ExprResult
  1587. Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
  1588. SourceLocation TemplateKWLoc,
  1589. LookupResult &R,
  1590. const TemplateArgumentListInfo *TemplateArgs,
  1591. bool IsKnownInstance, const Scope *S) {
  1592. assert(!R.empty() && !R.isAmbiguous());
  1593. SourceLocation loc = R.getNameLoc();
  1594. // If this is known to be an instance access, go ahead and build an
  1595. // implicit 'this' expression now.
  1596. // 'this' expression now.
  1597. QualType ThisTy = getCurrentThisType();
  1598. assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
  1599. Expr *baseExpr = nullptr; // null signifies implicit access
  1600. if (IsKnownInstance) {
  1601. SourceLocation Loc = R.getNameLoc();
  1602. if (SS.getRange().isValid())
  1603. Loc = SS.getRange().getBegin();
  1604. baseExpr = BuildCXXThisExpr(loc, ThisTy, /*IsImplicit=*/true);
  1605. }
  1606. return BuildMemberReferenceExpr(baseExpr, ThisTy,
  1607. /*OpLoc*/ SourceLocation(),
  1608. /*IsArrow*/ true,
  1609. SS, TemplateKWLoc,
  1610. /*FirstQualifierInScope*/ nullptr,
  1611. R, TemplateArgs, S);
  1612. }