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 Expr *Op = cast<UnaryOperator>(Val: E)->getSubExpr()->IgnoreParens();
302 Cl::Kinds K = ClassifyInternal(Ctx, E: Op);
303 if (K != Cl::CL_LValue) return K;
304
305 if (isa<ObjCPropertyRefExpr>(Val: Op))
306 return Cl::CL_SubObjCPropertySetting;
307 return Cl::CL_LValue;
308 }
309
310 // C++ [expr.pre.incr]p1: The result is the updated operand; it is an
311 // lvalue, [...]
312 // Not so in C.
313 case UO_PreInc:
314 case UO_PreDec:
315 return Lang.CPlusPlus ? Cl::CL_LValue : Cl::CL_PRValue;
316
317 default:
318 return Cl::CL_PRValue;
319 }
320
321 case Expr::RecoveryExprClass:
322 case Expr::OpaqueValueExprClass:
323 return ClassifyExprValueKind(Lang, E, Kind: E->getValueKind());
324
325 // Pseudo-object expressions can produce l-values with reference magic.
326 case Expr::PseudoObjectExprClass:
327 return ClassifyExprValueKind(Lang, E,
328 Kind: cast<PseudoObjectExpr>(Val: E)->getValueKind());
329
330 // Implicit casts are lvalues if they're lvalue casts. Other than that, we
331 // only specifically record class temporaries.
332 case Expr::ImplicitCastExprClass:
333 return ClassifyExprValueKind(Lang, E, Kind: E->getValueKind());
334
335 // C++ [expr.prim.general]p4: The presence of parentheses does not affect
336 // whether the expression is an lvalue.
337 case Expr::ParenExprClass:
338 return ClassifyInternal(Ctx, E: cast<ParenExpr>(Val: E)->getSubExpr());
339
340 // C11 6.5.1.1p4: [A generic selection] is an lvalue, a function designator,
341 // or a void expression if its result expression is, respectively, an
342 // lvalue, a function designator, or a void expression.
343 case Expr::GenericSelectionExprClass:
344 if (cast<GenericSelectionExpr>(Val: E)->isResultDependent())
345 return Cl::CL_PRValue;
346 return ClassifyInternal(Ctx,E: cast<GenericSelectionExpr>(Val: E)->getResultExpr());
347
348 case Expr::BinaryOperatorClass:
349 case Expr::CompoundAssignOperatorClass:
350 // C doesn't have any binary expressions that are lvalues.
351 if (Lang.CPlusPlus)
352 return ClassifyBinaryOp(Ctx, E: cast<BinaryOperator>(Val: E));
353 return Cl::CL_PRValue;
354
355 case Expr::CallExprClass:
356 case Expr::CXXOperatorCallExprClass:
357 case Expr::CXXMemberCallExprClass:
358 case Expr::UserDefinedLiteralClass:
359 case Expr::CUDAKernelCallExprClass:
360 return ClassifyUnnamed(Ctx, T: cast<CallExpr>(Val: E)->getCallReturnType(Ctx));
361
362 case Expr::CXXRewrittenBinaryOperatorClass:
363 return ClassifyInternal(
364 Ctx, E: cast<CXXRewrittenBinaryOperator>(Val: E)->getSemanticForm());
365
366 // __builtin_choose_expr is equivalent to the chosen expression.
367 case Expr::ChooseExprClass:
368 return ClassifyInternal(Ctx, E: cast<ChooseExpr>(Val: E)->getChosenSubExpr());
369
370 // Extended vector element access is an lvalue unless there are duplicates
371 // in the shuffle expression.
372 case Expr::ExtVectorElementExprClass:
373 if (cast<ExtVectorElementExpr>(Val: E)->containsDuplicateElements())
374 return Cl::CL_DuplicateVectorComponents;
375 if (cast<ExtVectorElementExpr>(Val: E)->isArrow())
376 return Cl::CL_LValue;
377 return ClassifyInternal(Ctx, E: cast<ExtVectorElementExpr>(Val: E)->getBase());
378
379 // Matrix element access is an lvalue unless there are duplicates
380 // in the shuffle expression.
381 case Expr::MatrixElementExprClass:
382 if (cast<MatrixElementExpr>(Val: E)->containsDuplicateElements())
383 return Cl::CL_DuplicateMatrixComponents;
384 // NOTE: MatrixElementExpr is currently only used by HLSL which does not
385 // have pointers so there is no isArrow() necessary or way to test
386 // Cl::CL_LValue
387 return ClassifyInternal(Ctx, E: cast<MatrixElementExpr>(Val: E)->getBase());
388
389 // Simply look at the actual default argument.
390 case Expr::CXXDefaultArgExprClass:
391 return ClassifyInternal(Ctx, E: cast<CXXDefaultArgExpr>(Val: E)->getExpr());
392
393 // Same idea for default initializers.
394 case Expr::CXXDefaultInitExprClass:
395 return ClassifyInternal(Ctx, E: cast<CXXDefaultInitExpr>(Val: E)->getExpr());
396
397 // Same idea for temporary binding.
398 case Expr::CXXBindTemporaryExprClass:
399 return ClassifyInternal(Ctx, E: cast<CXXBindTemporaryExpr>(Val: E)->getSubExpr());
400
401 // And the cleanups guard.
402 case Expr::ExprWithCleanupsClass:
403 return ClassifyInternal(Ctx, E: cast<ExprWithCleanups>(Val: E)->getSubExpr());
404
405 // Casts depend completely on the target type. All casts work the same.
406 case Expr::CStyleCastExprClass:
407 case Expr::CXXFunctionalCastExprClass:
408 case Expr::CXXStaticCastExprClass:
409 case Expr::CXXDynamicCastExprClass:
410 case Expr::CXXReinterpretCastExprClass:
411 case Expr::CXXConstCastExprClass:
412 case Expr::CXXAddrspaceCastExprClass:
413 case Expr::ObjCBridgedCastExprClass:
414 case Expr::BuiltinBitCastExprClass:
415 // Only in C++ can casts be interesting at all.
416 if (!Lang.CPlusPlus) return Cl::CL_PRValue;
417 return ClassifyUnnamed(Ctx, T: cast<ExplicitCastExpr>(Val: E)->getTypeAsWritten());
418
419 case Expr::CXXUnresolvedConstructExprClass:
420 return ClassifyUnnamed(Ctx,
421 T: cast<CXXUnresolvedConstructExpr>(Val: E)->getTypeAsWritten());
422
423 case Expr::BinaryConditionalOperatorClass: {
424 if (!Lang.CPlusPlus) return Cl::CL_PRValue;
425 const auto *co = cast<BinaryConditionalOperator>(Val: E);
426 return ClassifyConditional(Ctx, trueExpr: co->getTrueExpr(), falseExpr: co->getFalseExpr());
427 }
428
429 case Expr::ConditionalOperatorClass: {
430 // Once again, only C++ is interesting.
431 if (!Lang.CPlusPlus) return Cl::CL_PRValue;
432 const auto *co = cast<ConditionalOperator>(Val: E);
433 return ClassifyConditional(Ctx, trueExpr: co->getTrueExpr(), falseExpr: co->getFalseExpr());
434 }
435
436 // ObjC message sends are effectively function calls, if the target function
437 // is known.
438 case Expr::ObjCMessageExprClass:
439 if (const ObjCMethodDecl *Method =
440 cast<ObjCMessageExpr>(Val: E)->getMethodDecl()) {
441 Cl::Kinds kind = ClassifyUnnamed(Ctx, T: Method->getReturnType());
442 return (kind == Cl::CL_PRValue) ? Cl::CL_ObjCMessageRValue : kind;
443 }
444 return Cl::CL_PRValue;
445
446 // Some C++ expressions are always class temporaries.
447 case Expr::CXXConstructExprClass:
448 case Expr::CXXInheritedCtorInitExprClass:
449 case Expr::CXXTemporaryObjectExprClass:
450 case Expr::LambdaExprClass:
451 case Expr::CXXStdInitializerListExprClass:
452 return Cl::CL_ClassTemporary;
453
454 case Expr::VAArgExprClass:
455 return ClassifyUnnamed(Ctx, T: E->getType());
456
457 case Expr::DesignatedInitExprClass:
458 return ClassifyInternal(Ctx, E: cast<DesignatedInitExpr>(Val: E)->getInit());
459
460 case Expr::StmtExprClass: {
461 const CompoundStmt *S = cast<StmtExpr>(Val: E)->getSubStmt();
462 if (const auto *LastExpr = dyn_cast_or_null<Expr>(Val: S->body_back()))
463 return ClassifyUnnamed(Ctx, T: LastExpr->getType());
464 return Cl::CL_PRValue;
465 }
466
467 case Expr::PackExpansionExprClass:
468 return ClassifyInternal(Ctx, E: cast<PackExpansionExpr>(Val: E)->getPattern());
469
470 case Expr::MaterializeTemporaryExprClass:
471 return cast<MaterializeTemporaryExpr>(Val: E)->isBoundToLvalueReference()
472 ? Cl::CL_LValue
473 : Cl::CL_XValue;
474
475 case Expr::InitListExprClass:
476 // An init list can be an lvalue if it is bound to a reference and
477 // contains only one element. In that case, we look at that element
478 // for an exact classification. Init list creation takes care of the
479 // value kind for us, so we only need to fine-tune.
480 if (E->isPRValue())
481 return ClassifyExprValueKind(Lang, E, Kind: E->getValueKind());
482 assert(cast<InitListExpr>(E)->getNumInits() == 1 &&
483 "Only 1-element init lists can be glvalues.");
484 return ClassifyInternal(Ctx, E: cast<InitListExpr>(Val: E)->getInit(Init: 0));
485
486 case Expr::CoawaitExprClass:
487 case Expr::CoyieldExprClass:
488 return ClassifyInternal(Ctx, E: cast<CoroutineSuspendExpr>(Val: E)->getResumeExpr());
489 case Expr::SYCLUniqueStableNameExprClass:
490 case Expr::OpenACCAsteriskSizeExprClass:
491 return Cl::CL_PRValue;
492 break;
493
494 case Expr::CXXParenListInitExprClass:
495 if (isa<ArrayType>(Val: E->getType()))
496 return Cl::CL_ArrayTemporary;
497 return Cl::CL_ClassTemporary;
498 }
499
500 llvm_unreachable("unhandled expression kind in classification");
501}
502
503/// ClassifyDecl - Return the classification of an expression referencing the
504/// given declaration.
505static Cl::Kinds ClassifyDecl(ASTContext &Ctx, const Decl *D) {
506 // C++ [expr.prim.id.unqual]p3: The result is an lvalue if the entity is a
507 // function, variable, or data member, or a template parameter object and a
508 // prvalue otherwise.
509 // In C, functions are not lvalues.
510 // In addition, NonTypeTemplateParmDecl derives from VarDecl but isn't an
511 // lvalue unless it's a reference type or a class type (C++ [temp.param]p8),
512 // so we need to special-case this.
513
514 if (const auto *M = dyn_cast<CXXMethodDecl>(Val: D)) {
515 if (M->isImplicitObjectMemberFunction())
516 return Cl::CL_MemberFunction;
517 if (M->isStatic())
518 return Cl::CL_LValue;
519 return Cl::CL_PRValue;
520 }
521
522 bool islvalue;
523 if (const auto *NTTParm = dyn_cast<NonTypeTemplateParmDecl>(Val: D))
524 islvalue = NTTParm->getType()->isReferenceType() ||
525 NTTParm->getType()->isRecordType();
526 else
527 islvalue =
528 isa<VarDecl, FieldDecl, IndirectFieldDecl, BindingDecl, MSGuidDecl,
529 UnnamedGlobalConstantDecl, TemplateParamObjectDecl>(Val: D) ||
530 (Ctx.getLangOpts().CPlusPlus &&
531 (isa<FunctionDecl, MSPropertyDecl, FunctionTemplateDecl>(Val: D)));
532
533 return islvalue ? Cl::CL_LValue : Cl::CL_PRValue;
534}
535
536/// ClassifyUnnamed - Return the classification of an expression yielding an
537/// unnamed value of the given type. This applies in particular to function
538/// calls and casts.
539static Cl::Kinds ClassifyUnnamed(ASTContext &Ctx, QualType T) {
540 // In C, function calls are always rvalues.
541 if (!Ctx.getLangOpts().CPlusPlus) return Cl::CL_PRValue;
542
543 // C++ [expr.call]p10: A function call is an lvalue if the result type is an
544 // lvalue reference type or an rvalue reference to function type, an xvalue
545 // if the result type is an rvalue reference to object type, and a prvalue
546 // otherwise.
547 if (T->isLValueReferenceType())
548 return Cl::CL_LValue;
549 const auto *RV = T->getAs<RValueReferenceType>();
550 if (!RV) // Could still be a class temporary, though.
551 return ClassifyTemporary(T);
552
553 return RV->getPointeeType()->isFunctionType() ? Cl::CL_LValue : Cl::CL_XValue;
554}
555
556static Cl::Kinds ClassifyMemberExpr(ASTContext &Ctx, const MemberExpr *E) {
557 if (E->getType() == Ctx.UnknownAnyTy)
558 return (isa<FunctionDecl>(Val: E->getMemberDecl())
559 ? Cl::CL_PRValue : Cl::CL_LValue);
560
561 // Handle C first, it's easier.
562 if (!Ctx.getLangOpts().CPlusPlus) {
563 // C99 6.5.2.3p3
564 // For dot access, the expression is an lvalue if the first part is. For
565 // arrow access, it always is an lvalue.
566 if (E->isArrow())
567 return Cl::CL_LValue;
568 // ObjC property accesses are not lvalues, but get special treatment.
569 Expr *Base = E->getBase()->IgnoreParens();
570 if (isa<ObjCPropertyRefExpr>(Val: Base))
571 return Cl::CL_SubObjCPropertySetting;
572 return ClassifyInternal(Ctx, E: Base);
573 }
574
575 NamedDecl *Member = E->getMemberDecl();
576 // C++ [expr.ref]p3: E1->E2 is converted to the equivalent form (*(E1)).E2.
577 // C++ [expr.ref]p4: If E2 is declared to have type "reference to T", then
578 // E1.E2 is an lvalue.
579 if (const auto *Value = dyn_cast<ValueDecl>(Val: Member))
580 if (Value->getType()->isReferenceType())
581 return Cl::CL_LValue;
582
583 // Otherwise, one of the following rules applies.
584 // -- If E2 is a static member [...] then E1.E2 is an lvalue.
585 if (isa<VarDecl>(Val: Member) && Member->getDeclContext()->isRecord())
586 return Cl::CL_LValue;
587
588 // -- If E2 is a non-static data member [...]. If E1 is an lvalue, then
589 // E1.E2 is an lvalue; if E1 is an xvalue, then E1.E2 is an xvalue;
590 // otherwise, it is a prvalue.
591 if (isa<FieldDecl>(Val: Member)) {
592 // *E1 is an lvalue
593 if (E->isArrow())
594 return Cl::CL_LValue;
595 Expr *Base = E->getBase()->IgnoreParenImpCasts();
596 if (isa<ObjCPropertyRefExpr>(Val: Base))
597 return Cl::CL_SubObjCPropertySetting;
598 return ClassifyInternal(Ctx, E: E->getBase());
599 }
600
601 // -- If E2 is a [...] member function, [...]
602 // -- If it refers to a static member function [...], then E1.E2 is an
603 // lvalue; [...]
604 // -- Otherwise [...] E1.E2 is a prvalue.
605 if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: Member)) {
606 if (Method->isStatic())
607 return Cl::CL_LValue;
608 if (Method->isImplicitObjectMemberFunction())
609 return Cl::CL_MemberFunction;
610 return Cl::CL_PRValue;
611 }
612
613 // -- If E2 is a member enumerator [...], the expression E1.E2 is a prvalue.
614 // So is everything else we haven't handled yet.
615 return Cl::CL_PRValue;
616}
617
618static Cl::Kinds ClassifyBinaryOp(ASTContext &Ctx, const BinaryOperator *E) {
619 assert(Ctx.getLangOpts().CPlusPlus &&
620 "This is only relevant for C++.");
621
622 // For binary operators which are unknown due to type dependence, use the
623 // value kind assigned when the expression was created. Dependent assignment
624 // expressions can be either lvalues or prvalues depending on whether they
625 // might resolve to an overloaded operator.
626 if (E->getType() == Ctx.DependentTy)
627 return ClassifyExprValueKind(Lang: Ctx.getLangOpts(), E, Kind: E->getValueKind());
628
629 // C++ [expr.ass]p1: All [...] return an lvalue referring to the left operand.
630 // Except we override this for writes to ObjC properties.
631 if (E->isAssignmentOp())
632 return (E->getLHS()->getObjectKind() == OK_ObjCProperty
633 ? Cl::CL_PRValue : Cl::CL_LValue);
634
635 // C++ [expr.comma]p1: the result is of the same value category as its right
636 // operand, [...].
637 if (E->getOpcode() == BO_Comma)
638 return ClassifyInternal(Ctx, E: E->getRHS());
639
640 // C++ [expr.mptr.oper]p6: The result of a .* expression whose second operand
641 // is a pointer to a data member is of the same value category as its first
642 // operand.
643 if (E->getOpcode() == BO_PtrMemD)
644 return (E->getType()->isFunctionType() ||
645 E->hasPlaceholderType(K: BuiltinType::BoundMember))
646 ? Cl::CL_MemberFunction
647 : ClassifyInternal(Ctx, E: E->getLHS());
648
649 // C++ [expr.mptr.oper]p6: The result of an ->* expression is an lvalue if its
650 // second operand is a pointer to data member and a prvalue otherwise.
651 if (E->getOpcode() == BO_PtrMemI)
652 return (E->getType()->isFunctionType() ||
653 E->hasPlaceholderType(K: BuiltinType::BoundMember))
654 ? Cl::CL_MemberFunction
655 : Cl::CL_LValue;
656
657 // All other binary operations are prvalues.
658 return Cl::CL_PRValue;
659}
660
661static Cl::Kinds ClassifyConditional(ASTContext &Ctx, const Expr *True,
662 const Expr *False) {
663 assert(Ctx.getLangOpts().CPlusPlus &&
664 "This is only relevant for C++.");
665
666 // C++ [expr.cond]p2
667 // If either the second or the third operand has type (cv) void,
668 // one of the following shall hold:
669 if (True->getType()->isVoidType() || False->getType()->isVoidType()) {
670 // The second or the third operand (but not both) is a (possibly
671 // parenthesized) throw-expression; the result is of the [...] value
672 // category of the other.
673 bool TrueIsThrow = isa<CXXThrowExpr>(Val: True->IgnoreParenImpCasts());
674 bool FalseIsThrow = isa<CXXThrowExpr>(Val: False->IgnoreParenImpCasts());
675 if (const Expr *NonThrow = TrueIsThrow ? (FalseIsThrow ? nullptr : False)
676 : (FalseIsThrow ? True : nullptr))
677 return ClassifyInternal(Ctx, E: NonThrow);
678
679 // [Otherwise] the result [...] is a prvalue.
680 return Cl::CL_PRValue;
681 }
682
683 // Note that at this point, we have already performed all conversions
684 // according to [expr.cond]p3.
685 // C++ [expr.cond]p4: If the second and third operands are glvalues of the
686 // same value category [...], the result is of that [...] value category.
687 // C++ [expr.cond]p5: Otherwise, the result is a prvalue.
688 Cl::Kinds LCl = ClassifyInternal(Ctx, E: True),
689 RCl = ClassifyInternal(Ctx, E: False);
690 return LCl == RCl ? LCl : Cl::CL_PRValue;
691}
692
693static Cl::ModifiableType IsModifiable(ASTContext &Ctx, const Expr *E,
694 Cl::Kinds Kind, SourceLocation &Loc) {
695 // As a general rule, we only care about lvalues. But there are some rvalues
696 // for which we want to generate special results.
697 if (Kind == Cl::CL_PRValue) {
698 // For the sake of better diagnostics, we want to specifically recognize
699 // use of the GCC cast-as-lvalue extension.
700 if (const auto *CE = dyn_cast<ExplicitCastExpr>(Val: E->IgnoreParens())) {
701 if (CE->getSubExpr()->IgnoreParenImpCasts()->isLValue()) {
702 Loc = CE->getExprLoc();
703 return Cl::CM_LValueCast;
704 }
705 }
706 }
707 if (Kind != Cl::CL_LValue)
708 return Cl::CM_RValue;
709
710 // This is the lvalue case.
711 // Functions are lvalues in C++, but not modifiable. (C++ [basic.lval]p6)
712 if (Ctx.getLangOpts().CPlusPlus && E->getType()->isFunctionType())
713 return Cl::CM_Function;
714
715 // Assignment to a property in ObjC is an implicit setter access. But a
716 // setter might not exist.
717 if (const auto *Expr = dyn_cast<ObjCPropertyRefExpr>(Val: E)) {
718 if (Expr->isImplicitProperty() &&
719 Expr->getImplicitPropertySetter() == nullptr)
720 return Cl::CM_NoSetterProperty;
721 }
722
723 CanQualType CT = Ctx.getCanonicalType(T: E->getType());
724 // Const stuff is obviously not modifiable.
725 if (CT.isConstQualified())
726 return Cl::CM_ConstQualified;
727 if (Ctx.getLangOpts().OpenCL &&
728 CT.getQualifiers().getAddressSpace() == LangAS::opencl_constant)
729 return Cl::CM_ConstAddrSpace;
730
731 // Arrays are not modifiable, only their elements are.
732 if (CT->isArrayType() &&
733 !(Ctx.getLangOpts().HLSL && CT->isConstantArrayType()))
734 return Cl::CM_ArrayType;
735 // Incomplete types are not modifiable.
736 if (CT->isIncompleteType())
737 return Cl::CM_IncompleteType;
738
739 // Records with any const fields (recursively) are not modifiable.
740 if (const RecordType *R = CT->getAs<RecordType>())
741 if (R->hasConstFields())
742 return Cl::CM_ConstQualifiedField;
743
744 return Cl::CM_Modifiable;
745}
746
747Expr::LValueClassification Expr::ClassifyLValue(ASTContext &Ctx) const {
748 Classification VC = Classify(Ctx);
749 switch (VC.getKind()) {
750 case Cl::CL_LValue: return LV_Valid;
751 case Cl::CL_XValue: return LV_InvalidExpression;
752 case Cl::CL_Function: return LV_NotObjectType;
753 case Cl::CL_Void: return LV_InvalidExpression;
754 case Cl::CL_AddressableVoid: return LV_IncompleteVoidType;
755 case Cl::CL_DuplicateVectorComponents: return LV_DuplicateVectorComponents;
756 case Cl::CL_DuplicateMatrixComponents:
757 return LV_DuplicateMatrixComponents;
758 case Cl::CL_MemberFunction: return LV_MemberFunction;
759 case Cl::CL_SubObjCPropertySetting: return LV_SubObjCPropertySetting;
760 case Cl::CL_ClassTemporary: return LV_ClassTemporary;
761 case Cl::CL_ArrayTemporary: return LV_ArrayTemporary;
762 case Cl::CL_ObjCMessageRValue: return LV_InvalidMessageExpression;
763 case Cl::CL_PRValue: return LV_InvalidExpression;
764 }
765 llvm_unreachable("Unhandled kind");
766}
767
768Expr::isModifiableLvalueResult
769Expr::isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc) const {
770 SourceLocation dummy;
771 Classification VC = ClassifyModifiable(Ctx, Loc&: Loc ? *Loc : dummy);
772 switch (VC.getKind()) {
773 case Cl::CL_LValue: break;
774 case Cl::CL_XValue: return MLV_InvalidExpression;
775 case Cl::CL_Function: return MLV_NotObjectType;
776 case Cl::CL_Void: return MLV_InvalidExpression;
777 case Cl::CL_AddressableVoid: return MLV_IncompleteVoidType;
778 case Cl::CL_DuplicateVectorComponents: return MLV_DuplicateVectorComponents;
779 case Cl::CL_DuplicateMatrixComponents:
780 return MLV_DuplicateMatrixComponents;
781 case Cl::CL_MemberFunction: return MLV_MemberFunction;
782 case Cl::CL_SubObjCPropertySetting: return MLV_SubObjCPropertySetting;
783 case Cl::CL_ClassTemporary: return MLV_ClassTemporary;
784 case Cl::CL_ArrayTemporary: return MLV_ArrayTemporary;
785 case Cl::CL_ObjCMessageRValue: return MLV_InvalidMessageExpression;
786 case Cl::CL_PRValue:
787 return VC.getModifiable() == Cl::CM_LValueCast ?
788 MLV_LValueCast : MLV_InvalidExpression;
789 }
790 assert(VC.getKind() == Cl::CL_LValue && "Unhandled kind");
791 switch (VC.getModifiable()) {
792 case Cl::CM_Untested: llvm_unreachable("Did not test modifiability");
793 case Cl::CM_Modifiable: return MLV_Valid;
794 case Cl::CM_RValue: llvm_unreachable("CM_RValue and CL_LValue don't match");
795 case Cl::CM_Function: return MLV_NotObjectType;
796 case Cl::CM_LValueCast:
797 llvm_unreachable("CM_LValueCast and CL_LValue don't match");
798 case Cl::CM_NoSetterProperty: return MLV_NoSetterProperty;
799 case Cl::CM_ConstQualified: return MLV_ConstQualified;
800 case Cl::CM_ConstQualifiedField: return MLV_ConstQualifiedField;
801 case Cl::CM_ConstAddrSpace: return MLV_ConstAddrSpace;
802 case Cl::CM_ArrayType: return MLV_ArrayType;
803 case Cl::CM_IncompleteType: return MLV_IncompleteType;
804 }
805 llvm_unreachable("Unhandled modifiable type");
806}
807