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