SemaPseudoObject.cpp 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662
  1. //===--- SemaPseudoObject.cpp - Semantic Analysis for Pseudo-Objects ------===//
  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 for expressions involving
  11. // pseudo-object references. Pseudo-objects are conceptual objects
  12. // whose storage is entirely abstract and all accesses to which are
  13. // translated through some sort of abstraction barrier.
  14. //
  15. // For example, Objective-C objects can have "properties", either
  16. // declared or undeclared. A property may be accessed by writing
  17. // expr.prop
  18. // where 'expr' is an r-value of Objective-C pointer type and 'prop'
  19. // is the name of the property. If this expression is used in a context
  20. // needing an r-value, it is treated as if it were a message-send
  21. // of the associated 'getter' selector, typically:
  22. // [expr prop]
  23. // If it is used as the LHS of a simple assignment, it is treated
  24. // as a message-send of the associated 'setter' selector, typically:
  25. // [expr setProp: RHS]
  26. // If it is used as the LHS of a compound assignment, or the operand
  27. // of a unary increment or decrement, both are required; for example,
  28. // 'expr.prop *= 100' would be translated to:
  29. // [expr setProp: [expr prop] * 100]
  30. //
  31. //===----------------------------------------------------------------------===//
  32. #include "clang/Sema/SemaInternal.h"
  33. #include "clang/AST/ExprCXX.h"
  34. #include "clang/AST/ExprObjC.h"
  35. #include "clang/Basic/CharInfo.h"
  36. #include "clang/Lex/Preprocessor.h"
  37. #include "clang/Sema/Initialization.h"
  38. #include "clang/Sema/ScopeInfo.h"
  39. #include "llvm/ADT/SmallString.h"
  40. using namespace clang;
  41. using namespace sema;
  42. namespace {
  43. // Basically just a very focused copy of TreeTransform.
  44. struct Rebuilder {
  45. Sema &S;
  46. unsigned MSPropertySubscriptCount;
  47. typedef llvm::function_ref<Expr *(Expr *, unsigned)> SpecificRebuilderRefTy;
  48. const SpecificRebuilderRefTy &SpecificCallback;
  49. Rebuilder(Sema &S, const SpecificRebuilderRefTy &SpecificCallback)
  50. : S(S), MSPropertySubscriptCount(0),
  51. SpecificCallback(SpecificCallback) {}
  52. Expr *rebuildObjCPropertyRefExpr(ObjCPropertyRefExpr *refExpr) {
  53. // Fortunately, the constraint that we're rebuilding something
  54. // with a base limits the number of cases here.
  55. if (refExpr->isClassReceiver() || refExpr->isSuperReceiver())
  56. return refExpr;
  57. if (refExpr->isExplicitProperty()) {
  58. return new (S.Context) ObjCPropertyRefExpr(
  59. refExpr->getExplicitProperty(), refExpr->getType(),
  60. refExpr->getValueKind(), refExpr->getObjectKind(),
  61. refExpr->getLocation(), SpecificCallback(refExpr->getBase(), 0));
  62. }
  63. return new (S.Context) ObjCPropertyRefExpr(
  64. refExpr->getImplicitPropertyGetter(),
  65. refExpr->getImplicitPropertySetter(), refExpr->getType(),
  66. refExpr->getValueKind(), refExpr->getObjectKind(),
  67. refExpr->getLocation(), SpecificCallback(refExpr->getBase(), 0));
  68. }
  69. Expr *rebuildObjCSubscriptRefExpr(ObjCSubscriptRefExpr *refExpr) {
  70. assert(refExpr->getBaseExpr());
  71. assert(refExpr->getKeyExpr());
  72. return new (S.Context) ObjCSubscriptRefExpr(
  73. SpecificCallback(refExpr->getBaseExpr(), 0),
  74. SpecificCallback(refExpr->getKeyExpr(), 1), refExpr->getType(),
  75. refExpr->getValueKind(), refExpr->getObjectKind(),
  76. refExpr->getAtIndexMethodDecl(), refExpr->setAtIndexMethodDecl(),
  77. refExpr->getRBracket());
  78. }
  79. Expr *rebuildMSPropertyRefExpr(MSPropertyRefExpr *refExpr) {
  80. assert(refExpr->getBaseExpr());
  81. return new (S.Context) MSPropertyRefExpr(
  82. SpecificCallback(refExpr->getBaseExpr(), 0),
  83. refExpr->getPropertyDecl(), refExpr->isArrow(), refExpr->getType(),
  84. refExpr->getValueKind(), refExpr->getQualifierLoc(),
  85. refExpr->getMemberLoc());
  86. }
  87. Expr *rebuildMSPropertySubscriptExpr(MSPropertySubscriptExpr *refExpr) {
  88. assert(refExpr->getBase());
  89. assert(refExpr->getIdx());
  90. auto *NewBase = rebuild(refExpr->getBase());
  91. ++MSPropertySubscriptCount;
  92. return new (S.Context) MSPropertySubscriptExpr(
  93. NewBase,
  94. SpecificCallback(refExpr->getIdx(), MSPropertySubscriptCount),
  95. refExpr->getType(), refExpr->getValueKind(), refExpr->getObjectKind(),
  96. refExpr->getRBracketLoc());
  97. }
  98. Expr *rebuild(Expr *e) {
  99. // Fast path: nothing to look through.
  100. if (auto *PRE = dyn_cast<ObjCPropertyRefExpr>(e))
  101. return rebuildObjCPropertyRefExpr(PRE);
  102. if (auto *SRE = dyn_cast<ObjCSubscriptRefExpr>(e))
  103. return rebuildObjCSubscriptRefExpr(SRE);
  104. if (auto *MSPRE = dyn_cast<MSPropertyRefExpr>(e))
  105. return rebuildMSPropertyRefExpr(MSPRE);
  106. if (auto *MSPSE = dyn_cast<MSPropertySubscriptExpr>(e))
  107. return rebuildMSPropertySubscriptExpr(MSPSE);
  108. // Otherwise, we should look through and rebuild anything that
  109. // IgnoreParens would.
  110. if (ParenExpr *parens = dyn_cast<ParenExpr>(e)) {
  111. e = rebuild(parens->getSubExpr());
  112. return new (S.Context) ParenExpr(parens->getLParen(),
  113. parens->getRParen(),
  114. e);
  115. }
  116. if (UnaryOperator *uop = dyn_cast<UnaryOperator>(e)) {
  117. assert(uop->getOpcode() == UO_Extension);
  118. e = rebuild(uop->getSubExpr());
  119. return new (S.Context) UnaryOperator(e, uop->getOpcode(),
  120. uop->getType(),
  121. uop->getValueKind(),
  122. uop->getObjectKind(),
  123. uop->getOperatorLoc());
  124. }
  125. if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
  126. assert(!gse->isResultDependent());
  127. unsigned resultIndex = gse->getResultIndex();
  128. unsigned numAssocs = gse->getNumAssocs();
  129. SmallVector<Expr*, 8> assocs(numAssocs);
  130. SmallVector<TypeSourceInfo*, 8> assocTypes(numAssocs);
  131. for (unsigned i = 0; i != numAssocs; ++i) {
  132. Expr *assoc = gse->getAssocExpr(i);
  133. if (i == resultIndex) assoc = rebuild(assoc);
  134. assocs[i] = assoc;
  135. assocTypes[i] = gse->getAssocTypeSourceInfo(i);
  136. }
  137. return new (S.Context) GenericSelectionExpr(S.Context,
  138. gse->getGenericLoc(),
  139. gse->getControllingExpr(),
  140. assocTypes,
  141. assocs,
  142. gse->getDefaultLoc(),
  143. gse->getRParenLoc(),
  144. gse->containsUnexpandedParameterPack(),
  145. resultIndex);
  146. }
  147. if (ChooseExpr *ce = dyn_cast<ChooseExpr>(e)) {
  148. assert(!ce->isConditionDependent());
  149. Expr *LHS = ce->getLHS(), *RHS = ce->getRHS();
  150. Expr *&rebuiltExpr = ce->isConditionTrue() ? LHS : RHS;
  151. rebuiltExpr = rebuild(rebuiltExpr);
  152. return new (S.Context) ChooseExpr(ce->getBuiltinLoc(),
  153. ce->getCond(),
  154. LHS, RHS,
  155. rebuiltExpr->getType(),
  156. rebuiltExpr->getValueKind(),
  157. rebuiltExpr->getObjectKind(),
  158. ce->getRParenLoc(),
  159. ce->isConditionTrue(),
  160. rebuiltExpr->isTypeDependent(),
  161. rebuiltExpr->isValueDependent());
  162. }
  163. llvm_unreachable("bad expression to rebuild!");
  164. }
  165. };
  166. class PseudoOpBuilder {
  167. public:
  168. Sema &S;
  169. unsigned ResultIndex;
  170. SourceLocation GenericLoc;
  171. SmallVector<Expr *, 4> Semantics;
  172. PseudoOpBuilder(Sema &S, SourceLocation genericLoc)
  173. : S(S), ResultIndex(PseudoObjectExpr::NoResult),
  174. GenericLoc(genericLoc) {}
  175. virtual ~PseudoOpBuilder() {}
  176. /// Add a normal semantic expression.
  177. void addSemanticExpr(Expr *semantic) {
  178. Semantics.push_back(semantic);
  179. }
  180. /// Add the 'result' semantic expression.
  181. void addResultSemanticExpr(Expr *resultExpr) {
  182. assert(ResultIndex == PseudoObjectExpr::NoResult);
  183. ResultIndex = Semantics.size();
  184. Semantics.push_back(resultExpr);
  185. }
  186. ExprResult buildRValueOperation(Expr *op);
  187. ExprResult buildAssignmentOperation(Scope *Sc,
  188. SourceLocation opLoc,
  189. BinaryOperatorKind opcode,
  190. Expr *LHS, Expr *RHS);
  191. ExprResult buildIncDecOperation(Scope *Sc, SourceLocation opLoc,
  192. UnaryOperatorKind opcode,
  193. Expr *op);
  194. virtual ExprResult complete(Expr *syntacticForm);
  195. OpaqueValueExpr *capture(Expr *op);
  196. OpaqueValueExpr *captureValueAsResult(Expr *op);
  197. void setResultToLastSemantic() {
  198. assert(ResultIndex == PseudoObjectExpr::NoResult);
  199. ResultIndex = Semantics.size() - 1;
  200. }
  201. /// Return true if assignments have a non-void result.
  202. static bool CanCaptureValue(Expr *exp) {
  203. if (exp->isGLValue())
  204. return true;
  205. QualType ty = exp->getType();
  206. assert(!ty->isIncompleteType());
  207. assert(!ty->isDependentType());
  208. if (const CXXRecordDecl *ClassDecl = ty->getAsCXXRecordDecl())
  209. return ClassDecl->isTriviallyCopyable();
  210. return true;
  211. }
  212. virtual Expr *rebuildAndCaptureObject(Expr *) = 0;
  213. virtual ExprResult buildGet() = 0;
  214. virtual ExprResult buildSet(Expr *, SourceLocation,
  215. bool captureSetValueAsResult) = 0;
  216. /// \brief Should the result of an assignment be the formal result of the
  217. /// setter call or the value that was passed to the setter?
  218. ///
  219. /// Different pseudo-object language features use different language rules
  220. /// for this.
  221. /// The default is to use the set value. Currently, this affects the
  222. /// behavior of simple assignments, compound assignments, and prefix
  223. /// increment and decrement.
  224. /// Postfix increment and decrement always use the getter result as the
  225. /// expression result.
  226. ///
  227. /// If this method returns true, and the set value isn't capturable for
  228. /// some reason, the result of the expression will be void.
  229. virtual bool captureSetValueAsResult() const { return true; }
  230. };
  231. /// A PseudoOpBuilder for Objective-C \@properties.
  232. class ObjCPropertyOpBuilder : public PseudoOpBuilder {
  233. ObjCPropertyRefExpr *RefExpr;
  234. ObjCPropertyRefExpr *SyntacticRefExpr;
  235. OpaqueValueExpr *InstanceReceiver;
  236. ObjCMethodDecl *Getter;
  237. ObjCMethodDecl *Setter;
  238. Selector SetterSelector;
  239. Selector GetterSelector;
  240. public:
  241. ObjCPropertyOpBuilder(Sema &S, ObjCPropertyRefExpr *refExpr) :
  242. PseudoOpBuilder(S, refExpr->getLocation()), RefExpr(refExpr),
  243. SyntacticRefExpr(nullptr), InstanceReceiver(nullptr), Getter(nullptr),
  244. Setter(nullptr) {
  245. }
  246. ExprResult buildRValueOperation(Expr *op);
  247. ExprResult buildAssignmentOperation(Scope *Sc,
  248. SourceLocation opLoc,
  249. BinaryOperatorKind opcode,
  250. Expr *LHS, Expr *RHS);
  251. ExprResult buildIncDecOperation(Scope *Sc, SourceLocation opLoc,
  252. UnaryOperatorKind opcode,
  253. Expr *op);
  254. bool tryBuildGetOfReference(Expr *op, ExprResult &result);
  255. bool findSetter(bool warn=true);
  256. bool findGetter();
  257. void DiagnoseUnsupportedPropertyUse();
  258. Expr *rebuildAndCaptureObject(Expr *syntacticBase) override;
  259. ExprResult buildGet() override;
  260. ExprResult buildSet(Expr *op, SourceLocation, bool) override;
  261. ExprResult complete(Expr *SyntacticForm) override;
  262. bool isWeakProperty() const;
  263. };
  264. /// A PseudoOpBuilder for Objective-C array/dictionary indexing.
  265. class ObjCSubscriptOpBuilder : public PseudoOpBuilder {
  266. ObjCSubscriptRefExpr *RefExpr;
  267. OpaqueValueExpr *InstanceBase;
  268. OpaqueValueExpr *InstanceKey;
  269. ObjCMethodDecl *AtIndexGetter;
  270. Selector AtIndexGetterSelector;
  271. ObjCMethodDecl *AtIndexSetter;
  272. Selector AtIndexSetterSelector;
  273. public:
  274. ObjCSubscriptOpBuilder(Sema &S, ObjCSubscriptRefExpr *refExpr) :
  275. PseudoOpBuilder(S, refExpr->getSourceRange().getBegin()),
  276. RefExpr(refExpr),
  277. InstanceBase(nullptr), InstanceKey(nullptr),
  278. AtIndexGetter(nullptr), AtIndexSetter(nullptr) {}
  279. ExprResult buildRValueOperation(Expr *op);
  280. ExprResult buildAssignmentOperation(Scope *Sc,
  281. SourceLocation opLoc,
  282. BinaryOperatorKind opcode,
  283. Expr *LHS, Expr *RHS);
  284. Expr *rebuildAndCaptureObject(Expr *syntacticBase) override;
  285. bool findAtIndexGetter();
  286. bool findAtIndexSetter();
  287. ExprResult buildGet() override;
  288. ExprResult buildSet(Expr *op, SourceLocation, bool) override;
  289. };
  290. class MSPropertyOpBuilder : public PseudoOpBuilder {
  291. MSPropertyRefExpr *RefExpr;
  292. OpaqueValueExpr *InstanceBase;
  293. SmallVector<Expr *, 4> CallArgs;
  294. MSPropertyRefExpr *getBaseMSProperty(MSPropertySubscriptExpr *E);
  295. public:
  296. MSPropertyOpBuilder(Sema &S, MSPropertyRefExpr *refExpr) :
  297. PseudoOpBuilder(S, refExpr->getSourceRange().getBegin()),
  298. RefExpr(refExpr), InstanceBase(nullptr) {}
  299. MSPropertyOpBuilder(Sema &S, MSPropertySubscriptExpr *refExpr)
  300. : PseudoOpBuilder(S, refExpr->getSourceRange().getBegin()),
  301. InstanceBase(nullptr) {
  302. RefExpr = getBaseMSProperty(refExpr);
  303. }
  304. Expr *rebuildAndCaptureObject(Expr *) override;
  305. ExprResult buildGet() override;
  306. ExprResult buildSet(Expr *op, SourceLocation, bool) override;
  307. bool captureSetValueAsResult() const override { return false; }
  308. };
  309. }
  310. /// Capture the given expression in an OpaqueValueExpr.
  311. OpaqueValueExpr *PseudoOpBuilder::capture(Expr *e) {
  312. // Make a new OVE whose source is the given expression.
  313. OpaqueValueExpr *captured =
  314. new (S.Context) OpaqueValueExpr(GenericLoc, e->getType(),
  315. e->getValueKind(), e->getObjectKind(),
  316. e);
  317. // Make sure we bind that in the semantics.
  318. addSemanticExpr(captured);
  319. return captured;
  320. }
  321. /// Capture the given expression as the result of this pseudo-object
  322. /// operation. This routine is safe against expressions which may
  323. /// already be captured.
  324. ///
  325. /// \returns the captured expression, which will be the
  326. /// same as the input if the input was already captured
  327. OpaqueValueExpr *PseudoOpBuilder::captureValueAsResult(Expr *e) {
  328. assert(ResultIndex == PseudoObjectExpr::NoResult);
  329. // If the expression hasn't already been captured, just capture it
  330. // and set the new semantic
  331. if (!isa<OpaqueValueExpr>(e)) {
  332. OpaqueValueExpr *cap = capture(e);
  333. setResultToLastSemantic();
  334. return cap;
  335. }
  336. // Otherwise, it must already be one of our semantic expressions;
  337. // set ResultIndex to its index.
  338. unsigned index = 0;
  339. for (;; ++index) {
  340. assert(index < Semantics.size() &&
  341. "captured expression not found in semantics!");
  342. if (e == Semantics[index]) break;
  343. }
  344. ResultIndex = index;
  345. return cast<OpaqueValueExpr>(e);
  346. }
  347. /// The routine which creates the final PseudoObjectExpr.
  348. ExprResult PseudoOpBuilder::complete(Expr *syntactic) {
  349. return PseudoObjectExpr::Create(S.Context, syntactic,
  350. Semantics, ResultIndex);
  351. }
  352. /// The main skeleton for building an r-value operation.
  353. ExprResult PseudoOpBuilder::buildRValueOperation(Expr *op) {
  354. Expr *syntacticBase = rebuildAndCaptureObject(op);
  355. ExprResult getExpr = buildGet();
  356. if (getExpr.isInvalid()) return ExprError();
  357. addResultSemanticExpr(getExpr.get());
  358. return complete(syntacticBase);
  359. }
  360. /// The basic skeleton for building a simple or compound
  361. /// assignment operation.
  362. ExprResult
  363. PseudoOpBuilder::buildAssignmentOperation(Scope *Sc, SourceLocation opcLoc,
  364. BinaryOperatorKind opcode,
  365. Expr *LHS, Expr *RHS) {
  366. assert(BinaryOperator::isAssignmentOp(opcode));
  367. Expr *syntacticLHS = rebuildAndCaptureObject(LHS);
  368. OpaqueValueExpr *capturedRHS = capture(RHS);
  369. // In some very specific cases, semantic analysis of the RHS as an
  370. // expression may require it to be rewritten. In these cases, we
  371. // cannot safely keep the OVE around. Fortunately, we don't really
  372. // need to: we don't use this particular OVE in multiple places, and
  373. // no clients rely that closely on matching up expressions in the
  374. // semantic expression with expressions from the syntactic form.
  375. Expr *semanticRHS = capturedRHS;
  376. if (RHS->hasPlaceholderType() || isa<InitListExpr>(RHS)) {
  377. semanticRHS = RHS;
  378. Semantics.pop_back();
  379. }
  380. Expr *syntactic;
  381. ExprResult result;
  382. if (opcode == BO_Assign) {
  383. result = semanticRHS;
  384. syntactic = new (S.Context) BinaryOperator(syntacticLHS, capturedRHS,
  385. opcode, capturedRHS->getType(),
  386. capturedRHS->getValueKind(),
  387. OK_Ordinary, opcLoc,
  388. FPOptions());
  389. } else {
  390. ExprResult opLHS = buildGet();
  391. if (opLHS.isInvalid()) return ExprError();
  392. // Build an ordinary, non-compound operation.
  393. BinaryOperatorKind nonCompound =
  394. BinaryOperator::getOpForCompoundAssignment(opcode);
  395. result = S.BuildBinOp(Sc, opcLoc, nonCompound, opLHS.get(), semanticRHS);
  396. if (result.isInvalid()) return ExprError();
  397. syntactic =
  398. new (S.Context) CompoundAssignOperator(syntacticLHS, capturedRHS, opcode,
  399. result.get()->getType(),
  400. result.get()->getValueKind(),
  401. OK_Ordinary,
  402. opLHS.get()->getType(),
  403. result.get()->getType(),
  404. opcLoc, FPOptions());
  405. }
  406. // The result of the assignment, if not void, is the value set into
  407. // the l-value.
  408. result = buildSet(result.get(), opcLoc, captureSetValueAsResult());
  409. if (result.isInvalid()) return ExprError();
  410. addSemanticExpr(result.get());
  411. if (!captureSetValueAsResult() && !result.get()->getType()->isVoidType() &&
  412. (result.get()->isTypeDependent() || CanCaptureValue(result.get())))
  413. setResultToLastSemantic();
  414. return complete(syntactic);
  415. }
  416. /// The basic skeleton for building an increment or decrement
  417. /// operation.
  418. ExprResult
  419. PseudoOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc,
  420. UnaryOperatorKind opcode,
  421. Expr *op) {
  422. assert(UnaryOperator::isIncrementDecrementOp(opcode));
  423. Expr *syntacticOp = rebuildAndCaptureObject(op);
  424. // Load the value.
  425. ExprResult result = buildGet();
  426. if (result.isInvalid()) return ExprError();
  427. QualType resultType = result.get()->getType();
  428. // That's the postfix result.
  429. if (UnaryOperator::isPostfix(opcode) &&
  430. (result.get()->isTypeDependent() || CanCaptureValue(result.get()))) {
  431. result = capture(result.get());
  432. setResultToLastSemantic();
  433. }
  434. // Add or subtract a literal 1.
  435. llvm::APInt oneV(S.Context.getTypeSize(S.Context.IntTy), 1);
  436. Expr *one = IntegerLiteral::Create(S.Context, oneV, S.Context.IntTy,
  437. GenericLoc);
  438. if (UnaryOperator::isIncrementOp(opcode)) {
  439. result = S.BuildBinOp(Sc, opcLoc, BO_Add, result.get(), one);
  440. } else {
  441. result = S.BuildBinOp(Sc, opcLoc, BO_Sub, result.get(), one);
  442. }
  443. if (result.isInvalid()) return ExprError();
  444. // Store that back into the result. The value stored is the result
  445. // of a prefix operation.
  446. result = buildSet(result.get(), opcLoc, UnaryOperator::isPrefix(opcode) &&
  447. captureSetValueAsResult());
  448. if (result.isInvalid()) return ExprError();
  449. addSemanticExpr(result.get());
  450. if (UnaryOperator::isPrefix(opcode) && !captureSetValueAsResult() &&
  451. !result.get()->getType()->isVoidType() &&
  452. (result.get()->isTypeDependent() || CanCaptureValue(result.get())))
  453. setResultToLastSemantic();
  454. UnaryOperator *syntactic =
  455. new (S.Context) UnaryOperator(syntacticOp, opcode, resultType,
  456. VK_LValue, OK_Ordinary, opcLoc);
  457. return complete(syntactic);
  458. }
  459. //===----------------------------------------------------------------------===//
  460. // Objective-C @property and implicit property references
  461. //===----------------------------------------------------------------------===//
  462. /// Look up a method in the receiver type of an Objective-C property
  463. /// reference.
  464. static ObjCMethodDecl *LookupMethodInReceiverType(Sema &S, Selector sel,
  465. const ObjCPropertyRefExpr *PRE) {
  466. if (PRE->isObjectReceiver()) {
  467. const ObjCObjectPointerType *PT =
  468. PRE->getBase()->getType()->castAs<ObjCObjectPointerType>();
  469. // Special case for 'self' in class method implementations.
  470. if (PT->isObjCClassType() &&
  471. S.isSelfExpr(const_cast<Expr*>(PRE->getBase()))) {
  472. // This cast is safe because isSelfExpr is only true within
  473. // methods.
  474. ObjCMethodDecl *method =
  475. cast<ObjCMethodDecl>(S.CurContext->getNonClosureAncestor());
  476. return S.LookupMethodInObjectType(sel,
  477. S.Context.getObjCInterfaceType(method->getClassInterface()),
  478. /*instance*/ false);
  479. }
  480. return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true);
  481. }
  482. if (PRE->isSuperReceiver()) {
  483. if (const ObjCObjectPointerType *PT =
  484. PRE->getSuperReceiverType()->getAs<ObjCObjectPointerType>())
  485. return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true);
  486. return S.LookupMethodInObjectType(sel, PRE->getSuperReceiverType(), false);
  487. }
  488. assert(PRE->isClassReceiver() && "Invalid expression");
  489. QualType IT = S.Context.getObjCInterfaceType(PRE->getClassReceiver());
  490. return S.LookupMethodInObjectType(sel, IT, false);
  491. }
  492. bool ObjCPropertyOpBuilder::isWeakProperty() const {
  493. QualType T;
  494. if (RefExpr->isExplicitProperty()) {
  495. const ObjCPropertyDecl *Prop = RefExpr->getExplicitProperty();
  496. if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
  497. return true;
  498. T = Prop->getType();
  499. } else if (Getter) {
  500. T = Getter->getReturnType();
  501. } else {
  502. return false;
  503. }
  504. return T.getObjCLifetime() == Qualifiers::OCL_Weak;
  505. }
  506. bool ObjCPropertyOpBuilder::findGetter() {
  507. if (Getter) return true;
  508. // For implicit properties, just trust the lookup we already did.
  509. if (RefExpr->isImplicitProperty()) {
  510. if ((Getter = RefExpr->getImplicitPropertyGetter())) {
  511. GetterSelector = Getter->getSelector();
  512. return true;
  513. }
  514. else {
  515. // Must build the getter selector the hard way.
  516. ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter();
  517. assert(setter && "both setter and getter are null - cannot happen");
  518. IdentifierInfo *setterName =
  519. setter->getSelector().getIdentifierInfoForSlot(0);
  520. IdentifierInfo *getterName =
  521. &S.Context.Idents.get(setterName->getName().substr(3));
  522. GetterSelector =
  523. S.PP.getSelectorTable().getNullarySelector(getterName);
  524. return false;
  525. }
  526. }
  527. ObjCPropertyDecl *prop = RefExpr->getExplicitProperty();
  528. Getter = LookupMethodInReceiverType(S, prop->getGetterName(), RefExpr);
  529. return (Getter != nullptr);
  530. }
  531. /// Try to find the most accurate setter declaration for the property
  532. /// reference.
  533. ///
  534. /// \return true if a setter was found, in which case Setter
  535. bool ObjCPropertyOpBuilder::findSetter(bool warn) {
  536. // For implicit properties, just trust the lookup we already did.
  537. if (RefExpr->isImplicitProperty()) {
  538. if (ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter()) {
  539. Setter = setter;
  540. SetterSelector = setter->getSelector();
  541. return true;
  542. } else {
  543. IdentifierInfo *getterName =
  544. RefExpr->getImplicitPropertyGetter()->getSelector()
  545. .getIdentifierInfoForSlot(0);
  546. SetterSelector =
  547. SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
  548. S.PP.getSelectorTable(),
  549. getterName);
  550. return false;
  551. }
  552. }
  553. // For explicit properties, this is more involved.
  554. ObjCPropertyDecl *prop = RefExpr->getExplicitProperty();
  555. SetterSelector = prop->getSetterName();
  556. // Do a normal method lookup first.
  557. if (ObjCMethodDecl *setter =
  558. LookupMethodInReceiverType(S, SetterSelector, RefExpr)) {
  559. if (setter->isPropertyAccessor() && warn)
  560. if (const ObjCInterfaceDecl *IFace =
  561. dyn_cast<ObjCInterfaceDecl>(setter->getDeclContext())) {
  562. StringRef thisPropertyName = prop->getName();
  563. // Try flipping the case of the first character.
  564. char front = thisPropertyName.front();
  565. front = isLowercase(front) ? toUppercase(front) : toLowercase(front);
  566. SmallString<100> PropertyName = thisPropertyName;
  567. PropertyName[0] = front;
  568. IdentifierInfo *AltMember = &S.PP.getIdentifierTable().get(PropertyName);
  569. if (ObjCPropertyDecl *prop1 = IFace->FindPropertyDeclaration(
  570. AltMember, prop->getQueryKind()))
  571. if (prop != prop1 && (prop1->getSetterMethodDecl() == setter)) {
  572. S.Diag(RefExpr->getExprLoc(), diag::err_property_setter_ambiguous_use)
  573. << prop << prop1 << setter->getSelector();
  574. S.Diag(prop->getLocation(), diag::note_property_declare);
  575. S.Diag(prop1->getLocation(), diag::note_property_declare);
  576. }
  577. }
  578. Setter = setter;
  579. return true;
  580. }
  581. // That can fail in the somewhat crazy situation that we're
  582. // type-checking a message send within the @interface declaration
  583. // that declared the @property. But it's not clear that that's
  584. // valuable to support.
  585. return false;
  586. }
  587. void ObjCPropertyOpBuilder::DiagnoseUnsupportedPropertyUse() {
  588. if (S.getCurLexicalContext()->isObjCContainer() &&
  589. S.getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
  590. S.getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) {
  591. if (ObjCPropertyDecl *prop = RefExpr->getExplicitProperty()) {
  592. S.Diag(RefExpr->getLocation(),
  593. diag::err_property_function_in_objc_container);
  594. S.Diag(prop->getLocation(), diag::note_property_declare);
  595. }
  596. }
  597. }
  598. /// Capture the base object of an Objective-C property expression.
  599. Expr *ObjCPropertyOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
  600. assert(InstanceReceiver == nullptr);
  601. // If we have a base, capture it in an OVE and rebuild the syntactic
  602. // form to use the OVE as its base.
  603. if (RefExpr->isObjectReceiver()) {
  604. InstanceReceiver = capture(RefExpr->getBase());
  605. syntacticBase = Rebuilder(S, [=](Expr *, unsigned) -> Expr * {
  606. return InstanceReceiver;
  607. }).rebuild(syntacticBase);
  608. }
  609. if (ObjCPropertyRefExpr *
  610. refE = dyn_cast<ObjCPropertyRefExpr>(syntacticBase->IgnoreParens()))
  611. SyntacticRefExpr = refE;
  612. return syntacticBase;
  613. }
  614. /// Load from an Objective-C property reference.
  615. ExprResult ObjCPropertyOpBuilder::buildGet() {
  616. findGetter();
  617. if (!Getter) {
  618. DiagnoseUnsupportedPropertyUse();
  619. return ExprError();
  620. }
  621. if (SyntacticRefExpr)
  622. SyntacticRefExpr->setIsMessagingGetter();
  623. QualType receiverType = RefExpr->getReceiverType(S.Context);
  624. if (!Getter->isImplicit())
  625. S.DiagnoseUseOfDecl(Getter, GenericLoc, nullptr, true);
  626. // Build a message-send.
  627. ExprResult msg;
  628. if ((Getter->isInstanceMethod() && !RefExpr->isClassReceiver()) ||
  629. RefExpr->isObjectReceiver()) {
  630. assert(InstanceReceiver || RefExpr->isSuperReceiver());
  631. msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType,
  632. GenericLoc, Getter->getSelector(),
  633. Getter, None);
  634. } else {
  635. msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(),
  636. GenericLoc, Getter->getSelector(),
  637. Getter, None);
  638. }
  639. return msg;
  640. }
  641. /// Store to an Objective-C property reference.
  642. ///
  643. /// \param captureSetValueAsResult If true, capture the actual
  644. /// value being set as the value of the property operation.
  645. ExprResult ObjCPropertyOpBuilder::buildSet(Expr *op, SourceLocation opcLoc,
  646. bool captureSetValueAsResult) {
  647. if (!findSetter(false)) {
  648. DiagnoseUnsupportedPropertyUse();
  649. return ExprError();
  650. }
  651. if (SyntacticRefExpr)
  652. SyntacticRefExpr->setIsMessagingSetter();
  653. QualType receiverType = RefExpr->getReceiverType(S.Context);
  654. // Use assignment constraints when possible; they give us better
  655. // diagnostics. "When possible" basically means anything except a
  656. // C++ class type.
  657. if (!S.getLangOpts().CPlusPlus || !op->getType()->isRecordType()) {
  658. QualType paramType = (*Setter->param_begin())->getType()
  659. .substObjCMemberType(
  660. receiverType,
  661. Setter->getDeclContext(),
  662. ObjCSubstitutionContext::Parameter);
  663. if (!S.getLangOpts().CPlusPlus || !paramType->isRecordType()) {
  664. ExprResult opResult = op;
  665. Sema::AssignConvertType assignResult
  666. = S.CheckSingleAssignmentConstraints(paramType, opResult);
  667. if (opResult.isInvalid() ||
  668. S.DiagnoseAssignmentResult(assignResult, opcLoc, paramType,
  669. op->getType(), opResult.get(),
  670. Sema::AA_Assigning))
  671. return ExprError();
  672. op = opResult.get();
  673. assert(op && "successful assignment left argument invalid?");
  674. }
  675. }
  676. // Arguments.
  677. Expr *args[] = { op };
  678. // Build a message-send.
  679. ExprResult msg;
  680. if (!Setter->isImplicit())
  681. S.DiagnoseUseOfDecl(Setter, GenericLoc, nullptr, true);
  682. if ((Setter->isInstanceMethod() && !RefExpr->isClassReceiver()) ||
  683. RefExpr->isObjectReceiver()) {
  684. msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType,
  685. GenericLoc, SetterSelector, Setter,
  686. MultiExprArg(args, 1));
  687. } else {
  688. msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(),
  689. GenericLoc,
  690. SetterSelector, Setter,
  691. MultiExprArg(args, 1));
  692. }
  693. if (!msg.isInvalid() && captureSetValueAsResult) {
  694. ObjCMessageExpr *msgExpr =
  695. cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit());
  696. Expr *arg = msgExpr->getArg(0);
  697. if (CanCaptureValue(arg))
  698. msgExpr->setArg(0, captureValueAsResult(arg));
  699. }
  700. return msg;
  701. }
  702. /// @property-specific behavior for doing lvalue-to-rvalue conversion.
  703. ExprResult ObjCPropertyOpBuilder::buildRValueOperation(Expr *op) {
  704. // Explicit properties always have getters, but implicit ones don't.
  705. // Check that before proceeding.
  706. if (RefExpr->isImplicitProperty() && !RefExpr->getImplicitPropertyGetter()) {
  707. S.Diag(RefExpr->getLocation(), diag::err_getter_not_found)
  708. << RefExpr->getSourceRange();
  709. return ExprError();
  710. }
  711. ExprResult result = PseudoOpBuilder::buildRValueOperation(op);
  712. if (result.isInvalid()) return ExprError();
  713. if (RefExpr->isExplicitProperty() && !Getter->hasRelatedResultType())
  714. S.DiagnosePropertyAccessorMismatch(RefExpr->getExplicitProperty(),
  715. Getter, RefExpr->getLocation());
  716. // As a special case, if the method returns 'id', try to get
  717. // a better type from the property.
  718. if (RefExpr->isExplicitProperty() && result.get()->isRValue()) {
  719. QualType receiverType = RefExpr->getReceiverType(S.Context);
  720. QualType propType = RefExpr->getExplicitProperty()
  721. ->getUsageType(receiverType);
  722. if (result.get()->getType()->isObjCIdType()) {
  723. if (const ObjCObjectPointerType *ptr
  724. = propType->getAs<ObjCObjectPointerType>()) {
  725. if (!ptr->isObjCIdType())
  726. result = S.ImpCastExprToType(result.get(), propType, CK_BitCast);
  727. }
  728. }
  729. if (propType.getObjCLifetime() == Qualifiers::OCL_Weak &&
  730. !S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  731. RefExpr->getLocation()))
  732. S.getCurFunction()->markSafeWeakUse(RefExpr);
  733. }
  734. return result;
  735. }
  736. /// Try to build this as a call to a getter that returns a reference.
  737. ///
  738. /// \return true if it was possible, whether or not it actually
  739. /// succeeded
  740. bool ObjCPropertyOpBuilder::tryBuildGetOfReference(Expr *op,
  741. ExprResult &result) {
  742. if (!S.getLangOpts().CPlusPlus) return false;
  743. findGetter();
  744. if (!Getter) {
  745. // The property has no setter and no getter! This can happen if the type is
  746. // invalid. Error have already been reported.
  747. result = ExprError();
  748. return true;
  749. }
  750. // Only do this if the getter returns an l-value reference type.
  751. QualType resultType = Getter->getReturnType();
  752. if (!resultType->isLValueReferenceType()) return false;
  753. result = buildRValueOperation(op);
  754. return true;
  755. }
  756. /// @property-specific behavior for doing assignments.
  757. ExprResult
  758. ObjCPropertyOpBuilder::buildAssignmentOperation(Scope *Sc,
  759. SourceLocation opcLoc,
  760. BinaryOperatorKind opcode,
  761. Expr *LHS, Expr *RHS) {
  762. assert(BinaryOperator::isAssignmentOp(opcode));
  763. // If there's no setter, we have no choice but to try to assign to
  764. // the result of the getter.
  765. if (!findSetter()) {
  766. ExprResult result;
  767. if (tryBuildGetOfReference(LHS, result)) {
  768. if (result.isInvalid()) return ExprError();
  769. return S.BuildBinOp(Sc, opcLoc, opcode, result.get(), RHS);
  770. }
  771. // Otherwise, it's an error.
  772. S.Diag(opcLoc, diag::err_nosetter_property_assignment)
  773. << unsigned(RefExpr->isImplicitProperty())
  774. << SetterSelector
  775. << LHS->getSourceRange() << RHS->getSourceRange();
  776. return ExprError();
  777. }
  778. // If there is a setter, we definitely want to use it.
  779. // Verify that we can do a compound assignment.
  780. if (opcode != BO_Assign && !findGetter()) {
  781. S.Diag(opcLoc, diag::err_nogetter_property_compound_assignment)
  782. << LHS->getSourceRange() << RHS->getSourceRange();
  783. return ExprError();
  784. }
  785. ExprResult result =
  786. PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS);
  787. if (result.isInvalid()) return ExprError();
  788. // Various warnings about property assignments in ARC.
  789. if (S.getLangOpts().ObjCAutoRefCount && InstanceReceiver) {
  790. S.checkRetainCycles(InstanceReceiver->getSourceExpr(), RHS);
  791. S.checkUnsafeExprAssigns(opcLoc, LHS, RHS);
  792. }
  793. return result;
  794. }
  795. /// @property-specific behavior for doing increments and decrements.
  796. ExprResult
  797. ObjCPropertyOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc,
  798. UnaryOperatorKind opcode,
  799. Expr *op) {
  800. // If there's no setter, we have no choice but to try to assign to
  801. // the result of the getter.
  802. if (!findSetter()) {
  803. ExprResult result;
  804. if (tryBuildGetOfReference(op, result)) {
  805. if (result.isInvalid()) return ExprError();
  806. return S.BuildUnaryOp(Sc, opcLoc, opcode, result.get());
  807. }
  808. // Otherwise, it's an error.
  809. S.Diag(opcLoc, diag::err_nosetter_property_incdec)
  810. << unsigned(RefExpr->isImplicitProperty())
  811. << unsigned(UnaryOperator::isDecrementOp(opcode))
  812. << SetterSelector
  813. << op->getSourceRange();
  814. return ExprError();
  815. }
  816. // If there is a setter, we definitely want to use it.
  817. // We also need a getter.
  818. if (!findGetter()) {
  819. assert(RefExpr->isImplicitProperty());
  820. S.Diag(opcLoc, diag::err_nogetter_property_incdec)
  821. << unsigned(UnaryOperator::isDecrementOp(opcode))
  822. << GetterSelector
  823. << op->getSourceRange();
  824. return ExprError();
  825. }
  826. return PseudoOpBuilder::buildIncDecOperation(Sc, opcLoc, opcode, op);
  827. }
  828. ExprResult ObjCPropertyOpBuilder::complete(Expr *SyntacticForm) {
  829. if (isWeakProperty() &&
  830. !S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  831. SyntacticForm->getLocStart()))
  832. S.recordUseOfEvaluatedWeak(SyntacticRefExpr,
  833. SyntacticRefExpr->isMessagingGetter());
  834. return PseudoOpBuilder::complete(SyntacticForm);
  835. }
  836. // ObjCSubscript build stuff.
  837. //
  838. /// objective-c subscripting-specific behavior for doing lvalue-to-rvalue
  839. /// conversion.
  840. /// FIXME. Remove this routine if it is proven that no additional
  841. /// specifity is needed.
  842. ExprResult ObjCSubscriptOpBuilder::buildRValueOperation(Expr *op) {
  843. ExprResult result = PseudoOpBuilder::buildRValueOperation(op);
  844. if (result.isInvalid()) return ExprError();
  845. return result;
  846. }
  847. /// objective-c subscripting-specific behavior for doing assignments.
  848. ExprResult
  849. ObjCSubscriptOpBuilder::buildAssignmentOperation(Scope *Sc,
  850. SourceLocation opcLoc,
  851. BinaryOperatorKind opcode,
  852. Expr *LHS, Expr *RHS) {
  853. assert(BinaryOperator::isAssignmentOp(opcode));
  854. // There must be a method to do the Index'ed assignment.
  855. if (!findAtIndexSetter())
  856. return ExprError();
  857. // Verify that we can do a compound assignment.
  858. if (opcode != BO_Assign && !findAtIndexGetter())
  859. return ExprError();
  860. ExprResult result =
  861. PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS);
  862. if (result.isInvalid()) return ExprError();
  863. // Various warnings about objc Index'ed assignments in ARC.
  864. if (S.getLangOpts().ObjCAutoRefCount && InstanceBase) {
  865. S.checkRetainCycles(InstanceBase->getSourceExpr(), RHS);
  866. S.checkUnsafeExprAssigns(opcLoc, LHS, RHS);
  867. }
  868. return result;
  869. }
  870. /// Capture the base object of an Objective-C Index'ed expression.
  871. Expr *ObjCSubscriptOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
  872. assert(InstanceBase == nullptr);
  873. // Capture base expression in an OVE and rebuild the syntactic
  874. // form to use the OVE as its base expression.
  875. InstanceBase = capture(RefExpr->getBaseExpr());
  876. InstanceKey = capture(RefExpr->getKeyExpr());
  877. syntacticBase =
  878. Rebuilder(S, [=](Expr *, unsigned Idx) -> Expr * {
  879. switch (Idx) {
  880. case 0:
  881. return InstanceBase;
  882. case 1:
  883. return InstanceKey;
  884. default:
  885. llvm_unreachable("Unexpected index for ObjCSubscriptExpr");
  886. }
  887. }).rebuild(syntacticBase);
  888. return syntacticBase;
  889. }
  890. /// CheckSubscriptingKind - This routine decide what type
  891. /// of indexing represented by "FromE" is being done.
  892. Sema::ObjCSubscriptKind
  893. Sema::CheckSubscriptingKind(Expr *FromE) {
  894. // If the expression already has integral or enumeration type, we're golden.
  895. QualType T = FromE->getType();
  896. if (T->isIntegralOrEnumerationType())
  897. return OS_Array;
  898. // If we don't have a class type in C++, there's no way we can get an
  899. // expression of integral or enumeration type.
  900. const RecordType *RecordTy = T->getAs<RecordType>();
  901. if (!RecordTy &&
  902. (T->isObjCObjectPointerType() || T->isVoidPointerType()))
  903. // All other scalar cases are assumed to be dictionary indexing which
  904. // caller handles, with diagnostics if needed.
  905. return OS_Dictionary;
  906. if (!getLangOpts().CPlusPlus ||
  907. !RecordTy || RecordTy->isIncompleteType()) {
  908. // No indexing can be done. Issue diagnostics and quit.
  909. const Expr *IndexExpr = FromE->IgnoreParenImpCasts();
  910. if (isa<StringLiteral>(IndexExpr))
  911. Diag(FromE->getExprLoc(), diag::err_objc_subscript_pointer)
  912. << T << FixItHint::CreateInsertion(FromE->getExprLoc(), "@");
  913. else
  914. Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion)
  915. << T;
  916. return OS_Error;
  917. }
  918. // We must have a complete class type.
  919. if (RequireCompleteType(FromE->getExprLoc(), T,
  920. diag::err_objc_index_incomplete_class_type, FromE))
  921. return OS_Error;
  922. // Look for a conversion to an integral, enumeration type, or
  923. // objective-C pointer type.
  924. int NoIntegrals=0, NoObjCIdPointers=0;
  925. SmallVector<CXXConversionDecl *, 4> ConversionDecls;
  926. for (NamedDecl *D : cast<CXXRecordDecl>(RecordTy->getDecl())
  927. ->getVisibleConversionFunctions()) {
  928. if (CXXConversionDecl *Conversion =
  929. dyn_cast<CXXConversionDecl>(D->getUnderlyingDecl())) {
  930. QualType CT = Conversion->getConversionType().getNonReferenceType();
  931. if (CT->isIntegralOrEnumerationType()) {
  932. ++NoIntegrals;
  933. ConversionDecls.push_back(Conversion);
  934. }
  935. else if (CT->isObjCIdType() ||CT->isBlockPointerType()) {
  936. ++NoObjCIdPointers;
  937. ConversionDecls.push_back(Conversion);
  938. }
  939. }
  940. }
  941. if (NoIntegrals ==1 && NoObjCIdPointers == 0)
  942. return OS_Array;
  943. if (NoIntegrals == 0 && NoObjCIdPointers == 1)
  944. return OS_Dictionary;
  945. if (NoIntegrals == 0 && NoObjCIdPointers == 0) {
  946. // No conversion function was found. Issue diagnostic and return.
  947. Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion)
  948. << FromE->getType();
  949. return OS_Error;
  950. }
  951. Diag(FromE->getExprLoc(), diag::err_objc_multiple_subscript_type_conversion)
  952. << FromE->getType();
  953. for (unsigned int i = 0; i < ConversionDecls.size(); i++)
  954. Diag(ConversionDecls[i]->getLocation(),
  955. diag::note_conv_function_declared_at);
  956. return OS_Error;
  957. }
  958. /// CheckKeyForObjCARCConversion - This routine suggests bridge casting of CF
  959. /// objects used as dictionary subscript key objects.
  960. static void CheckKeyForObjCARCConversion(Sema &S, QualType ContainerT,
  961. Expr *Key) {
  962. if (ContainerT.isNull())
  963. return;
  964. // dictionary subscripting.
  965. // - (id)objectForKeyedSubscript:(id)key;
  966. IdentifierInfo *KeyIdents[] = {
  967. &S.Context.Idents.get("objectForKeyedSubscript")
  968. };
  969. Selector GetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
  970. ObjCMethodDecl *Getter = S.LookupMethodInObjectType(GetterSelector, ContainerT,
  971. true /*instance*/);
  972. if (!Getter)
  973. return;
  974. QualType T = Getter->parameters()[0]->getType();
  975. S.CheckObjCConversion(Key->getSourceRange(), T, Key,
  976. Sema::CCK_ImplicitConversion);
  977. }
  978. bool ObjCSubscriptOpBuilder::findAtIndexGetter() {
  979. if (AtIndexGetter)
  980. return true;
  981. Expr *BaseExpr = RefExpr->getBaseExpr();
  982. QualType BaseT = BaseExpr->getType();
  983. QualType ResultType;
  984. if (const ObjCObjectPointerType *PTy =
  985. BaseT->getAs<ObjCObjectPointerType>()) {
  986. ResultType = PTy->getPointeeType();
  987. }
  988. Sema::ObjCSubscriptKind Res =
  989. S.CheckSubscriptingKind(RefExpr->getKeyExpr());
  990. if (Res == Sema::OS_Error) {
  991. if (S.getLangOpts().ObjCAutoRefCount)
  992. CheckKeyForObjCARCConversion(S, ResultType,
  993. RefExpr->getKeyExpr());
  994. return false;
  995. }
  996. bool arrayRef = (Res == Sema::OS_Array);
  997. if (ResultType.isNull()) {
  998. S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type)
  999. << BaseExpr->getType() << arrayRef;
  1000. return false;
  1001. }
  1002. if (!arrayRef) {
  1003. // dictionary subscripting.
  1004. // - (id)objectForKeyedSubscript:(id)key;
  1005. IdentifierInfo *KeyIdents[] = {
  1006. &S.Context.Idents.get("objectForKeyedSubscript")
  1007. };
  1008. AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
  1009. }
  1010. else {
  1011. // - (id)objectAtIndexedSubscript:(size_t)index;
  1012. IdentifierInfo *KeyIdents[] = {
  1013. &S.Context.Idents.get("objectAtIndexedSubscript")
  1014. };
  1015. AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
  1016. }
  1017. AtIndexGetter = S.LookupMethodInObjectType(AtIndexGetterSelector, ResultType,
  1018. true /*instance*/);
  1019. if (!AtIndexGetter && S.getLangOpts().DebuggerObjCLiteral) {
  1020. AtIndexGetter = ObjCMethodDecl::Create(S.Context, SourceLocation(),
  1021. SourceLocation(), AtIndexGetterSelector,
  1022. S.Context.getObjCIdType() /*ReturnType*/,
  1023. nullptr /*TypeSourceInfo */,
  1024. S.Context.getTranslationUnitDecl(),
  1025. true /*Instance*/, false/*isVariadic*/,
  1026. /*isPropertyAccessor=*/false,
  1027. /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
  1028. ObjCMethodDecl::Required,
  1029. false);
  1030. ParmVarDecl *Argument = ParmVarDecl::Create(S.Context, AtIndexGetter,
  1031. SourceLocation(), SourceLocation(),
  1032. arrayRef ? &S.Context.Idents.get("index")
  1033. : &S.Context.Idents.get("key"),
  1034. arrayRef ? S.Context.UnsignedLongTy
  1035. : S.Context.getObjCIdType(),
  1036. /*TInfo=*/nullptr,
  1037. SC_None,
  1038. nullptr);
  1039. AtIndexGetter->setMethodParams(S.Context, Argument, None);
  1040. }
  1041. if (!AtIndexGetter) {
  1042. if (!BaseT->isObjCIdType()) {
  1043. S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_method_not_found)
  1044. << BaseExpr->getType() << 0 << arrayRef;
  1045. return false;
  1046. }
  1047. AtIndexGetter =
  1048. S.LookupInstanceMethodInGlobalPool(AtIndexGetterSelector,
  1049. RefExpr->getSourceRange(),
  1050. true);
  1051. }
  1052. if (AtIndexGetter) {
  1053. QualType T = AtIndexGetter->parameters()[0]->getType();
  1054. if ((arrayRef && !T->isIntegralOrEnumerationType()) ||
  1055. (!arrayRef && !T->isObjCObjectPointerType())) {
  1056. S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
  1057. arrayRef ? diag::err_objc_subscript_index_type
  1058. : diag::err_objc_subscript_key_type) << T;
  1059. S.Diag(AtIndexGetter->parameters()[0]->getLocation(),
  1060. diag::note_parameter_type) << T;
  1061. return false;
  1062. }
  1063. QualType R = AtIndexGetter->getReturnType();
  1064. if (!R->isObjCObjectPointerType()) {
  1065. S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
  1066. diag::err_objc_indexing_method_result_type) << R << arrayRef;
  1067. S.Diag(AtIndexGetter->getLocation(), diag::note_method_declared_at) <<
  1068. AtIndexGetter->getDeclName();
  1069. }
  1070. }
  1071. return true;
  1072. }
  1073. bool ObjCSubscriptOpBuilder::findAtIndexSetter() {
  1074. if (AtIndexSetter)
  1075. return true;
  1076. Expr *BaseExpr = RefExpr->getBaseExpr();
  1077. QualType BaseT = BaseExpr->getType();
  1078. QualType ResultType;
  1079. if (const ObjCObjectPointerType *PTy =
  1080. BaseT->getAs<ObjCObjectPointerType>()) {
  1081. ResultType = PTy->getPointeeType();
  1082. }
  1083. Sema::ObjCSubscriptKind Res =
  1084. S.CheckSubscriptingKind(RefExpr->getKeyExpr());
  1085. if (Res == Sema::OS_Error) {
  1086. if (S.getLangOpts().ObjCAutoRefCount)
  1087. CheckKeyForObjCARCConversion(S, ResultType,
  1088. RefExpr->getKeyExpr());
  1089. return false;
  1090. }
  1091. bool arrayRef = (Res == Sema::OS_Array);
  1092. if (ResultType.isNull()) {
  1093. S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type)
  1094. << BaseExpr->getType() << arrayRef;
  1095. return false;
  1096. }
  1097. if (!arrayRef) {
  1098. // dictionary subscripting.
  1099. // - (void)setObject:(id)object forKeyedSubscript:(id)key;
  1100. IdentifierInfo *KeyIdents[] = {
  1101. &S.Context.Idents.get("setObject"),
  1102. &S.Context.Idents.get("forKeyedSubscript")
  1103. };
  1104. AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents);
  1105. }
  1106. else {
  1107. // - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index;
  1108. IdentifierInfo *KeyIdents[] = {
  1109. &S.Context.Idents.get("setObject"),
  1110. &S.Context.Idents.get("atIndexedSubscript")
  1111. };
  1112. AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents);
  1113. }
  1114. AtIndexSetter = S.LookupMethodInObjectType(AtIndexSetterSelector, ResultType,
  1115. true /*instance*/);
  1116. if (!AtIndexSetter && S.getLangOpts().DebuggerObjCLiteral) {
  1117. TypeSourceInfo *ReturnTInfo = nullptr;
  1118. QualType ReturnType = S.Context.VoidTy;
  1119. AtIndexSetter = ObjCMethodDecl::Create(
  1120. S.Context, SourceLocation(), SourceLocation(), AtIndexSetterSelector,
  1121. ReturnType, ReturnTInfo, S.Context.getTranslationUnitDecl(),
  1122. true /*Instance*/, false /*isVariadic*/,
  1123. /*isPropertyAccessor=*/false,
  1124. /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
  1125. ObjCMethodDecl::Required, false);
  1126. SmallVector<ParmVarDecl *, 2> Params;
  1127. ParmVarDecl *object = ParmVarDecl::Create(S.Context, AtIndexSetter,
  1128. SourceLocation(), SourceLocation(),
  1129. &S.Context.Idents.get("object"),
  1130. S.Context.getObjCIdType(),
  1131. /*TInfo=*/nullptr,
  1132. SC_None,
  1133. nullptr);
  1134. Params.push_back(object);
  1135. ParmVarDecl *key = ParmVarDecl::Create(S.Context, AtIndexSetter,
  1136. SourceLocation(), SourceLocation(),
  1137. arrayRef ? &S.Context.Idents.get("index")
  1138. : &S.Context.Idents.get("key"),
  1139. arrayRef ? S.Context.UnsignedLongTy
  1140. : S.Context.getObjCIdType(),
  1141. /*TInfo=*/nullptr,
  1142. SC_None,
  1143. nullptr);
  1144. Params.push_back(key);
  1145. AtIndexSetter->setMethodParams(S.Context, Params, None);
  1146. }
  1147. if (!AtIndexSetter) {
  1148. if (!BaseT->isObjCIdType()) {
  1149. S.Diag(BaseExpr->getExprLoc(),
  1150. diag::err_objc_subscript_method_not_found)
  1151. << BaseExpr->getType() << 1 << arrayRef;
  1152. return false;
  1153. }
  1154. AtIndexSetter =
  1155. S.LookupInstanceMethodInGlobalPool(AtIndexSetterSelector,
  1156. RefExpr->getSourceRange(),
  1157. true);
  1158. }
  1159. bool err = false;
  1160. if (AtIndexSetter && arrayRef) {
  1161. QualType T = AtIndexSetter->parameters()[1]->getType();
  1162. if (!T->isIntegralOrEnumerationType()) {
  1163. S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
  1164. diag::err_objc_subscript_index_type) << T;
  1165. S.Diag(AtIndexSetter->parameters()[1]->getLocation(),
  1166. diag::note_parameter_type) << T;
  1167. err = true;
  1168. }
  1169. T = AtIndexSetter->parameters()[0]->getType();
  1170. if (!T->isObjCObjectPointerType()) {
  1171. S.Diag(RefExpr->getBaseExpr()->getExprLoc(),
  1172. diag::err_objc_subscript_object_type) << T << arrayRef;
  1173. S.Diag(AtIndexSetter->parameters()[0]->getLocation(),
  1174. diag::note_parameter_type) << T;
  1175. err = true;
  1176. }
  1177. }
  1178. else if (AtIndexSetter && !arrayRef)
  1179. for (unsigned i=0; i <2; i++) {
  1180. QualType T = AtIndexSetter->parameters()[i]->getType();
  1181. if (!T->isObjCObjectPointerType()) {
  1182. if (i == 1)
  1183. S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
  1184. diag::err_objc_subscript_key_type) << T;
  1185. else
  1186. S.Diag(RefExpr->getBaseExpr()->getExprLoc(),
  1187. diag::err_objc_subscript_dic_object_type) << T;
  1188. S.Diag(AtIndexSetter->parameters()[i]->getLocation(),
  1189. diag::note_parameter_type) << T;
  1190. err = true;
  1191. }
  1192. }
  1193. return !err;
  1194. }
  1195. // Get the object at "Index" position in the container.
  1196. // [BaseExpr objectAtIndexedSubscript : IndexExpr];
  1197. ExprResult ObjCSubscriptOpBuilder::buildGet() {
  1198. if (!findAtIndexGetter())
  1199. return ExprError();
  1200. QualType receiverType = InstanceBase->getType();
  1201. // Build a message-send.
  1202. ExprResult msg;
  1203. Expr *Index = InstanceKey;
  1204. // Arguments.
  1205. Expr *args[] = { Index };
  1206. assert(InstanceBase);
  1207. if (AtIndexGetter)
  1208. S.DiagnoseUseOfDecl(AtIndexGetter, GenericLoc);
  1209. msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType,
  1210. GenericLoc,
  1211. AtIndexGetterSelector, AtIndexGetter,
  1212. MultiExprArg(args, 1));
  1213. return msg;
  1214. }
  1215. /// Store into the container the "op" object at "Index"'ed location
  1216. /// by building this messaging expression:
  1217. /// - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index;
  1218. /// \param captureSetValueAsResult If true, capture the actual
  1219. /// value being set as the value of the property operation.
  1220. ExprResult ObjCSubscriptOpBuilder::buildSet(Expr *op, SourceLocation opcLoc,
  1221. bool captureSetValueAsResult) {
  1222. if (!findAtIndexSetter())
  1223. return ExprError();
  1224. if (AtIndexSetter)
  1225. S.DiagnoseUseOfDecl(AtIndexSetter, GenericLoc);
  1226. QualType receiverType = InstanceBase->getType();
  1227. Expr *Index = InstanceKey;
  1228. // Arguments.
  1229. Expr *args[] = { op, Index };
  1230. // Build a message-send.
  1231. ExprResult msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType,
  1232. GenericLoc,
  1233. AtIndexSetterSelector,
  1234. AtIndexSetter,
  1235. MultiExprArg(args, 2));
  1236. if (!msg.isInvalid() && captureSetValueAsResult) {
  1237. ObjCMessageExpr *msgExpr =
  1238. cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit());
  1239. Expr *arg = msgExpr->getArg(0);
  1240. if (CanCaptureValue(arg))
  1241. msgExpr->setArg(0, captureValueAsResult(arg));
  1242. }
  1243. return msg;
  1244. }
  1245. //===----------------------------------------------------------------------===//
  1246. // MSVC __declspec(property) references
  1247. //===----------------------------------------------------------------------===//
  1248. MSPropertyRefExpr *
  1249. MSPropertyOpBuilder::getBaseMSProperty(MSPropertySubscriptExpr *E) {
  1250. CallArgs.insert(CallArgs.begin(), E->getIdx());
  1251. Expr *Base = E->getBase()->IgnoreParens();
  1252. while (auto *MSPropSubscript = dyn_cast<MSPropertySubscriptExpr>(Base)) {
  1253. CallArgs.insert(CallArgs.begin(), MSPropSubscript->getIdx());
  1254. Base = MSPropSubscript->getBase()->IgnoreParens();
  1255. }
  1256. return cast<MSPropertyRefExpr>(Base);
  1257. }
  1258. Expr *MSPropertyOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
  1259. InstanceBase = capture(RefExpr->getBaseExpr());
  1260. llvm::for_each(CallArgs, [this](Expr *&Arg) { Arg = capture(Arg); });
  1261. syntacticBase = Rebuilder(S, [=](Expr *, unsigned Idx) -> Expr * {
  1262. switch (Idx) {
  1263. case 0:
  1264. return InstanceBase;
  1265. default:
  1266. assert(Idx <= CallArgs.size());
  1267. return CallArgs[Idx - 1];
  1268. }
  1269. }).rebuild(syntacticBase);
  1270. return syntacticBase;
  1271. }
  1272. ExprResult MSPropertyOpBuilder::buildGet() {
  1273. if (!RefExpr->getPropertyDecl()->hasGetter()) {
  1274. S.Diag(RefExpr->getMemberLoc(), diag::err_no_accessor_for_property)
  1275. << 0 /* getter */ << RefExpr->getPropertyDecl();
  1276. return ExprError();
  1277. }
  1278. UnqualifiedId GetterName;
  1279. IdentifierInfo *II = RefExpr->getPropertyDecl()->getGetterId();
  1280. GetterName.setIdentifier(II, RefExpr->getMemberLoc());
  1281. CXXScopeSpec SS;
  1282. SS.Adopt(RefExpr->getQualifierLoc());
  1283. ExprResult GetterExpr =
  1284. S.ActOnMemberAccessExpr(S.getCurScope(), InstanceBase, SourceLocation(),
  1285. RefExpr->isArrow() ? tok::arrow : tok::period, SS,
  1286. SourceLocation(), GetterName, nullptr);
  1287. if (GetterExpr.isInvalid()) {
  1288. S.Diag(RefExpr->getMemberLoc(),
  1289. diag::err_cannot_find_suitable_accessor) << 0 /* getter */
  1290. << RefExpr->getPropertyDecl();
  1291. return ExprError();
  1292. }
  1293. return S.ActOnCallExpr(S.getCurScope(), GetterExpr.get(),
  1294. RefExpr->getSourceRange().getBegin(), CallArgs,
  1295. RefExpr->getSourceRange().getEnd());
  1296. }
  1297. ExprResult MSPropertyOpBuilder::buildSet(Expr *op, SourceLocation sl,
  1298. bool captureSetValueAsResult) {
  1299. if (!RefExpr->getPropertyDecl()->hasSetter()) {
  1300. S.Diag(RefExpr->getMemberLoc(), diag::err_no_accessor_for_property)
  1301. << 1 /* setter */ << RefExpr->getPropertyDecl();
  1302. return ExprError();
  1303. }
  1304. UnqualifiedId SetterName;
  1305. IdentifierInfo *II = RefExpr->getPropertyDecl()->getSetterId();
  1306. SetterName.setIdentifier(II, RefExpr->getMemberLoc());
  1307. CXXScopeSpec SS;
  1308. SS.Adopt(RefExpr->getQualifierLoc());
  1309. ExprResult SetterExpr =
  1310. S.ActOnMemberAccessExpr(S.getCurScope(), InstanceBase, SourceLocation(),
  1311. RefExpr->isArrow() ? tok::arrow : tok::period, SS,
  1312. SourceLocation(), SetterName, nullptr);
  1313. if (SetterExpr.isInvalid()) {
  1314. S.Diag(RefExpr->getMemberLoc(),
  1315. diag::err_cannot_find_suitable_accessor) << 1 /* setter */
  1316. << RefExpr->getPropertyDecl();
  1317. return ExprError();
  1318. }
  1319. SmallVector<Expr*, 4> ArgExprs;
  1320. ArgExprs.append(CallArgs.begin(), CallArgs.end());
  1321. ArgExprs.push_back(op);
  1322. return S.ActOnCallExpr(S.getCurScope(), SetterExpr.get(),
  1323. RefExpr->getSourceRange().getBegin(), ArgExprs,
  1324. op->getSourceRange().getEnd());
  1325. }
  1326. //===----------------------------------------------------------------------===//
  1327. // General Sema routines.
  1328. //===----------------------------------------------------------------------===//
  1329. ExprResult Sema::checkPseudoObjectRValue(Expr *E) {
  1330. Expr *opaqueRef = E->IgnoreParens();
  1331. if (ObjCPropertyRefExpr *refExpr
  1332. = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
  1333. ObjCPropertyOpBuilder builder(*this, refExpr);
  1334. return builder.buildRValueOperation(E);
  1335. }
  1336. else if (ObjCSubscriptRefExpr *refExpr
  1337. = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
  1338. ObjCSubscriptOpBuilder builder(*this, refExpr);
  1339. return builder.buildRValueOperation(E);
  1340. } else if (MSPropertyRefExpr *refExpr
  1341. = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
  1342. MSPropertyOpBuilder builder(*this, refExpr);
  1343. return builder.buildRValueOperation(E);
  1344. } else if (MSPropertySubscriptExpr *RefExpr =
  1345. dyn_cast<MSPropertySubscriptExpr>(opaqueRef)) {
  1346. MSPropertyOpBuilder Builder(*this, RefExpr);
  1347. return Builder.buildRValueOperation(E);
  1348. } else {
  1349. llvm_unreachable("unknown pseudo-object kind!");
  1350. }
  1351. }
  1352. /// Check an increment or decrement of a pseudo-object expression.
  1353. ExprResult Sema::checkPseudoObjectIncDec(Scope *Sc, SourceLocation opcLoc,
  1354. UnaryOperatorKind opcode, Expr *op) {
  1355. // Do nothing if the operand is dependent.
  1356. if (op->isTypeDependent())
  1357. return new (Context) UnaryOperator(op, opcode, Context.DependentTy,
  1358. VK_RValue, OK_Ordinary, opcLoc);
  1359. assert(UnaryOperator::isIncrementDecrementOp(opcode));
  1360. Expr *opaqueRef = op->IgnoreParens();
  1361. if (ObjCPropertyRefExpr *refExpr
  1362. = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
  1363. ObjCPropertyOpBuilder builder(*this, refExpr);
  1364. return builder.buildIncDecOperation(Sc, opcLoc, opcode, op);
  1365. } else if (isa<ObjCSubscriptRefExpr>(opaqueRef)) {
  1366. Diag(opcLoc, diag::err_illegal_container_subscripting_op);
  1367. return ExprError();
  1368. } else if (MSPropertyRefExpr *refExpr
  1369. = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
  1370. MSPropertyOpBuilder builder(*this, refExpr);
  1371. return builder.buildIncDecOperation(Sc, opcLoc, opcode, op);
  1372. } else if (MSPropertySubscriptExpr *RefExpr
  1373. = dyn_cast<MSPropertySubscriptExpr>(opaqueRef)) {
  1374. MSPropertyOpBuilder Builder(*this, RefExpr);
  1375. return Builder.buildIncDecOperation(Sc, opcLoc, opcode, op);
  1376. } else {
  1377. llvm_unreachable("unknown pseudo-object kind!");
  1378. }
  1379. }
  1380. ExprResult Sema::checkPseudoObjectAssignment(Scope *S, SourceLocation opcLoc,
  1381. BinaryOperatorKind opcode,
  1382. Expr *LHS, Expr *RHS) {
  1383. // Do nothing if either argument is dependent.
  1384. if (LHS->isTypeDependent() || RHS->isTypeDependent())
  1385. return new (Context) BinaryOperator(LHS, RHS, opcode, Context.DependentTy,
  1386. VK_RValue, OK_Ordinary, opcLoc,
  1387. FPOptions());
  1388. // Filter out non-overload placeholder types in the RHS.
  1389. if (RHS->getType()->isNonOverloadPlaceholderType()) {
  1390. ExprResult result = CheckPlaceholderExpr(RHS);
  1391. if (result.isInvalid()) return ExprError();
  1392. RHS = result.get();
  1393. }
  1394. Expr *opaqueRef = LHS->IgnoreParens();
  1395. if (ObjCPropertyRefExpr *refExpr
  1396. = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
  1397. ObjCPropertyOpBuilder builder(*this, refExpr);
  1398. return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
  1399. } else if (ObjCSubscriptRefExpr *refExpr
  1400. = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
  1401. ObjCSubscriptOpBuilder builder(*this, refExpr);
  1402. return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
  1403. } else if (MSPropertyRefExpr *refExpr
  1404. = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
  1405. MSPropertyOpBuilder builder(*this, refExpr);
  1406. return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
  1407. } else if (MSPropertySubscriptExpr *RefExpr
  1408. = dyn_cast<MSPropertySubscriptExpr>(opaqueRef)) {
  1409. MSPropertyOpBuilder Builder(*this, RefExpr);
  1410. return Builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
  1411. } else {
  1412. llvm_unreachable("unknown pseudo-object kind!");
  1413. }
  1414. }
  1415. /// Given a pseudo-object reference, rebuild it without the opaque
  1416. /// values. Basically, undo the behavior of rebuildAndCaptureObject.
  1417. /// This should never operate in-place.
  1418. static Expr *stripOpaqueValuesFromPseudoObjectRef(Sema &S, Expr *E) {
  1419. return Rebuilder(S,
  1420. [=](Expr *E, unsigned) -> Expr * {
  1421. return cast<OpaqueValueExpr>(E)->getSourceExpr();
  1422. })
  1423. .rebuild(E);
  1424. }
  1425. /// Given a pseudo-object expression, recreate what it looks like
  1426. /// syntactically without the attendant OpaqueValueExprs.
  1427. ///
  1428. /// This is a hack which should be removed when TreeTransform is
  1429. /// capable of rebuilding a tree without stripping implicit
  1430. /// operations.
  1431. Expr *Sema::recreateSyntacticForm(PseudoObjectExpr *E) {
  1432. Expr *syntax = E->getSyntacticForm();
  1433. if (UnaryOperator *uop = dyn_cast<UnaryOperator>(syntax)) {
  1434. Expr *op = stripOpaqueValuesFromPseudoObjectRef(*this, uop->getSubExpr());
  1435. return new (Context) UnaryOperator(op, uop->getOpcode(), uop->getType(),
  1436. uop->getValueKind(), uop->getObjectKind(),
  1437. uop->getOperatorLoc());
  1438. } else if (CompoundAssignOperator *cop
  1439. = dyn_cast<CompoundAssignOperator>(syntax)) {
  1440. Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, cop->getLHS());
  1441. Expr *rhs = cast<OpaqueValueExpr>(cop->getRHS())->getSourceExpr();
  1442. return new (Context) CompoundAssignOperator(lhs, rhs, cop->getOpcode(),
  1443. cop->getType(),
  1444. cop->getValueKind(),
  1445. cop->getObjectKind(),
  1446. cop->getComputationLHSType(),
  1447. cop->getComputationResultType(),
  1448. cop->getOperatorLoc(),
  1449. FPOptions());
  1450. } else if (BinaryOperator *bop = dyn_cast<BinaryOperator>(syntax)) {
  1451. Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, bop->getLHS());
  1452. Expr *rhs = cast<OpaqueValueExpr>(bop->getRHS())->getSourceExpr();
  1453. return new (Context) BinaryOperator(lhs, rhs, bop->getOpcode(),
  1454. bop->getType(), bop->getValueKind(),
  1455. bop->getObjectKind(),
  1456. bop->getOperatorLoc(), FPOptions());
  1457. } else {
  1458. assert(syntax->hasPlaceholderType(BuiltinType::PseudoObject));
  1459. return stripOpaqueValuesFromPseudoObjectRef(*this, syntax);
  1460. }
  1461. }