1//===- ExprClassification.cpp - Expression AST Node Implementation --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements Expr::classify.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/Expr.h"
14#include "clang/AST/ASTContext.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 "llvm/Support/ErrorHandling.h"
21
22using namespace clang;
23
24using Cl = Expr::Classification;
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 Expr *trueExpr,
33 const Expr *falseExpr);
34static Cl::ModifiableType IsModifiable(ASTContext &Ctx, const Expr *E,
35 Cl::Kinds Kind, SourceLocation &Loc);
36
37Cl Expr::ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const {
38 assert(!TR->isReferenceType() && "Expressions can't have reference type.");
39
40 Cl::Kinds kind = ClassifyInternal(Ctx, E: this);
41 // C99 6.3.2.1: An lvalue is an expression with an object type or an
42 // incomplete type other than void.
43 if (!Ctx.getLangOpts().CPlusPlus) {
44 // Thus, no functions.
45 if (TR->isFunctionType() || TR == Ctx.OverloadTy)
46 kind = Cl::CL_Function;
47 // No void either, but qualified void is OK because it is "other than void".
48 // Void "lvalues" are classified as addressable void values, which are void
49 // expressions whose address can be taken.
50 else if (TR->isVoidType() && !TR.hasQualifiers())
51 kind = (kind == Cl::CL_LValue ? Cl::CL_AddressableVoid : Cl::CL_Void);
52 }
53
54 // Enable this assertion for testing.
55 switch (kind) {
56 case Cl::CL_LValue:
57 assert(isLValue());
58 break;
59 case Cl::CL_XValue:
60 assert(isXValue());
61 break;
62 case Cl::CL_Function:
63 case Cl::CL_Void:
64 case Cl::CL_AddressableVoid:
65 case Cl::CL_DuplicateVectorComponents:
66 case Cl::CL_DuplicateMatrixComponents:
67 case Cl::CL_MemberFunction:
68 case Cl::CL_SubObjCPropertySetting:
69 case Cl::CL_ClassTemporary:
70 case Cl::CL_ArrayTemporary:
71 case Cl::CL_ObjCMessageRValue:
72 case Cl::CL_PRValue:
73 assert(isPRValue());
74 break;
75 }
76
77 Cl::ModifiableType modifiable = Cl::CM_Untested;
78 if (Loc)
79 modifiable = IsModifiable(Ctx, E: this, Kind: kind, Loc&: *Loc);
80 return Classification(kind, modifiable);
81}
82
83/// Classify an expression which creates a temporary, based on its type.
84static Cl::Kinds ClassifyTemporary(QualType T) {
85 if (T->isRecordType())
86 return Cl::CL_ClassTemporary;
87 if (T->isArrayType())
88 return Cl::CL_ArrayTemporary;
89
90 // No special classification: these don't behave differently from normal
91 // prvalues.
92 return Cl::CL_PRValue;
93}
94
95static Cl::Kinds ClassifyExprValueKind(const LangOptions &Lang,
96 const Expr *E,
97 ExprValueKind Kind) {
98 switch (Kind) {
99 case VK_PRValue:
100 return Lang.CPlusPlus ? ClassifyTemporary(T: E->getType()) : Cl::CL_PRValue;
101 case VK_LValue:
102 return Cl::CL_LValue;
103 case VK_XValue:
104 return Cl::CL_XValue;
105 }
106 llvm_unreachable("Invalid value category of implicit cast.");
107}
108
109static Cl::Kinds ClassifyInternal(ASTContext &Ctx, const Expr *E) {
110 // This function takes the first stab at classifying expressions.
111 const LangOptions &Lang = Ctx.getLangOpts();
112
113 switch (E->getStmtClass()) {
114 case Stmt::NoStmtClass:
115#define ABSTRACT_STMT(Kind)
116#define STMT(Kind, Base) case Expr::Kind##Class:
117#define EXPR(Kind, Base)
118#include "clang/AST/StmtNodes.inc"
119 llvm_unreachable("cannot classify a statement");
120
121 // First come the expressions that are always lvalues, unconditionally.
122 case Expr::ObjCIsaExprClass:
123 // Property references are lvalues
124 case Expr::ObjCSubscriptRefExprClass:
125 case Expr::ObjCPropertyRefExprClass:
126 // C++ [expr.typeid]p1: The result of a typeid expression is an lvalue of...
127 case Expr::CXXTypeidExprClass:
128 case Expr::CXXUuidofExprClass:
129 // Unresolved lookups and uncorrected typos get classified as lvalues.
130 // FIXME: Is this wise? Should they get their own kind?
131 case Expr::UnresolvedLookupExprClass:
132 case Expr::UnresolvedMemberExprClass:
133 case Expr::DependentTemplateIdExprClass:
134 case Expr::DependentCoawaitExprClass:
135 case Expr::CXXDependentScopeMemberExprClass:
136 case Expr::DependentScopeDeclRefExprClass:
137 // ObjC instance variables are lvalues
138 // FIXME: ObjC++0x might have different rules
139 case Expr::ObjCIvarRefExprClass:
140 case Expr::FunctionParmPackExprClass:
141 case Expr::MSPropertyRefExprClass:
142 case Expr::MSPropertySubscriptExprClass:
143 case Expr::ArraySectionExprClass:
144 case Expr::OMPArrayShapingExprClass:
145 case Expr::OMPIteratorExprClass:
146 case Expr::HLSLOutArgExprClass:
147 return Cl::CL_LValue;
148
149 // C++ [expr.prim.general]p1: A string literal is an lvalue.
150 case Expr::StringLiteralClass:
151 // @encode is equivalent to its string
152 case Expr::ObjCEncodeExprClass:
153 // Except we special case them as prvalues when they are used to
154 // initialize a char array.
155 return E->isLValue() ? Cl::CL_LValue : Cl::CL_PRValue;
156
157 // __func__ and friends are too.
158 // The char array initialization special case also applies
159 // when they are transparent.
160 case Expr::PredefinedExprClass: {
161 auto *PE = cast<PredefinedExpr>(Val: E);
162 const StringLiteral *SL = PE->getFunctionName();
163 if (PE->isTransparent())
164 return SL ? ClassifyInternal(Ctx, E: SL) : Cl::CL_LValue;
165 assert(!SL || SL->isLValue());
166 return Cl::CL_LValue;
167 }
168
169 // C99 6.5.2.5p5 says that compound literals are lvalues.
170 // In C++, they're prvalue temporaries, except for file-scope arrays.
171 case Expr::CompoundLiteralExprClass:
172 return !E->isLValue() ? ClassifyTemporary(T: E->getType()) : Cl::CL_LValue;
173
174 // Expressions that are prvalues.
175 case Expr::CXXBoolLiteralExprClass:
176 case Expr::CXXPseudoDestructorExprClass:
177 case Expr::UnaryExprOrTypeTraitExprClass:
178 case Expr::CXXNewExprClass:
179 case Expr::CXXNullPtrLiteralExprClass:
180 case Expr::ImaginaryLiteralClass:
181 case Expr::GNUNullExprClass:
182 case Expr::OffsetOfExprClass:
183 case Expr::CXXThrowExprClass:
184 case Expr::ShuffleVectorExprClass:
185 case Expr::ConvertVectorExprClass:
186 case Expr::IntegerLiteralClass:
187 case Expr::FixedPointLiteralClass:
188 case Expr::CharacterLiteralClass:
189 case Expr::AddrLabelExprClass:
190 case Expr::CXXDeleteExprClass:
191 case Expr::ImplicitValueInitExprClass:
192 case Expr::BlockExprClass:
193 case Expr::FloatingLiteralClass:
194 case Expr::CXXNoexceptExprClass:
195 case Expr::CXXScalarValueInitExprClass:
196 case Expr::TypeTraitExprClass:
197 case Expr::ArrayTypeTraitExprClass:
198 case Expr::ExpressionTraitExprClass:
199 case Expr::ObjCSelectorExprClass:
200 case Expr::ObjCProtocolExprClass:
201 case Expr::ObjCStringLiteralClass:
202 case Expr::ObjCBoxedExprClass:
203 case Expr::ObjCArrayLiteralClass:
204 case Expr::ObjCDictionaryLiteralClass:
205 case Expr::ObjCBoolLiteralExprClass:
206 case Expr::ObjCAvailabilityCheckExprClass:
207 case Expr::ParenListExprClass:
208 case Expr::SizeOfPackExprClass:
209 case Expr::SubstNonTypeTemplateParmPackExprClass:
210 case Expr::AsTypeExprClass:
211 case Expr::ObjCIndirectCopyRestoreExprClass:
212 case Expr::AtomicExprClass:
213 case Expr::CXXFoldExprClass:
214 case Expr::ArrayInitLoopExprClass:
215 case Expr::ArrayInitIndexExprClass:
216 case Expr::NoInitExprClass:
217 case Expr::DesignatedInitUpdateExprClass:
218 case Expr::SourceLocExprClass:
219 case Expr::ConceptSpecializationExprClass:
220 case Expr::RequiresExprClass:
221 case Expr::CXXReflectExprClass:
222 case Expr::CXXExpansionSelectExprClass:
223 return Cl::CL_PRValue;
224
225 case Expr::EmbedExprClass:
226 // Nominally, this just goes through as a PRValue until we actually expand
227 // it and check it.
228 return Cl::CL_PRValue;
229
230 // Make HLSL this reference-like
231 case Expr::CXXThisExprClass:
232 return Lang.HLSL ? Cl::CL_LValue : Cl::CL_PRValue;
233
234 case Expr::ConstantExprClass:
235 return ClassifyInternal(Ctx, E: cast<ConstantExpr>(Val: E)->getSubExpr());
236
237 // Next come the complicated cases.
238 case Expr::SubstNonTypeTemplateParmExprClass:
239 return ClassifyInternal(Ctx,
240 E: cast<SubstNonTypeTemplateParmExpr>(Val: E)->getReplacement());
241
242 case Expr::PackIndexingExprClass: {
243 // A pack-index-expression always expands to an id-expression.
244 // Consider it as an LValue expression.
245 if (cast<PackIndexingExpr>(Val: E)->isInstantiationDependent())
246 return Cl::CL_LValue;
247 return ClassifyInternal(Ctx, E: cast<PackIndexingExpr>(Val: E)->getSelectedExpr());
248 }
249
250 // C, C++98 [expr.sub]p1: The result is an lvalue of type "T".
251 // C++11 (DR1213): in the case of an array operand, the result is an lvalue
252 // if that operand is an lvalue and an xvalue otherwise.
253 // Subscripting vector types is more like member access.
254 case Expr::ArraySubscriptExprClass:
255 if (cast<ArraySubscriptExpr>(Val: E)->getBase()->getType()->isVectorType())
256 return ClassifyInternal(Ctx, E: cast<ArraySubscriptExpr>(Val: E)->getBase());
257 if (Lang.CPlusPlus11) {
258 // Step over the array-to-pointer decay if present, but not over the
259 // temporary materialization.
260 auto *Base = cast<ArraySubscriptExpr>(Val: E)->getBase()->IgnoreImpCasts();
261 if (Base->getType()->isArrayType())
262 return ClassifyInternal(Ctx, E: Base);
263 }
264 return Cl::CL_LValue;
265
266 case Expr::MatrixSingleSubscriptExprClass:
267 return ClassifyInternal(Ctx, E: cast<MatrixSingleSubscriptExpr>(Val: E)->getBase());
268
269 // Subscripting matrix types behaves like member accesses.
270 case Expr::MatrixSubscriptExprClass:
271 return ClassifyInternal(Ctx, E: cast<MatrixSubscriptExpr>(Val: E)->getBase());
272
273 // C++ [expr.prim.general]p3: The result is an lvalue if the entity is a
274 // function or variable and a prvalue otherwise.
275 case Expr::DeclRefExprClass:
276 if (E->getType() == Ctx.UnknownAnyTy)
277 return isa<FunctionDecl>(Val: cast<DeclRefExpr>(Val: E)->getDecl())
278 ? Cl::CL_PRValue : Cl::CL_LValue;
279 return ClassifyDecl(Ctx, D: cast<DeclRefExpr>(Val: E)->getDecl());
280
281 // Member access is complex.
282 case Expr::MemberExprClass:
283 return ClassifyMemberExpr(Ctx, E: cast<MemberExpr>(Val: E));
284
285 case Expr::UnaryOperatorClass:
286 switch (cast<UnaryOperator>(Val: E)->getOpcode()) {
287 // C++ [expr.unary.op]p1: The unary * operator performs indirection:
288 // [...] the result is an lvalue referring to the object or function
289 // to which the expression points.
290 case UO_Deref:
291 return Cl::CL_LValue;
292
293 // GNU extensions, simply look through them.
294 case UO_Extension:
295 return ClassifyInternal(Ctx, E: cast<UnaryOperator>(Val: E)->getSubExpr());
296
297 // Treat _Real and _Imag basically as if they were member
298 // expressions: l-value only if the operand is a true l-value.
299 case UO_Real:
300 case UO_Imag: {
301 const auto *UnaryOp = cast<UnaryOperator>(Val: E);
302 const Expr *Op = UnaryOp->getSubExpr()->IgnoreParens();
303 Cl::Kinds K = ClassifyInternal(Ctx, E: Op);
304 if (K != Cl::CL_LValue) return K;
305
306 if (isa<ObjCPropertyRefExpr>(Val: Op))
307 return Cl::CL_SubObjCPropertySetting;
308
309 // _Imag with non-complex operand is not a valid l-value.
310 if (UnaryOp->getOpcode() == UO_Imag && !Op->getType()->isAnyComplexType())
311 return Cl::CL_PRValue;
312
313 return Cl::CL_LValue;
314 }
315
316 // C++ [expr.pre.incr]p1: The result is the updated operand; it is an
317 // lvalue, [...]
318 // Not so in C.
319 case UO_PreInc:
320 case UO_PreDec:
321 return Lang.CPlusPlus ? Cl::CL_LValue : Cl::CL_PRValue;
322
323 default:
324 return Cl::CL_PRValue;
325 }
326
327 case Expr::RecoveryExprClass:
328 case Expr::OpaqueValueExprClass:
329 return ClassifyExprValueKind(Lang, E, Kind: E->getValueKind());
330
331 // Pseudo-object expressions can produce l-values with reference magic.
332 case Expr::PseudoObjectExprClass:
333 return ClassifyExprValueKind(Lang, E,
334 Kind: cast<PseudoObjectExpr>(Val: E)->getValueKind());
335
336 // Implicit casts are lvalues if they're lvalue casts. Other than that, we
337 // only specifically record class temporaries.
338 case Expr::ImplicitCastExprClass:
339 return ClassifyExprValueKind(Lang, E, Kind: E->getValueKind());
340
341 // C++ [expr.prim.general]p4: The presence of parentheses does not affect
342 // whether the expression is an lvalue.
343 case Expr::ParenExprClass:
344 return ClassifyInternal(Ctx, E: cast<ParenExpr>(Val: E)->getSubExpr());
345
346 // C11 6.5.1.1p4: [A generic selection] is an lvalue, a function designator,
347 // or a void expression if its result expression is, respectively, an
348 // lvalue, a function designator, or a void expression.
349 case Expr::GenericSelectionExprClass:
350 if (cast<GenericSelectionExpr>(Val: E)->isResultDependent())
351 return Cl::CL_PRValue;
352 return ClassifyInternal(Ctx,E: cast<GenericSelectionExpr>(Val: E)->getResultExpr());
353
354 case Expr::BinaryOperatorClass:
355 case Expr::CompoundAssignOperatorClass:
356 // C doesn't have any binary expressions that are lvalues.
357 if (Lang.CPlusPlus)
358 return ClassifyBinaryOp(Ctx, E: cast<BinaryOperator>(Val: E));
359 return Cl::CL_PRValue;
360
361 case Expr::CallExprClass:
362 case Expr::CXXOperatorCallExprClass:
363 case Expr::CXXMemberCallExprClass:
364 case Expr::UserDefinedLiteralClass:
365 case Expr::CUDAKernelCallExprClass:
366 return ClassifyUnnamed(Ctx, T: cast<CallExpr>(Val: E)->getCallReturnType(Ctx));
367
368 case Expr::CXXRewrittenBinaryOperatorClass:
369 return ClassifyInternal(
370 Ctx, E: cast<CXXRewrittenBinaryOperator>(Val: E)->getSemanticForm());
371
372 // __builtin_choose_expr is equivalent to the chosen expression.
373 case Expr::ChooseExprClass:
374 return ClassifyInternal(Ctx, E: cast<ChooseExpr>(Val: E)->getChosenSubExpr());
375
376 // Extended vector element access is an lvalue unless there are duplicates
377 // in the shuffle expression.
378 case Expr::ExtVectorElementExprClass:
379 if (cast<ExtVectorElementExpr>(Val: E)->containsDuplicateElements())
380 return Cl::CL_DuplicateVectorComponents;
381 if (cast<ExtVectorElementExpr>(Val: E)->isArrow())
382 return Cl::CL_LValue;
383 return ClassifyInternal(Ctx, E: cast<ExtVectorElementExpr>(Val: E)->getBase());
384
385 // Matrix element access is an lvalue unless there are duplicates
386 // in the shuffle expression.
387 case Expr::MatrixElementExprClass:
388 if (cast<MatrixElementExpr>(Val: E)->containsDuplicateElements())
389 return Cl::CL_DuplicateMatrixComponents;
390 // NOTE: MatrixElementExpr is currently only used by HLSL which does not
391 // have pointers so there is no isArrow() necessary or way to test
392 // Cl::CL_LValue
393 return ClassifyInternal(Ctx, E: cast<MatrixElementExpr>(Val: E)->getBase());
394
395 // Simply look at the actual default argument.
396 case Expr::CXXDefaultArgExprClass:
397 return ClassifyInternal(Ctx, E: cast<CXXDefaultArgExpr>(Val: E)->getExpr());
398
399 // Same idea for default initializers.
400 case Expr::CXXDefaultInitExprClass:
401 return ClassifyInternal(Ctx, E: cast<CXXDefaultInitExpr>(Val: E)->getExpr());
402
403 // Same idea for temporary binding.
404 case Expr::CXXBindTemporaryExprClass:
405 return ClassifyInternal(Ctx, E: cast<CXXBindTemporaryExpr>(Val: E)->getSubExpr());
406
407 // And the cleanups guard.
408 case Expr::ExprWithCleanupsClass:
409 return ClassifyInternal(Ctx, E: cast<ExprWithCleanups>(Val: E)->getSubExpr());
410
411 // Casts depend completely on the target type. All casts work the same.
412 case Expr::CStyleCastExprClass:
413 case Expr::CXXFunctionalCastExprClass:
414 case Expr::CXXStaticCastExprClass:
415 case Expr::CXXDynamicCastExprClass:
416 case Expr::CXXReinterpretCastExprClass:
417 case Expr::CXXConstCastExprClass:
418 case Expr::CXXAddrspaceCastExprClass:
419 case Expr::ObjCBridgedCastExprClass:
420 case Expr::BuiltinBitCastExprClass:
421 // Only in C++ can casts be interesting at all.
422 if (!Lang.CPlusPlus) return Cl::CL_PRValue;
423 return ClassifyUnnamed(Ctx, T: cast<ExplicitCastExpr>(Val: E)->getTypeAsWritten());
424
425 case Expr::CXXUnresolvedConstructExprClass:
426 return ClassifyUnnamed(Ctx,
427 T: cast<CXXUnresolvedConstructExpr>(Val: E)->getTypeAsWritten());
428
429 case Expr::BinaryConditionalOperatorClass: {
430 if (!Lang.CPlusPlus) return Cl::CL_PRValue;
431 const auto *co = cast<BinaryConditionalOperator>(Val: E);
432 return ClassifyConditional(Ctx, trueExpr: co->getTrueExpr(), falseExpr: co->getFalseExpr());
433 }
434
435 case Expr::ConditionalOperatorClass: {
436 // Once again, only C++ is interesting.
437 if (!Lang.CPlusPlus) return Cl::CL_PRValue;
438 const auto *co = cast<ConditionalOperator>(Val: E);
439 return ClassifyConditional(Ctx, trueExpr: co->getTrueExpr(), falseExpr: co->getFalseExpr());
440 }
441
442 // ObjC message sends are effectively function calls, if the target function
443 // is known.
444 case Expr::ObjCMessageExprClass:
445 if (const ObjCMethodDecl *Method =
446 cast<ObjCMessageExpr>(Val: E)->getMethodDecl()) {
447 Cl::Kinds kind = ClassifyUnnamed(Ctx, T: Method->getReturnType());
448 return (kind == Cl::CL_PRValue) ? Cl::CL_ObjCMessageRValue : kind;
449 }
450 return Cl::CL_PRValue;
451
452 // Some C++ expressions are always class temporaries.
453 case Expr::CXXConstructExprClass:
454 case Expr::CXXInheritedCtorInitExprClass:
455 case Expr::CXXTemporaryObjectExprClass:
456 case Expr::LambdaExprClass:
457 case Expr::CXXStdInitializerListExprClass:
458 return Cl::CL_ClassTemporary;
459
460 case Expr::VAArgExprClass:
461 return ClassifyUnnamed(Ctx, T: E->getType());
462
463 case Expr::DesignatedInitExprClass:
464 return ClassifyInternal(Ctx, E: cast<DesignatedInitExpr>(Val: E)->getInit());
465
466 case Expr::StmtExprClass: {
467 const CompoundStmt *S = cast<StmtExpr>(Val: E)->getSubStmt();
468 if (const auto *LastExpr = dyn_cast_or_null<Expr>(Val: S->body_back()))
469 return ClassifyUnnamed(Ctx, T: LastExpr->getType());
470 return Cl::CL_PRValue;
471 }
472
473 case Expr::PackExpansionExprClass:
474 return ClassifyInternal(Ctx, E: cast<PackExpansionExpr>(Val: E)->getPattern());
475
476 case Expr::MaterializeTemporaryExprClass:
477 return cast<MaterializeTemporaryExpr>(Val: E)->isBoundToLvalueReference()
478 ? Cl::CL_LValue
479 : Cl::CL_XValue;
480
481 case Expr::InitListExprClass:
482 // An init list can be an lvalue if it is bound to a reference and
483 // contains only one element. In that case, we look at that element
484 // for an exact classification. Init list creation takes care of the
485 // value kind for us, so we only need to fine-tune.
486 if (E->isPRValue())
487 return ClassifyExprValueKind(Lang, E, Kind: E->getValueKind());
488 assert(cast<InitListExpr>(E)->getNumInits() == 1 &&
489 "Only 1-element init lists can be glvalues.");
490 return ClassifyInternal(Ctx, E: cast<InitListExpr>(Val: E)->getInit(Init: 0));
491
492 case Expr::CoawaitExprClass:
493 case Expr::CoyieldExprClass:
494 return ClassifyInternal(Ctx, E: cast<CoroutineSuspendExpr>(Val: E)->getResumeExpr());
495 case Expr::SYCLUniqueStableNameExprClass:
496 case Expr::OpenACCAsteriskSizeExprClass:
497 return Cl::CL_PRValue;
498 break;
499
500 case Expr::CXXParenListInitExprClass:
501 if (isa<ArrayType>(Val: E->getType()))
502 return Cl::CL_ArrayTemporary;
503 return Cl::CL_ClassTemporary;
504 }
505
506 llvm_unreachable("unhandled expression kind in classification");
507}
508
509/// ClassifyDecl - Return the classification of an expression referencing the
510/// given declaration.
511static Cl::Kinds ClassifyDecl(ASTContext &Ctx, const Decl *D) {
512 // C++ [expr.prim.id.unqual]p3: The result is an lvalue if the entity is a
513 // function, variable, or data member, or a template parameter object and a
514 // prvalue otherwise.
515 // In C, functions are not lvalues.
516 // In addition, NonTypeTemplateParmDecl derives from VarDecl but isn't an
517 // lvalue unless it's a reference type or a class type (C++ [temp.param]p8),
518 // so we need to special-case this.
519
520 if (const auto *M = dyn_cast<CXXMethodDecl>(Val: D)) {
521 if (M->isImplicitObjectMemberFunction())
522 return Cl::CL_MemberFunction;
523 if (M->isStatic())
524 return Cl::CL_LValue;
525 return Cl::CL_PRValue;
526 }
527
528 bool islvalue;
529 if (const auto *NTTParm = dyn_cast<NonTypeTemplateParmDecl>(Val: D))
530 islvalue = NTTParm->getType()->isReferenceType() ||
531 NTTParm->getType()->isRecordType();
532 else
533 islvalue =
534 isa<VarDecl, FieldDecl, IndirectFieldDecl, BindingDecl, MSGuidDecl,
535 UnnamedGlobalConstantDecl, TemplateParamObjectDecl>(Val: D) ||
536 (Ctx.getLangOpts().CPlusPlus &&
537 (isa<FunctionDecl, MSPropertyDecl, FunctionTemplateDecl>(Val: D)));
538
539 return islvalue ? Cl::CL_LValue : Cl::CL_PRValue;
540}
541
542/// ClassifyUnnamed - Return the classification of an expression yielding an
543/// unnamed value of the given type. This applies in particular to function
544/// calls and casts.
545static Cl::Kinds ClassifyUnnamed(ASTContext &Ctx, QualType T) {
546 // In C, function calls are always rvalues.
547 if (!Ctx.getLangOpts().CPlusPlus) return Cl::CL_PRValue;
548
549 // C++ [expr.call]p10: A function call is an lvalue if the result type is an
550 // lvalue reference type or an rvalue reference to function type, an xvalue
551 // if the result type is an rvalue reference to object type, and a prvalue
552 // otherwise.
553 if (T->isLValueReferenceType())
554 return Cl::CL_LValue;
555 const auto *RV = T->getAs<RValueReferenceType>();
556 if (!RV) // Could still be a class temporary, though.
557 return ClassifyTemporary(T);
558
559 return RV->getPointeeType()->isFunctionType() ? Cl::CL_LValue : Cl::CL_XValue;
560}
561
562static Cl::Kinds ClassifyMemberExpr(ASTContext &Ctx, const MemberExpr *E) {
563 if (E->getType() == Ctx.UnknownAnyTy)
564 return (isa<FunctionDecl>(Val: E->getMemberDecl())
565 ? Cl::CL_PRValue : Cl::CL_LValue);
566
567 // Handle C first, it's easier.
568 if (!Ctx.getLangOpts().CPlusPlus) {
569 // C99 6.5.2.3p3
570 // For dot access, the expression is an lvalue if the first part is. For
571 // arrow access, it always is an lvalue.
572 if (E->isArrow())
573 return Cl::CL_LValue;
574 // ObjC property accesses are not lvalues, but get special treatment.
575 Expr *Base = E->getBase()->IgnoreParens();
576 if (isa<ObjCPropertyRefExpr>(Val: Base))
577 return Cl::CL_SubObjCPropertySetting;
578 return ClassifyInternal(Ctx, E: Base);
579 }
580
581 NamedDecl *Member = E->getMemberDecl();
582 // C++ [expr.ref]p3: E1->E2 is converted to the equivalent form (*(E1)).E2.
583 // C++ [expr.ref]p4: If E2 is declared to have type "reference to T", then
584 // E1.E2 is an lvalue.
585 if (const auto *Value = dyn_cast<ValueDecl>(Val: Member))
586 if (Value->getType()->isReferenceType())
587 return Cl::CL_LValue;
588
589 // Otherwise, one of the following rules applies.
590 // -- If E2 is a static member [...] then E1.E2 is an lvalue.
591 if (isa<VarDecl>(Val: Member) && Member->getDeclContext()->isRecord())
592 return Cl::CL_LValue;
593
594 // -- If E2 is a non-static data member [...]. If E1 is an lvalue, then
595 // E1.E2 is an lvalue; if E1 is an xvalue, then E1.E2 is an xvalue;
596 // otherwise, it is a prvalue.
597 if (isa<FieldDecl>(Val: Member)) {
598 // *E1 is an lvalue
599 if (E->isArrow())
600 return Cl::CL_LValue;
601 Expr *Base = E->getBase()->IgnoreParenImpCasts();
602 if (isa<ObjCPropertyRefExpr>(Val: Base))
603 return Cl::CL_SubObjCPropertySetting;
604 return ClassifyInternal(Ctx, E: E->getBase());
605 }
606
607 // -- If E2 is a [...] member function, [...]
608 // -- If it refers to a static member function [...], then E1.E2 is an
609 // lvalue; [...]
610 // -- Otherwise [...] E1.E2 is a prvalue.
611 if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: Member)) {
612 if (Method->isStatic())
613 return Cl::CL_LValue;
614 if (Method->isImplicitObjectMemberFunction())
615 return Cl::CL_MemberFunction;
616 return Cl::CL_PRValue;
617 }
618
619 // -- If E2 is a member enumerator [...], the expression E1.E2 is a prvalue.
620 // So is everything else we haven't handled yet.
621 return Cl::CL_PRValue;
622}
623
624static Cl::Kinds ClassifyBinaryOp(ASTContext &Ctx, const BinaryOperator *E) {
625 assert(Ctx.getLangOpts().CPlusPlus &&
626 "This is only relevant for C++.");
627
628 // For binary operators which are unknown due to type dependence, use the
629 // value kind assigned when the expression was created. Dependent assignment
630 // expressions can be either lvalues or prvalues depending on whether they
631 // might resolve to an overloaded operator.
632 if (E->getType() == Ctx.DependentTy)
633 return ClassifyExprValueKind(Lang: Ctx.getLangOpts(), E, Kind: E->getValueKind());
634
635 // C++ [expr.ass]p1: All [...] return an lvalue referring to the left operand.
636 // Except we override this for writes to ObjC properties.
637 if (E->isAssignmentOp())
638 return (E->getLHS()->getObjectKind() == OK_ObjCProperty
639 ? Cl::CL_PRValue : Cl::CL_LValue);
640
641 // C++ [expr.comma]p1: the result is of the same value category as its right
642 // operand, [...].
643 if (E->getOpcode() == BO_Comma)
644 return ClassifyInternal(Ctx, E: E->getRHS());
645
646 // C++ [expr.mptr.oper]p6: The result of a .* expression whose second operand
647 // is a pointer to a data member is of the same value category as its first
648 // operand.
649 if (E->getOpcode() == BO_PtrMemD)
650 return (E->getType()->isFunctionType() ||
651 E->hasPlaceholderType(K: BuiltinType::BoundMember))
652 ? Cl::CL_MemberFunction
653 : ClassifyInternal(Ctx, E: E->getLHS());
654
655 // C++ [expr.mptr.oper]p6: The result of an ->* expression is an lvalue if its
656 // second operand is a pointer to data member and a prvalue otherwise.
657 if (E->getOpcode() == BO_PtrMemI)
658 return (E->getType()->isFunctionType() ||
659 E->hasPlaceholderType(K: BuiltinType::BoundMember))
660 ? Cl::CL_MemberFunction
661 : Cl::CL_LValue;
662
663 // All other binary operations are prvalues.
664 return Cl::CL_PRValue;
665}
666
667static Cl::Kinds ClassifyConditional(ASTContext &Ctx, const Expr *True,
668 const Expr *False) {
669 assert(Ctx.getLangOpts().CPlusPlus &&
670 "This is only relevant for C++.");
671
672 // C++ [expr.cond]p2
673 // If either the second or the third operand has type (cv) void,
674 // one of the following shall hold:
675 if (True->getType()->isVoidType() || False->getType()->isVoidType()) {
676 // The second or the third operand (but not both) is a (possibly
677 // parenthesized) throw-expression; the result is of the [...] value
678 // category of the other.
679 bool TrueIsThrow = isa<CXXThrowExpr>(Val: True->IgnoreParenImpCasts());
680 bool FalseIsThrow = isa<CXXThrowExpr>(Val: False->IgnoreParenImpCasts());
681 if (const Expr *NonThrow = TrueIsThrow ? (FalseIsThrow ? nullptr : False)
682 : (FalseIsThrow ? True : nullptr))
683 return ClassifyInternal(Ctx, E: NonThrow);
684
685 // [Otherwise] the result [...] is a prvalue.
686 return Cl::CL_PRValue;
687 }
688
689 // Note that at this point, we have already performed all conversions
690 // according to [expr.cond]p3.
691 // C++ [expr.cond]p4: If the second and third operands are glvalues of the
692 // same value category [...], the result is of that [...] value category.
693 // C++ [expr.cond]p5: Otherwise, the result is a prvalue.
694 Cl::Kinds LCl = ClassifyInternal(Ctx, E: True),
695 RCl = ClassifyInternal(Ctx, E: False);
696 return LCl == RCl ? LCl : Cl::CL_PRValue;
697}
698
699static Cl::ModifiableType IsModifiable(ASTContext &Ctx, const Expr *E,
700 Cl::Kinds Kind, SourceLocation &Loc) {
701 // As a general rule, we only care about lvalues. But there are some rvalues
702 // for which we want to generate special results.
703 if (Kind == Cl::CL_PRValue) {
704 // For the sake of better diagnostics, we want to specifically recognize
705 // use of the GCC cast-as-lvalue extension.
706 if (const auto *CE = dyn_cast<ExplicitCastExpr>(Val: E->IgnoreParens())) {
707 if (CE->getSubExpr()->IgnoreParenImpCasts()->isLValue()) {
708 Loc = CE->getExprLoc();
709 return Cl::CM_LValueCast;
710 }
711 }
712 }
713 if (Kind != Cl::CL_LValue)
714 return Cl::CM_RValue;
715
716 // This is the lvalue case.
717 // Functions are lvalues in C++, but not modifiable. (C++ [basic.lval]p6)
718 if (Ctx.getLangOpts().CPlusPlus && E->getType()->isFunctionType())
719 return Cl::CM_Function;
720
721 // Assignment to a property in ObjC is an implicit setter access. But a
722 // setter might not exist.
723 if (const auto *Expr = dyn_cast<ObjCPropertyRefExpr>(Val: E)) {
724 if (Expr->isImplicitProperty() &&
725 Expr->getImplicitPropertySetter() == nullptr)
726 return Cl::CM_NoSetterProperty;
727 }
728
729 CanQualType CT = Ctx.getCanonicalType(T: E->getType());
730 // Const stuff is obviously not modifiable.
731 if (CT.isConstQualified())
732 return Cl::CM_ConstQualified;
733 if (Ctx.getLangOpts().OpenCL &&
734 CT.getQualifiers().getAddressSpace() == LangAS::opencl_constant)
735 return Cl::CM_ConstAddrSpace;
736
737 // Arrays are not modifiable, only their elements are.
738 if (CT->isArrayType() &&
739 !(Ctx.getLangOpts().HLSL && CT->isConstantArrayType()))
740 return Cl::CM_ArrayType;
741 // Incomplete types are not modifiable.
742 if (CT->isIncompleteType())
743 return Cl::CM_IncompleteType;
744
745 // Records with any const fields (recursively) are not modifiable.
746 if (const RecordType *R = CT->getAs<RecordType>())
747 if (R->hasConstFields())
748 return Cl::CM_ConstQualifiedField;
749
750 return Cl::CM_Modifiable;
751}
752
753Expr::LValueClassification Expr::ClassifyLValue(ASTContext &Ctx) const {
754 Classification VC = Classify(Ctx);
755 switch (VC.getKind()) {
756 case Cl::CL_LValue: return LV_Valid;
757 case Cl::CL_XValue: return LV_InvalidExpression;
758 case Cl::CL_Function: return LV_NotObjectType;
759 case Cl::CL_Void: return LV_InvalidExpression;
760 case Cl::CL_AddressableVoid: return LV_IncompleteVoidType;
761 case Cl::CL_DuplicateVectorComponents: return LV_DuplicateVectorComponents;
762 case Cl::CL_DuplicateMatrixComponents:
763 return LV_DuplicateMatrixComponents;
764 case Cl::CL_MemberFunction: return LV_MemberFunction;
765 case Cl::CL_SubObjCPropertySetting: return LV_SubObjCPropertySetting;
766 case Cl::CL_ClassTemporary: return LV_ClassTemporary;
767 case Cl::CL_ArrayTemporary: return LV_ArrayTemporary;
768 case Cl::CL_ObjCMessageRValue: return LV_InvalidMessageExpression;
769 case Cl::CL_PRValue: return LV_InvalidExpression;
770 }
771 llvm_unreachable("Unhandled kind");
772}
773
774Expr::isModifiableLvalueResult
775Expr::isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc) const {
776 SourceLocation dummy;
777 Classification VC = ClassifyModifiable(Ctx, Loc&: Loc ? *Loc : dummy);
778 switch (VC.getKind()) {
779 case Cl::CL_LValue: break;
780 case Cl::CL_XValue: return MLV_InvalidExpression;
781 case Cl::CL_Function: return MLV_NotObjectType;
782 case Cl::CL_Void: return MLV_InvalidExpression;
783 case Cl::CL_AddressableVoid: return MLV_IncompleteVoidType;
784 case Cl::CL_DuplicateVectorComponents: return MLV_DuplicateVectorComponents;
785 case Cl::CL_DuplicateMatrixComponents:
786 return MLV_DuplicateMatrixComponents;
787 case Cl::CL_MemberFunction: return MLV_MemberFunction;
788 case Cl::CL_SubObjCPropertySetting: return MLV_SubObjCPropertySetting;
789 case Cl::CL_ClassTemporary: return MLV_ClassTemporary;
790 case Cl::CL_ArrayTemporary: return MLV_ArrayTemporary;
791 case Cl::CL_ObjCMessageRValue: return MLV_InvalidMessageExpression;
792 case Cl::CL_PRValue:
793 return VC.getModifiable() == Cl::CM_LValueCast ?
794 MLV_LValueCast : MLV_InvalidExpression;
795 }
796 assert(VC.getKind() == Cl::CL_LValue && "Unhandled kind");
797 switch (VC.getModifiable()) {
798 case Cl::CM_Untested: llvm_unreachable("Did not test modifiability");
799 case Cl::CM_Modifiable: return MLV_Valid;
800 case Cl::CM_RValue: llvm_unreachable("CM_RValue and CL_LValue don't match");
801 case Cl::CM_Function: return MLV_NotObjectType;
802 case Cl::CM_LValueCast:
803 llvm_unreachable("CM_LValueCast and CL_LValue don't match");
804 case Cl::CM_NoSetterProperty: return MLV_NoSetterProperty;
805 case Cl::CM_ConstQualified: return MLV_ConstQualified;
806 case Cl::CM_ConstQualifiedField: return MLV_ConstQualifiedField;
807 case Cl::CM_ConstAddrSpace: return MLV_ConstAddrSpace;
808 case Cl::CM_ArrayType: return MLV_ArrayType;
809 case Cl::CM_IncompleteType: return MLV_IncompleteType;
810 }
811 llvm_unreachable("Unhandled modifiable type");
812}
813