ExprClassification.cpp revision 016a4a90c8e75d59de731fa3aa98f0a55656e66c
1//===--- ExprClassification.cpp - Expression AST Node Implementation ------===//
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 Expr::classify.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Support/ErrorHandling.h"
15#include "clang/AST/Expr.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ExprObjC.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclTemplate.h"
22using namespace clang;
23
24typedef Expr::Classification Cl;
25
26static Cl::Kinds ClassifyInternal(ASTContext &Ctx, const Expr *E);
27static Cl::Kinds ClassifyDecl(ASTContext &Ctx, const Decl *D);
28static Cl::Kinds ClassifyUnnamed(ASTContext &Ctx, QualType T);
29static Cl::Kinds ClassifyMemberExpr(ASTContext &Ctx, const MemberExpr *E);
30static Cl::Kinds ClassifyBinaryOp(ASTContext &Ctx, const BinaryOperator *E);
31static Cl::Kinds ClassifyConditional(ASTContext &Ctx,
32                                    const ConditionalOperator *E);
33static Cl::ModifiableType IsModifiable(ASTContext &Ctx, const Expr *E,
34                                       Cl::Kinds Kind, SourceLocation &Loc);
35
36Cl Expr::ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const {
37  assert(!TR->isReferenceType() && "Expressions can't have reference type.");
38
39  Cl::Kinds kind = ClassifyInternal(Ctx, this);
40  // C99 6.3.2.1: An lvalue is an expression with an object type or an
41  //   incomplete type other than void.
42  if (!Ctx.getLangOptions().CPlusPlus) {
43    // Thus, no functions.
44    if (TR->isFunctionType() || TR == Ctx.OverloadTy)
45      kind = Cl::CL_Function;
46    // No void either, but qualified void is OK because it is "other than void".
47    else if (TR->isVoidType() && !Ctx.getCanonicalType(TR).hasQualifiers())
48      kind = Cl::CL_Void;
49  }
50
51  Cl::ModifiableType modifiable = Cl::CM_Untested;
52  if (Loc)
53    modifiable = IsModifiable(Ctx, this, kind, *Loc);
54  return Classification(kind, modifiable);
55}
56
57static Cl::Kinds ClassifyInternal(ASTContext &Ctx, const Expr *E) {
58  // This function takes the first stab at classifying expressions.
59  const LangOptions &Lang = Ctx.getLangOptions();
60
61  switch (E->getStmtClass()) {
62    // First come the expressions that are always lvalues, unconditionally.
63
64  case Expr::ObjCIsaExprClass:
65    // C++ [expr.prim.general]p1: A string literal is an lvalue.
66  case Expr::StringLiteralClass:
67    // @encode is equivalent to its string
68  case Expr::ObjCEncodeExprClass:
69    // __func__ and friends are too.
70  case Expr::PredefinedExprClass:
71    // Property references are lvalues
72  case Expr::ObjCPropertyRefExprClass:
73  case Expr::ObjCImplicitSetterGetterRefExprClass:
74    // C++ [expr.typeid]p1: The result of a typeid expression is an lvalue of...
75  case Expr::CXXTypeidExprClass:
76    // Unresolved lookups get classified as lvalues.
77    // FIXME: Is this wise? Should they get their own kind?
78  case Expr::UnresolvedLookupExprClass:
79  case Expr::UnresolvedMemberExprClass:
80    // ObjC instance variables are lvalues
81    // FIXME: ObjC++0x might have different rules
82  case Expr::ObjCIvarRefExprClass:
83    // C99 6.5.2.5p5 says that compound literals are lvalues.
84    // FIXME: C++ might have a different opinion.
85  case Expr::CompoundLiteralExprClass:
86    return Cl::CL_LValue;
87
88    // Next come the complicated cases.
89
90    // C++ [expr.sub]p1: The result is an lvalue of type "T".
91    // However, subscripting vector types is more like member access.
92  case Expr::ArraySubscriptExprClass:
93    if (cast<ArraySubscriptExpr>(E)->getBase()->getType()->isVectorType())
94      return ClassifyInternal(Ctx, cast<ArraySubscriptExpr>(E)->getBase());
95    return Cl::CL_LValue;
96
97    // C++ [expr.prim.general]p3: The result is an lvalue if the entity is a
98    //   function or variable and a prvalue otherwise.
99  case Expr::DeclRefExprClass:
100    return ClassifyDecl(Ctx, cast<DeclRefExpr>(E)->getDecl());
101    // We deal with names referenced from blocks the same way.
102  case Expr::BlockDeclRefExprClass:
103    return ClassifyDecl(Ctx, cast<BlockDeclRefExpr>(E)->getDecl());
104
105    // Member access is complex.
106  case Expr::MemberExprClass:
107    return ClassifyMemberExpr(Ctx, cast<MemberExpr>(E));
108
109  case Expr::UnaryOperatorClass:
110    switch (cast<UnaryOperator>(E)->getOpcode()) {
111      // C++ [expr.unary.op]p1: The unary * operator performs indirection:
112      //   [...] the result is an lvalue referring to the object or function
113      //   to which the expression points.
114    case UnaryOperator::Deref:
115      return Cl::CL_LValue;
116
117      // GNU extensions, simply look through them.
118    case UnaryOperator::Real:
119    case UnaryOperator::Imag:
120    case UnaryOperator::Extension:
121      return ClassifyInternal(Ctx, cast<UnaryOperator>(E)->getSubExpr());
122
123      // C++ [expr.pre.incr]p1: The result is the updated operand; it is an
124      //   lvalue, [...]
125      // Not so in C.
126    case UnaryOperator::PreInc:
127    case UnaryOperator::PreDec:
128      return Lang.CPlusPlus ? Cl::CL_LValue : Cl::CL_PRValue;
129
130    default:
131      return Cl::CL_PRValue;
132    }
133
134    // Implicit casts are lvalues if they're lvalue casts. Other than that, we
135    // only specifically record class temporaries.
136  case Expr::ImplicitCastExprClass:
137    if (cast<ImplicitCastExpr>(E)->isLvalueCast())
138      return Cl::CL_LValue;
139    return Lang.CPlusPlus && E->getType()->isRecordType() ?
140      Cl::CL_ClassTemporary : Cl::CL_PRValue;
141
142    // C++ [expr.prim.general]p4: The presence of parentheses does not affect
143    //   whether the expression is an lvalue.
144  case Expr::ParenExprClass:
145    return ClassifyInternal(Ctx, cast<ParenExpr>(E)->getSubExpr());
146
147  case Expr::BinaryOperatorClass:
148  case Expr::CompoundAssignOperatorClass:
149    // C doesn't have any binary expressions that are lvalues.
150    if (Lang.CPlusPlus)
151      return ClassifyBinaryOp(Ctx, cast<BinaryOperator>(E));
152    return Cl::CL_PRValue;
153
154  case Expr::CallExprClass:
155  case Expr::CXXOperatorCallExprClass:
156  case Expr::CXXMemberCallExprClass:
157    return ClassifyUnnamed(Ctx, cast<CallExpr>(E)->getCallReturnType());
158
159    // __builtin_choose_expr is equivalent to the chosen expression.
160  case Expr::ChooseExprClass:
161    return ClassifyInternal(Ctx, cast<ChooseExpr>(E)->getChosenSubExpr(Ctx));
162
163    // Extended vector element access is an lvalue unless there are duplicates
164    // in the shuffle expression.
165  case Expr::ExtVectorElementExprClass:
166    return cast<ExtVectorElementExpr>(E)->containsDuplicateElements() ?
167      Cl::CL_DuplicateVectorComponents : Cl::CL_LValue;
168
169    // Simply look at the actual default argument.
170  case Expr::CXXDefaultArgExprClass:
171    return ClassifyInternal(Ctx, cast<CXXDefaultArgExpr>(E)->getExpr());
172
173    // Same idea for temporary binding.
174  case Expr::CXXBindTemporaryExprClass:
175    return ClassifyInternal(Ctx, cast<CXXBindTemporaryExpr>(E)->getSubExpr());
176
177    // And the temporary lifetime guard.
178  case Expr::CXXExprWithTemporariesClass:
179    return ClassifyInternal(Ctx, cast<CXXExprWithTemporaries>(E)->getSubExpr());
180
181    // Casts depend completely on the target type. All casts work the same.
182  case Expr::CStyleCastExprClass:
183  case Expr::CXXFunctionalCastExprClass:
184  case Expr::CXXStaticCastExprClass:
185  case Expr::CXXDynamicCastExprClass:
186  case Expr::CXXReinterpretCastExprClass:
187  case Expr::CXXConstCastExprClass:
188    // Only in C++ can casts be interesting at all.
189    if (!Lang.CPlusPlus) return Cl::CL_PRValue;
190    return ClassifyUnnamed(Ctx, cast<ExplicitCastExpr>(E)->getTypeAsWritten());
191
192  case Expr::ConditionalOperatorClass:
193    // Once again, only C++ is interesting.
194    if (!Lang.CPlusPlus) return Cl::CL_PRValue;
195    return ClassifyConditional(Ctx, cast<ConditionalOperator>(E));
196
197    // ObjC message sends are effectively function calls, if the target function
198    // is known.
199  case Expr::ObjCMessageExprClass:
200    if (const ObjCMethodDecl *Method =
201          cast<ObjCMessageExpr>(E)->getMethodDecl()) {
202      return ClassifyUnnamed(Ctx, Method->getResultType());
203    }
204
205    // Some C++ expressions are always class temporaries.
206  case Expr::CXXConstructExprClass:
207  case Expr::CXXTemporaryObjectExprClass:
208  case Expr::CXXScalarValueInitExprClass:
209    return Cl::CL_ClassTemporary;
210
211    // Everything we haven't handled is a prvalue.
212  default:
213    return Cl::CL_PRValue;
214  }
215}
216
217/// ClassifyDecl - Return the classification of an expression referencing the
218/// given declaration.
219static Cl::Kinds ClassifyDecl(ASTContext &Ctx, const Decl *D) {
220  // C++ [expr.prim.general]p6: The result is an lvalue if the entity is a
221  //   function, variable, or data member and a prvalue otherwise.
222  // In C, functions are not lvalues.
223  // In addition, NonTypeTemplateParmDecl derives from VarDecl but isn't an
224  // lvalue unless it's a reference type (C++ [temp.param]p6), so we need to
225  // special-case this.
226  bool islvalue;
227  if (const NonTypeTemplateParmDecl *NTTParm =
228        dyn_cast<NonTypeTemplateParmDecl>(D))
229    islvalue = NTTParm->getType()->isReferenceType();
230  else
231    islvalue = isa<VarDecl>(D) || isa<FieldDecl>(D) ||
232      (Ctx.getLangOptions().CPlusPlus &&
233        (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)));
234
235  return islvalue ? Cl::CL_LValue : Cl::CL_PRValue;
236}
237
238/// ClassifyUnnamed - Return the classification of an expression yielding an
239/// unnamed value of the given type. This applies in particular to function
240/// calls and casts.
241static Cl::Kinds ClassifyUnnamed(ASTContext &Ctx, QualType T) {
242  // In C, function calls are always rvalues.
243  if (!Ctx.getLangOptions().CPlusPlus) return Cl::CL_PRValue;
244
245  // C++ [expr.call]p10: A function call is an lvalue if the result type is an
246  //   lvalue reference type or an rvalue reference to function type, an xvalue
247  //   if the result type is an rvalue refernence to object type, and a prvalue
248  //   otherwise.
249  if (T->isLValueReferenceType())
250    return Cl::CL_LValue;
251  const RValueReferenceType *RV = T->getAs<RValueReferenceType>();
252  if (!RV) // Could still be a class temporary, though.
253    return T->isRecordType() ? Cl::CL_ClassTemporary : Cl::CL_PRValue;
254
255  return RV->getPointeeType()->isFunctionType() ? Cl::CL_LValue : Cl::CL_XValue;
256}
257
258static Cl::Kinds ClassifyMemberExpr(ASTContext &Ctx, const MemberExpr *E) {
259  // Handle C first, it's easier.
260  if (!Ctx.getLangOptions().CPlusPlus) {
261    // C99 6.5.2.3p3
262    // For dot access, the expression is an lvalue if the first part is. For
263    // arrow access, it always is an lvalue.
264    if (E->isArrow())
265      return Cl::CL_LValue;
266    // ObjC property accesses are not lvalues, but get special treatment.
267    Expr *Base = E->getBase();
268    if (isa<ObjCPropertyRefExpr>(Base) ||
269        isa<ObjCImplicitSetterGetterRefExpr>(Base))
270      return Cl::CL_SubObjCPropertySetting;
271    return ClassifyInternal(Ctx, Base);
272  }
273
274  NamedDecl *Member = E->getMemberDecl();
275  // C++ [expr.ref]p3: E1->E2 is converted to the equivalent form (*(E1)).E2.
276  // C++ [expr.ref]p4: If E2 is declared to have type "reference to T", then
277  //   E1.E2 is an lvalue.
278  if (ValueDecl *Value = dyn_cast<ValueDecl>(Member))
279    if (Value->getType()->isReferenceType())
280      return Cl::CL_LValue;
281
282  //   Otherwise, one of the following rules applies.
283  //   -- If E2 is a static member [...] then E1.E2 is an lvalue.
284  if (isa<VarDecl>(Member) && Member->getDeclContext()->isRecord())
285    return Cl::CL_LValue;
286
287  //   -- If E2 is a non-static data member [...]. If E1 is an lvalue, then
288  //      E1.E2 is an lvalue; if E1 is an xvalue, then E1.E2 is an xvalue;
289  //      otherwise, it is a prvalue.
290  if (isa<FieldDecl>(Member)) {
291    // *E1 is an lvalue
292    if (E->isArrow())
293      return Cl::CL_LValue;
294    return ClassifyInternal(Ctx, E->getBase());
295  }
296
297  //   -- If E2 is a [...] member function, [...]
298  //      -- If it refers to a static member function [...], then E1.E2 is an
299  //         lvalue; [...]
300  //      -- Otherwise [...] E1.E2 is a prvalue.
301  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member))
302    return Method->isStatic() ? Cl::CL_LValue : Cl::CL_MemberFunction;
303
304  //   -- If E2 is a member enumerator [...], the expression E1.E2 is a prvalue.
305  // So is everything else we haven't handled yet.
306  return Cl::CL_PRValue;
307}
308
309static Cl::Kinds ClassifyBinaryOp(ASTContext &Ctx, const BinaryOperator *E) {
310  assert(Ctx.getLangOptions().CPlusPlus &&
311         "This is only relevant for C++.");
312  // C++ [expr.ass]p1: All [...] return an lvalue referring to the left operand.
313  if (E->isAssignmentOp())
314    return Cl::CL_LValue;
315
316  // C++ [expr.comma]p1: the result is of the same value category as its right
317  //   operand, [...].
318  if (E->getOpcode() == BinaryOperator::Comma)
319    return ClassifyInternal(Ctx, E->getRHS());
320
321  // C++ [expr.mptr.oper]p6: The result of a .* expression whose second operand
322  //   is a pointer to a data member is of the same value category as its first
323  //   operand.
324  if (E->getOpcode() == BinaryOperator::PtrMemD)
325    return E->getType()->isFunctionType() ? Cl::CL_MemberFunction :
326      ClassifyInternal(Ctx, E->getLHS());
327
328  // C++ [expr.mptr.oper]p6: The result of an ->* expression is an lvalue if its
329  //   second operand is a pointer to data member and a prvalue otherwise.
330  if (E->getOpcode() == BinaryOperator::PtrMemI)
331    return E->getType()->isFunctionType() ?
332      Cl::CL_MemberFunction : Cl::CL_LValue;
333
334  // All other binary operations are prvalues.
335  return Cl::CL_PRValue;
336}
337
338static Cl::Kinds ClassifyConditional(ASTContext &Ctx,
339                                     const ConditionalOperator *E) {
340  assert(Ctx.getLangOptions().CPlusPlus &&
341         "This is only relevant for C++.");
342
343  Expr *True = E->getTrueExpr();
344  Expr *False = E->getFalseExpr();
345  // C++ [expr.cond]p2
346  //   If either the second or the third operand has type (cv) void, [...]
347  //   the result [...] is a prvalue.
348  if (True->getType()->isVoidType() || False->getType()->isVoidType())
349    return Cl::CL_PRValue;
350
351  // Note that at this point, we have already performed all conversions
352  // according to [expr.cond]p3.
353  // C++ [expr.cond]p4: If the second and third operands are glvalues of the
354  //   same value category [...], the result is of that [...] value category.
355  // C++ [expr.cond]p5: Otherwise, the result is a prvalue.
356  Cl::Kinds LCl = ClassifyInternal(Ctx, True),
357            RCl = ClassifyInternal(Ctx, False);
358  return LCl == RCl ? LCl : Cl::CL_PRValue;
359}
360
361static Cl::ModifiableType IsModifiable(ASTContext &Ctx, const Expr *E,
362                                       Cl::Kinds Kind, SourceLocation &Loc) {
363  // As a general rule, we only care about lvalues. But there are some rvalues
364  // for which we want to generate special results.
365  if (Kind == Cl::CL_PRValue) {
366    // For the sake of better diagnostics, we want to specifically recognize
367    // use of the GCC cast-as-lvalue extension.
368    if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E->IgnoreParens())){
369      if (CE->getSubExpr()->Classify(Ctx).isLValue()) {
370        Loc = CE->getLParenLoc();
371        return Cl::CM_LValueCast;
372      }
373    }
374  }
375  if (Kind != Cl::CL_LValue)
376    return Cl::CM_RValue;
377
378  // This is the lvalue case.
379  // Functions are lvalues in C++, but not modifiable. (C++ [basic.lval]p6)
380  if (Ctx.getLangOptions().CPlusPlus && E->getType()->isFunctionType())
381    return Cl::CM_Function;
382
383  // You cannot assign to a variable outside a block from within the block if
384  // it is not marked __block, e.g.
385  //   void takeclosure(void (^C)(void));
386  //   void func() { int x = 1; takeclosure(^{ x = 7; }); }
387  if (const BlockDeclRefExpr *BDR = dyn_cast<BlockDeclRefExpr>(E)) {
388    if (!BDR->isByRef() && isa<VarDecl>(BDR->getDecl()))
389      return Cl::CM_NotBlockQualified;
390  }
391
392  // Assignment to a property in ObjC is an implicit setter access. But a
393  // setter might not exist.
394  if (const ObjCImplicitSetterGetterRefExpr *Expr =
395        dyn_cast<ObjCImplicitSetterGetterRefExpr>(E)) {
396    if (Expr->getSetterMethod() == 0)
397      return Cl::CM_NoSetterProperty;
398  }
399
400  CanQualType CT = Ctx.getCanonicalType(E->getType());
401  // Const stuff is obviously not modifiable.
402  if (CT.isConstQualified())
403    return Cl::CM_ConstQualified;
404  // Arrays are not modifiable, only their elements are.
405  if (CT->isArrayType())
406    return Cl::CM_ArrayType;
407  // Incomplete types are not modifiable.
408  if (CT->isIncompleteType())
409    return Cl::CM_IncompleteType;
410
411  // Records with any const fields (recursively) are not modifiable.
412  if (const RecordType *R = CT->getAs<RecordType>()) {
413    assert(!Ctx.getLangOptions().CPlusPlus &&
414           "C++ struct assignment should be resolved by the "
415           "copy assignment operator.");
416    if (R->hasConstFields())
417      return Cl::CM_ConstQualified;
418  }
419
420  return Cl::CM_Modifiable;
421}
422
423Expr::isLvalueResult Expr::isLvalue(ASTContext &Ctx) const {
424  Classification VC = Classify(Ctx);
425  switch (VC.getKind()) {
426  case Cl::CL_LValue: return LV_Valid;
427  case Cl::CL_XValue: return LV_InvalidExpression;
428  case Cl::CL_Function: return LV_NotObjectType;
429  case Cl::CL_Void: return LV_IncompleteVoidType;
430  case Cl::CL_DuplicateVectorComponents: return LV_DuplicateVectorComponents;
431  case Cl::CL_MemberFunction: return LV_MemberFunction;
432  case Cl::CL_SubObjCPropertySetting: return LV_SubObjCPropertySetting;
433  case Cl::CL_ClassTemporary: return LV_ClassTemporary;
434  case Cl::CL_PRValue: return LV_InvalidExpression;
435  }
436  llvm_unreachable("Unhandled kind");
437}
438
439Expr::isModifiableLvalueResult
440Expr::isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc) const {
441  SourceLocation dummy;
442  Classification VC = ClassifyModifiable(Ctx, Loc ? *Loc : dummy);
443  switch (VC.getKind()) {
444  case Cl::CL_LValue: break;
445  case Cl::CL_XValue: return MLV_InvalidExpression;
446  case Cl::CL_Function: return MLV_NotObjectType;
447  case Cl::CL_Void: return MLV_IncompleteVoidType;
448  case Cl::CL_DuplicateVectorComponents: return MLV_DuplicateVectorComponents;
449  case Cl::CL_MemberFunction: return MLV_MemberFunction;
450  case Cl::CL_SubObjCPropertySetting: return MLV_SubObjCPropertySetting;
451  case Cl::CL_ClassTemporary: return MLV_ClassTemporary;
452  case Cl::CL_PRValue:
453    return VC.getModifiable() == Cl::CM_LValueCast ?
454      MLV_LValueCast : MLV_InvalidExpression;
455  }
456  assert(VC.getKind() == Cl::CL_LValue && "Unhandled kind");
457  switch (VC.getModifiable()) {
458  case Cl::CM_Untested: llvm_unreachable("Did not test modifiability");
459  case Cl::CM_Modifiable: return MLV_Valid;
460  case Cl::CM_RValue: llvm_unreachable("CM_RValue and CL_LValue don't match");
461  case Cl::CM_Function: return MLV_NotObjectType;
462  case Cl::CM_LValueCast:
463    llvm_unreachable("CM_LValueCast and CL_LValue don't match");
464  case Cl::CM_NotBlockQualified: return MLV_NotBlockQualified;
465  case Cl::CM_NoSetterProperty: return MLV_NoSetterProperty;
466  case Cl::CM_ConstQualified: return MLV_ConstQualified;
467  case Cl::CM_ArrayType: return MLV_ArrayType;
468  case Cl::CM_IncompleteType: return MLV_IncompleteType;
469  }
470  llvm_unreachable("Unhandled modifiable type");
471}
472