SemaExprMember.cpp 69 KB

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