1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the Expr constant evaluator.
11 // Constant expression evaluation produces four main results:
13 // * A success/failure flag indicating whether constant folding was successful.
14 // This is the 'bool' return value used by most of the code in this file. A
15 // 'false' return value indicates that constant folding has failed, and any
16 // appropriate diagnostic has already been produced.
18 // * An evaluated result, valid only if constant folding has not failed.
20 // * A flag indicating if evaluation encountered (unevaluated) side-effects.
21 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22 // where it is possible to determine the evaluated result regardless.
24 // * A set of notes indicating why the evaluation was not a constant expression
25 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26 // too, why the expression could not be folded.
28 // If we are checking for a potential constant expression, failure to constant
29 // fold a potential constant sub-expression will be indicated by a 'false'
30 // return value (the expression could not be folded) and no diagnostic (the
31 // expression is not necessarily non-constant).
33 //===----------------------------------------------------------------------===//
35 #include "Interp/Context.h"
36 #include "Interp/Frame.h"
37 #include "Interp/State.h"
38 #include "clang/AST/APValue.h"
39 #include "clang/AST/ASTContext.h"
40 #include "clang/AST/ASTDiagnostic.h"
41 #include "clang/AST/ASTLambda.h"
42 #include "clang/AST/Attr.h"
43 #include "clang/AST/CXXInheritance.h"
44 #include "clang/AST/CharUnits.h"
45 #include "clang/AST/CurrentSourceLocExprScope.h"
46 #include "clang/AST/Expr.h"
47 #include "clang/AST/OSLog.h"
48 #include "clang/AST/OptionalDiagnostic.h"
49 #include "clang/AST/RecordLayout.h"
50 #include "clang/AST/StmtVisitor.h"
51 #include "clang/AST/TypeLoc.h"
52 #include "clang/Basic/Builtins.h"
53 #include "clang/Basic/DiagnosticSema.h"
54 #include "clang/Basic/TargetInfo.h"
55 #include "llvm/ADT/APFixedPoint.h"
56 #include "llvm/ADT/SmallBitVector.h"
57 #include "llvm/ADT/StringExtras.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Support/SaveAndRestore.h"
60 #include "llvm/Support/TimeProfiler.h"
61 #include "llvm/Support/raw_ostream.h"
66 #define DEBUG_TYPE "exprconstant"
68 using namespace clang
;
69 using llvm::APFixedPoint
;
73 using llvm::FixedPointSemantics
;
80 using SourceLocExprScopeGuard
=
81 CurrentSourceLocExprScope::SourceLocExprScopeGuard
;
83 static QualType
getType(APValue::LValueBase B
) {
87 /// Get an LValue path entry, which is known to not be an array index, as a
88 /// field declaration.
89 static const FieldDecl
*getAsField(APValue::LValuePathEntry E
) {
90 return dyn_cast_or_null
<FieldDecl
>(E
.getAsBaseOrMember().getPointer());
92 /// Get an LValue path entry, which is known to not be an array index, as a
93 /// base class declaration.
94 static const CXXRecordDecl
*getAsBaseClass(APValue::LValuePathEntry E
) {
95 return dyn_cast_or_null
<CXXRecordDecl
>(E
.getAsBaseOrMember().getPointer());
97 /// Determine whether this LValue path entry for a base class names a virtual
99 static bool isVirtualBaseClass(APValue::LValuePathEntry E
) {
100 return E
.getAsBaseOrMember().getInt();
103 /// Given an expression, determine the type used to store the result of
104 /// evaluating that expression.
105 static QualType
getStorageType(const ASTContext
&Ctx
, const Expr
*E
) {
108 return Ctx
.getLValueReferenceType(E
->getType());
111 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
112 static const AllocSizeAttr
*getAllocSizeAttr(const CallExpr
*CE
) {
113 if (const FunctionDecl
*DirectCallee
= CE
->getDirectCallee())
114 return DirectCallee
->getAttr
<AllocSizeAttr
>();
115 if (const Decl
*IndirectCallee
= CE
->getCalleeDecl())
116 return IndirectCallee
->getAttr
<AllocSizeAttr
>();
120 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
121 /// This will look through a single cast.
123 /// Returns null if we couldn't unwrap a function with alloc_size.
124 static const CallExpr
*tryUnwrapAllocSizeCall(const Expr
*E
) {
125 if (!E
->getType()->isPointerType())
128 E
= E
->IgnoreParens();
129 // If we're doing a variable assignment from e.g. malloc(N), there will
130 // probably be a cast of some kind. In exotic cases, we might also see a
131 // top-level ExprWithCleanups. Ignore them either way.
132 if (const auto *FE
= dyn_cast
<FullExpr
>(E
))
133 E
= FE
->getSubExpr()->IgnoreParens();
135 if (const auto *Cast
= dyn_cast
<CastExpr
>(E
))
136 E
= Cast
->getSubExpr()->IgnoreParens();
138 if (const auto *CE
= dyn_cast
<CallExpr
>(E
))
139 return getAllocSizeAttr(CE
) ? CE
: nullptr;
143 /// Determines whether or not the given Base contains a call to a function
144 /// with the alloc_size attribute.
145 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base
) {
146 const auto *E
= Base
.dyn_cast
<const Expr
*>();
147 return E
&& E
->getType()->isPointerType() && tryUnwrapAllocSizeCall(E
);
150 /// Determines whether the given kind of constant expression is only ever
151 /// used for name mangling. If so, it's permitted to reference things that we
152 /// can't generate code for (in particular, dllimported functions).
153 static bool isForManglingOnly(ConstantExprKind Kind
) {
155 case ConstantExprKind::Normal
:
156 case ConstantExprKind::ClassTemplateArgument
:
157 case ConstantExprKind::ImmediateInvocation
:
158 // Note that non-type template arguments of class type are emitted as
159 // template parameter objects.
162 case ConstantExprKind::NonClassTemplateArgument
:
165 llvm_unreachable("unknown ConstantExprKind");
168 static bool isTemplateArgument(ConstantExprKind Kind
) {
170 case ConstantExprKind::Normal
:
171 case ConstantExprKind::ImmediateInvocation
:
174 case ConstantExprKind::ClassTemplateArgument
:
175 case ConstantExprKind::NonClassTemplateArgument
:
178 llvm_unreachable("unknown ConstantExprKind");
181 /// The bound to claim that an array of unknown bound has.
182 /// The value in MostDerivedArraySize is undefined in this case. So, set it
183 /// to an arbitrary value that's likely to loudly break things if it's used.
184 static const uint64_t AssumedSizeForUnsizedArray
=
185 std::numeric_limits
<uint64_t>::max() / 2;
187 /// Determines if an LValue with the given LValueBase will have an unsized
188 /// array in its designator.
189 /// Find the path length and type of the most-derived subobject in the given
190 /// path, and find the size of the containing array, if any.
192 findMostDerivedSubobject(ASTContext
&Ctx
, APValue::LValueBase Base
,
193 ArrayRef
<APValue::LValuePathEntry
> Path
,
194 uint64_t &ArraySize
, QualType
&Type
, bool &IsArray
,
195 bool &FirstEntryIsUnsizedArray
) {
196 // This only accepts LValueBases from APValues, and APValues don't support
197 // arrays that lack size info.
198 assert(!isBaseAnAllocSizeCall(Base
) &&
199 "Unsized arrays shouldn't appear here");
200 unsigned MostDerivedLength
= 0;
201 Type
= getType(Base
);
203 for (unsigned I
= 0, N
= Path
.size(); I
!= N
; ++I
) {
204 if (Type
->isArrayType()) {
205 const ArrayType
*AT
= Ctx
.getAsArrayType(Type
);
206 Type
= AT
->getElementType();
207 MostDerivedLength
= I
+ 1;
210 if (auto *CAT
= dyn_cast
<ConstantArrayType
>(AT
)) {
211 ArraySize
= CAT
->getSize().getZExtValue();
213 assert(I
== 0 && "unexpected unsized array designator");
214 FirstEntryIsUnsizedArray
= true;
215 ArraySize
= AssumedSizeForUnsizedArray
;
217 } else if (Type
->isAnyComplexType()) {
218 const ComplexType
*CT
= Type
->castAs
<ComplexType
>();
219 Type
= CT
->getElementType();
221 MostDerivedLength
= I
+ 1;
223 } else if (const FieldDecl
*FD
= getAsField(Path
[I
])) {
224 Type
= FD
->getType();
226 MostDerivedLength
= I
+ 1;
229 // Path[I] describes a base class.
234 return MostDerivedLength
;
237 /// A path from a glvalue to a subobject of that glvalue.
238 struct SubobjectDesignator
{
239 /// True if the subobject was named in a manner not supported by C++11. Such
240 /// lvalues can still be folded, but they are not core constant expressions
241 /// and we cannot perform lvalue-to-rvalue conversions on them.
242 unsigned Invalid
: 1;
244 /// Is this a pointer one past the end of an object?
245 unsigned IsOnePastTheEnd
: 1;
247 /// Indicator of whether the first entry is an unsized array.
248 unsigned FirstEntryIsAnUnsizedArray
: 1;
250 /// Indicator of whether the most-derived object is an array element.
251 unsigned MostDerivedIsArrayElement
: 1;
253 /// The length of the path to the most-derived object of which this is a
255 unsigned MostDerivedPathLength
: 28;
257 /// The size of the array of which the most-derived object is an element.
258 /// This will always be 0 if the most-derived object is not an array
259 /// element. 0 is not an indicator of whether or not the most-derived object
260 /// is an array, however, because 0-length arrays are allowed.
262 /// If the current array is an unsized array, the value of this is
264 uint64_t MostDerivedArraySize
;
266 /// The type of the most derived object referred to by this address.
267 QualType MostDerivedType
;
269 typedef APValue::LValuePathEntry PathEntry
;
271 /// The entries on the path from the glvalue to the designated subobject.
272 SmallVector
<PathEntry
, 8> Entries
;
274 SubobjectDesignator() : Invalid(true) {}
276 explicit SubobjectDesignator(QualType T
)
277 : Invalid(false), IsOnePastTheEnd(false),
278 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
279 MostDerivedPathLength(0), MostDerivedArraySize(0),
280 MostDerivedType(T
) {}
282 SubobjectDesignator(ASTContext
&Ctx
, const APValue
&V
)
283 : Invalid(!V
.isLValue() || !V
.hasLValuePath()), IsOnePastTheEnd(false),
284 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
285 MostDerivedPathLength(0), MostDerivedArraySize(0) {
286 assert(V
.isLValue() && "Non-LValue used to make an LValue designator?");
288 IsOnePastTheEnd
= V
.isLValueOnePastTheEnd();
289 ArrayRef
<PathEntry
> VEntries
= V
.getLValuePath();
290 Entries
.insert(Entries
.end(), VEntries
.begin(), VEntries
.end());
291 if (V
.getLValueBase()) {
292 bool IsArray
= false;
293 bool FirstIsUnsizedArray
= false;
294 MostDerivedPathLength
= findMostDerivedSubobject(
295 Ctx
, V
.getLValueBase(), V
.getLValuePath(), MostDerivedArraySize
,
296 MostDerivedType
, IsArray
, FirstIsUnsizedArray
);
297 MostDerivedIsArrayElement
= IsArray
;
298 FirstEntryIsAnUnsizedArray
= FirstIsUnsizedArray
;
303 void truncate(ASTContext
&Ctx
, APValue::LValueBase Base
,
304 unsigned NewLength
) {
308 assert(Base
&& "cannot truncate path for null pointer");
309 assert(NewLength
<= Entries
.size() && "not a truncation");
311 if (NewLength
== Entries
.size())
313 Entries
.resize(NewLength
);
315 bool IsArray
= false;
316 bool FirstIsUnsizedArray
= false;
317 MostDerivedPathLength
= findMostDerivedSubobject(
318 Ctx
, Base
, Entries
, MostDerivedArraySize
, MostDerivedType
, IsArray
,
319 FirstIsUnsizedArray
);
320 MostDerivedIsArrayElement
= IsArray
;
321 FirstEntryIsAnUnsizedArray
= FirstIsUnsizedArray
;
329 /// Determine whether the most derived subobject is an array without a
331 bool isMostDerivedAnUnsizedArray() const {
332 assert(!Invalid
&& "Calling this makes no sense on invalid designators");
333 return Entries
.size() == 1 && FirstEntryIsAnUnsizedArray
;
336 /// Determine what the most derived array's size is. Results in an assertion
337 /// failure if the most derived array lacks a size.
338 uint64_t getMostDerivedArraySize() const {
339 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
340 return MostDerivedArraySize
;
343 /// Determine whether this is a one-past-the-end pointer.
344 bool isOnePastTheEnd() const {
348 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement
&&
349 Entries
[MostDerivedPathLength
- 1].getAsArrayIndex() ==
350 MostDerivedArraySize
)
355 /// Get the range of valid index adjustments in the form
356 /// {maximum value that can be subtracted from this pointer,
357 /// maximum value that can be added to this pointer}
358 std::pair
<uint64_t, uint64_t> validIndexAdjustments() {
359 if (Invalid
|| isMostDerivedAnUnsizedArray())
362 // [expr.add]p4: For the purposes of these operators, a pointer to a
363 // nonarray object behaves the same as a pointer to the first element of
364 // an array of length one with the type of the object as its element type.
365 bool IsArray
= MostDerivedPathLength
== Entries
.size() &&
366 MostDerivedIsArrayElement
;
367 uint64_t ArrayIndex
= IsArray
? Entries
.back().getAsArrayIndex()
368 : (uint64_t)IsOnePastTheEnd
;
370 IsArray
? getMostDerivedArraySize() : (uint64_t)1;
371 return {ArrayIndex
, ArraySize
- ArrayIndex
};
374 /// Check that this refers to a valid subobject.
375 bool isValidSubobject() const {
378 return !isOnePastTheEnd();
380 /// Check that this refers to a valid subobject, and if not, produce a
381 /// relevant diagnostic and set the designator as invalid.
382 bool checkSubobject(EvalInfo
&Info
, const Expr
*E
, CheckSubobjectKind CSK
);
384 /// Get the type of the designated object.
385 QualType
getType(ASTContext
&Ctx
) const {
386 assert(!Invalid
&& "invalid designator has no subobject type");
387 return MostDerivedPathLength
== Entries
.size()
389 : Ctx
.getRecordType(getAsBaseClass(Entries
.back()));
392 /// Update this designator to refer to the first element within this array.
393 void addArrayUnchecked(const ConstantArrayType
*CAT
) {
394 Entries
.push_back(PathEntry::ArrayIndex(0));
396 // This is a most-derived object.
397 MostDerivedType
= CAT
->getElementType();
398 MostDerivedIsArrayElement
= true;
399 MostDerivedArraySize
= CAT
->getSize().getZExtValue();
400 MostDerivedPathLength
= Entries
.size();
402 /// Update this designator to refer to the first element within the array of
403 /// elements of type T. This is an array of unknown size.
404 void addUnsizedArrayUnchecked(QualType ElemTy
) {
405 Entries
.push_back(PathEntry::ArrayIndex(0));
407 MostDerivedType
= ElemTy
;
408 MostDerivedIsArrayElement
= true;
409 // The value in MostDerivedArraySize is undefined in this case. So, set it
410 // to an arbitrary value that's likely to loudly break things if it's
412 MostDerivedArraySize
= AssumedSizeForUnsizedArray
;
413 MostDerivedPathLength
= Entries
.size();
415 /// Update this designator to refer to the given base or member of this
417 void addDeclUnchecked(const Decl
*D
, bool Virtual
= false) {
418 Entries
.push_back(APValue::BaseOrMemberType(D
, Virtual
));
420 // If this isn't a base class, it's a new most-derived object.
421 if (const FieldDecl
*FD
= dyn_cast
<FieldDecl
>(D
)) {
422 MostDerivedType
= FD
->getType();
423 MostDerivedIsArrayElement
= false;
424 MostDerivedArraySize
= 0;
425 MostDerivedPathLength
= Entries
.size();
428 /// Update this designator to refer to the given complex component.
429 void addComplexUnchecked(QualType EltTy
, bool Imag
) {
430 Entries
.push_back(PathEntry::ArrayIndex(Imag
));
432 // This is technically a most-derived object, though in practice this
433 // is unlikely to matter.
434 MostDerivedType
= EltTy
;
435 MostDerivedIsArrayElement
= true;
436 MostDerivedArraySize
= 2;
437 MostDerivedPathLength
= Entries
.size();
439 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo
&Info
, const Expr
*E
);
440 void diagnosePointerArithmetic(EvalInfo
&Info
, const Expr
*E
,
442 /// Add N to the address of this subobject.
443 void adjustIndex(EvalInfo
&Info
, const Expr
*E
, APSInt N
) {
444 if (Invalid
|| !N
) return;
445 uint64_t TruncatedN
= N
.extOrTrunc(64).getZExtValue();
446 if (isMostDerivedAnUnsizedArray()) {
447 diagnoseUnsizedArrayPointerArithmetic(Info
, E
);
448 // Can't verify -- trust that the user is doing the right thing (or if
449 // not, trust that the caller will catch the bad behavior).
450 // FIXME: Should we reject if this overflows, at least?
451 Entries
.back() = PathEntry::ArrayIndex(
452 Entries
.back().getAsArrayIndex() + TruncatedN
);
456 // [expr.add]p4: For the purposes of these operators, a pointer to a
457 // nonarray object behaves the same as a pointer to the first element of
458 // an array of length one with the type of the object as its element type.
459 bool IsArray
= MostDerivedPathLength
== Entries
.size() &&
460 MostDerivedIsArrayElement
;
461 uint64_t ArrayIndex
= IsArray
? Entries
.back().getAsArrayIndex()
462 : (uint64_t)IsOnePastTheEnd
;
464 IsArray
? getMostDerivedArraySize() : (uint64_t)1;
466 if (N
< -(int64_t)ArrayIndex
|| N
> ArraySize
- ArrayIndex
) {
467 // Calculate the actual index in a wide enough type, so we can include
469 N
= N
.extend(std::max
<unsigned>(N
.getBitWidth() + 1, 65));
470 (llvm::APInt
&)N
+= ArrayIndex
;
471 assert(N
.ugt(ArraySize
) && "bounds check failed for in-bounds index");
472 diagnosePointerArithmetic(Info
, E
, N
);
477 ArrayIndex
+= TruncatedN
;
478 assert(ArrayIndex
<= ArraySize
&&
479 "bounds check succeeded for out-of-bounds index");
482 Entries
.back() = PathEntry::ArrayIndex(ArrayIndex
);
484 IsOnePastTheEnd
= (ArrayIndex
!= 0);
488 /// A scope at the end of which an object can need to be destroyed.
489 enum class ScopeKind
{
495 /// A reference to a particular call and its arguments.
497 CallRef() : OrigCallee(), CallIndex(0), Version() {}
498 CallRef(const FunctionDecl
*Callee
, unsigned CallIndex
, unsigned Version
)
499 : OrigCallee(Callee
), CallIndex(CallIndex
), Version(Version
) {}
501 explicit operator bool() const { return OrigCallee
; }
503 /// Get the parameter that the caller initialized, corresponding to the
504 /// given parameter in the callee.
505 const ParmVarDecl
*getOrigParam(const ParmVarDecl
*PVD
) const {
506 return OrigCallee
? OrigCallee
->getParamDecl(PVD
->getFunctionScopeIndex())
510 /// The callee at the point where the arguments were evaluated. This might
511 /// be different from the actual callee (a different redeclaration, or a
512 /// virtual override), but this function's parameters are the ones that
513 /// appear in the parameter map.
514 const FunctionDecl
*OrigCallee
;
515 /// The call index of the frame that holds the argument values.
517 /// The version of the parameters corresponding to this call.
521 /// A stack frame in the constexpr call stack.
522 class CallStackFrame
: public interp::Frame
{
526 /// Parent - The caller of this stack frame.
527 CallStackFrame
*Caller
;
529 /// Callee - The function which was called.
530 const FunctionDecl
*Callee
;
532 /// This - The binding for the this pointer in this call, if any.
535 /// CallExpr - The syntactical structure of member function calls
536 const Expr
*CallExpr
;
538 /// Information on how to find the arguments to this call. Our arguments
539 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
540 /// key and this value as the version.
543 /// Source location information about the default argument or default
544 /// initializer expression we're evaluating, if any.
545 CurrentSourceLocExprScope CurSourceLocExprScope
;
547 // Note that we intentionally use std::map here so that references to
548 // values are stable.
549 typedef std::pair
<const void *, unsigned> MapKeyTy
;
550 typedef std::map
<MapKeyTy
, APValue
> MapTy
;
551 /// Temporaries - Temporary lvalues materialized within this stack frame.
554 /// CallRange - The source range of the call expression for this call.
555 SourceRange CallRange
;
557 /// Index - The call index of this call.
560 /// The stack of integers for tracking version numbers for temporaries.
561 SmallVector
<unsigned, 2> TempVersionStack
= {1};
562 unsigned CurTempVersion
= TempVersionStack
.back();
564 unsigned getTempVersion() const { return TempVersionStack
.back(); }
566 void pushTempVersion() {
567 TempVersionStack
.push_back(++CurTempVersion
);
570 void popTempVersion() {
571 TempVersionStack
.pop_back();
574 CallRef
createCall(const FunctionDecl
*Callee
) {
575 return {Callee
, Index
, ++CurTempVersion
};
578 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
579 // on the overall stack usage of deeply-recursing constexpr evaluations.
580 // (We should cache this map rather than recomputing it repeatedly.)
581 // But let's try this and see how it goes; we can look into caching the map
582 // as a later change.
584 /// LambdaCaptureFields - Mapping from captured variables/this to
585 /// corresponding data members in the closure class.
586 llvm::DenseMap
<const ValueDecl
*, FieldDecl
*> LambdaCaptureFields
;
587 FieldDecl
*LambdaThisCaptureField
= nullptr;
589 CallStackFrame(EvalInfo
&Info
, SourceRange CallRange
,
590 const FunctionDecl
*Callee
, const LValue
*This
,
591 const Expr
*CallExpr
, CallRef Arguments
);
594 // Return the temporary for Key whose version number is Version.
595 APValue
*getTemporary(const void *Key
, unsigned Version
) {
596 MapKeyTy
KV(Key
, Version
);
597 auto LB
= Temporaries
.lower_bound(KV
);
598 if (LB
!= Temporaries
.end() && LB
->first
== KV
)
603 // Return the current temporary for Key in the map.
604 APValue
*getCurrentTemporary(const void *Key
) {
605 auto UB
= Temporaries
.upper_bound(MapKeyTy(Key
, UINT_MAX
));
606 if (UB
!= Temporaries
.begin() && std::prev(UB
)->first
.first
== Key
)
607 return &std::prev(UB
)->second
;
611 // Return the version number of the current temporary for Key.
612 unsigned getCurrentTemporaryVersion(const void *Key
) const {
613 auto UB
= Temporaries
.upper_bound(MapKeyTy(Key
, UINT_MAX
));
614 if (UB
!= Temporaries
.begin() && std::prev(UB
)->first
.first
== Key
)
615 return std::prev(UB
)->first
.second
;
619 /// Allocate storage for an object of type T in this stack frame.
620 /// Populates LV with a handle to the created object. Key identifies
621 /// the temporary within the stack frame, and must not be reused without
622 /// bumping the temporary version number.
623 template<typename KeyT
>
624 APValue
&createTemporary(const KeyT
*Key
, QualType T
,
625 ScopeKind Scope
, LValue
&LV
);
627 /// Allocate storage for a parameter of a function call made in this frame.
628 APValue
&createParam(CallRef Args
, const ParmVarDecl
*PVD
, LValue
&LV
);
630 void describe(llvm::raw_ostream
&OS
) const override
;
632 Frame
*getCaller() const override
{ return Caller
; }
633 SourceRange
getCallRange() const override
{ return CallRange
; }
634 const FunctionDecl
*getCallee() const override
{ return Callee
; }
636 bool isStdFunction() const {
637 for (const DeclContext
*DC
= Callee
; DC
; DC
= DC
->getParent())
638 if (DC
->isStdNamespace())
644 APValue
&createLocal(APValue::LValueBase Base
, const void *Key
, QualType T
,
648 /// Temporarily override 'this'.
649 class ThisOverrideRAII
{
651 ThisOverrideRAII(CallStackFrame
&Frame
, const LValue
*NewThis
, bool Enable
)
652 : Frame(Frame
), OldThis(Frame
.This
) {
654 Frame
.This
= NewThis
;
656 ~ThisOverrideRAII() {
657 Frame
.This
= OldThis
;
660 CallStackFrame
&Frame
;
661 const LValue
*OldThis
;
664 // A shorthand time trace scope struct, prints source range, for example
665 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
666 class ExprTimeTraceScope
{
668 ExprTimeTraceScope(const Expr
*E
, const ASTContext
&Ctx
, StringRef Name
)
669 : TimeScope(Name
, [E
, &Ctx
] {
670 return E
->getSourceRange().printToString(Ctx
.getSourceManager());
674 llvm::TimeTraceScope TimeScope
;
678 static bool HandleDestruction(EvalInfo
&Info
, const Expr
*E
,
679 const LValue
&This
, QualType ThisType
);
680 static bool HandleDestruction(EvalInfo
&Info
, SourceLocation Loc
,
681 APValue::LValueBase LVBase
, APValue
&Value
,
685 /// A cleanup, and a flag indicating whether it is lifetime-extended.
687 llvm::PointerIntPair
<APValue
*, 2, ScopeKind
> Value
;
688 APValue::LValueBase Base
;
692 Cleanup(APValue
*Val
, APValue::LValueBase Base
, QualType T
,
694 : Value(Val
, Scope
), Base(Base
), T(T
) {}
696 /// Determine whether this cleanup should be performed at the end of the
697 /// given kind of scope.
698 bool isDestroyedAtEndOf(ScopeKind K
) const {
699 return (int)Value
.getInt() >= (int)K
;
701 bool endLifetime(EvalInfo
&Info
, bool RunDestructors
) {
702 if (RunDestructors
) {
704 if (const ValueDecl
*VD
= Base
.dyn_cast
<const ValueDecl
*>())
705 Loc
= VD
->getLocation();
706 else if (const Expr
*E
= Base
.dyn_cast
<const Expr
*>())
707 Loc
= E
->getExprLoc();
708 return HandleDestruction(Info
, Loc
, Base
, *Value
.getPointer(), T
);
710 *Value
.getPointer() = APValue();
714 bool hasSideEffect() {
715 return T
.isDestructedType();
719 /// A reference to an object whose construction we are currently evaluating.
720 struct ObjectUnderConstruction
{
721 APValue::LValueBase Base
;
722 ArrayRef
<APValue::LValuePathEntry
> Path
;
723 friend bool operator==(const ObjectUnderConstruction
&LHS
,
724 const ObjectUnderConstruction
&RHS
) {
725 return LHS
.Base
== RHS
.Base
&& LHS
.Path
== RHS
.Path
;
727 friend llvm::hash_code
hash_value(const ObjectUnderConstruction
&Obj
) {
728 return llvm::hash_combine(Obj
.Base
, Obj
.Path
);
731 enum class ConstructionPhase
{
742 template<> struct DenseMapInfo
<ObjectUnderConstruction
> {
743 using Base
= DenseMapInfo
<APValue::LValueBase
>;
744 static ObjectUnderConstruction
getEmptyKey() {
745 return {Base::getEmptyKey(), {}}; }
746 static ObjectUnderConstruction
getTombstoneKey() {
747 return {Base::getTombstoneKey(), {}};
749 static unsigned getHashValue(const ObjectUnderConstruction
&Object
) {
750 return hash_value(Object
);
752 static bool isEqual(const ObjectUnderConstruction
&LHS
,
753 const ObjectUnderConstruction
&RHS
) {
760 /// A dynamically-allocated heap object.
762 /// The value of this heap-allocated object.
764 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
765 /// or a CallExpr (the latter is for direct calls to operator new inside
766 /// std::allocator<T>::allocate).
767 const Expr
*AllocExpr
= nullptr;
775 /// Get the kind of the allocation. This must match between allocation
776 /// and deallocation.
777 Kind
getKind() const {
778 if (auto *NE
= dyn_cast
<CXXNewExpr
>(AllocExpr
))
779 return NE
->isArray() ? ArrayNew
: New
;
780 assert(isa
<CallExpr
>(AllocExpr
));
785 struct DynAllocOrder
{
786 bool operator()(DynamicAllocLValue L
, DynamicAllocLValue R
) const {
787 return L
.getIndex() < R
.getIndex();
791 /// EvalInfo - This is a private struct used by the evaluator to capture
792 /// information about a subexpression as it is folded. It retains information
793 /// about the AST context, but also maintains information about the folded
796 /// If an expression could be evaluated, it is still possible it is not a C
797 /// "integer constant expression" or constant expression. If not, this struct
798 /// captures information about how and why not.
800 /// One bit of information passed *into* the request for constant folding
801 /// indicates whether the subexpression is "evaluated" or not according to C
802 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
803 /// evaluate the expression regardless of what the RHS is, but C only allows
804 /// certain things in certain situations.
805 class EvalInfo
: public interp::State
{
809 /// EvalStatus - Contains information about the evaluation.
810 Expr::EvalStatus
&EvalStatus
;
812 /// CurrentCall - The top of the constexpr call stack.
813 CallStackFrame
*CurrentCall
;
815 /// CallStackDepth - The number of calls in the call stack right now.
816 unsigned CallStackDepth
;
818 /// NextCallIndex - The next call index to assign.
819 unsigned NextCallIndex
;
821 /// StepsLeft - The remaining number of evaluation steps we're permitted
822 /// to perform. This is essentially a limit for the number of statements
823 /// we will evaluate.
826 /// Enable the experimental new constant interpreter. If an expression is
827 /// not supported by the interpreter, an error is triggered.
828 bool EnableNewConstInterp
;
830 /// BottomFrame - The frame in which evaluation started. This must be
831 /// initialized after CurrentCall and CallStackDepth.
832 CallStackFrame BottomFrame
;
834 /// A stack of values whose lifetimes end at the end of some surrounding
835 /// evaluation frame.
836 llvm::SmallVector
<Cleanup
, 16> CleanupStack
;
838 /// EvaluatingDecl - This is the declaration whose initializer is being
839 /// evaluated, if any.
840 APValue::LValueBase EvaluatingDecl
;
842 enum class EvaluatingDeclKind
{
844 /// We're evaluating the construction of EvaluatingDecl.
846 /// We're evaluating the destruction of EvaluatingDecl.
849 EvaluatingDeclKind IsEvaluatingDecl
= EvaluatingDeclKind::None
;
851 /// EvaluatingDeclValue - This is the value being constructed for the
852 /// declaration whose initializer is being evaluated, if any.
853 APValue
*EvaluatingDeclValue
;
855 /// Set of objects that are currently being constructed.
856 llvm::DenseMap
<ObjectUnderConstruction
, ConstructionPhase
>
857 ObjectsUnderConstruction
;
859 /// Current heap allocations, along with the location where each was
860 /// allocated. We use std::map here because we need stable addresses
861 /// for the stored APValues.
862 std::map
<DynamicAllocLValue
, DynAlloc
, DynAllocOrder
> HeapAllocs
;
864 /// The number of heap allocations performed so far in this evaluation.
865 unsigned NumHeapAllocs
= 0;
867 struct EvaluatingConstructorRAII
{
869 ObjectUnderConstruction Object
;
871 EvaluatingConstructorRAII(EvalInfo
&EI
, ObjectUnderConstruction Object
,
873 : EI(EI
), Object(Object
) {
875 EI
.ObjectsUnderConstruction
876 .insert({Object
, HasBases
? ConstructionPhase::Bases
877 : ConstructionPhase::AfterBases
})
880 void finishedConstructingBases() {
881 EI
.ObjectsUnderConstruction
[Object
] = ConstructionPhase::AfterBases
;
883 void finishedConstructingFields() {
884 EI
.ObjectsUnderConstruction
[Object
] = ConstructionPhase::AfterFields
;
886 ~EvaluatingConstructorRAII() {
887 if (DidInsert
) EI
.ObjectsUnderConstruction
.erase(Object
);
891 struct EvaluatingDestructorRAII
{
893 ObjectUnderConstruction Object
;
895 EvaluatingDestructorRAII(EvalInfo
&EI
, ObjectUnderConstruction Object
)
896 : EI(EI
), Object(Object
) {
897 DidInsert
= EI
.ObjectsUnderConstruction
898 .insert({Object
, ConstructionPhase::Destroying
})
901 void startedDestroyingBases() {
902 EI
.ObjectsUnderConstruction
[Object
] =
903 ConstructionPhase::DestroyingBases
;
905 ~EvaluatingDestructorRAII() {
907 EI
.ObjectsUnderConstruction
.erase(Object
);
912 isEvaluatingCtorDtor(APValue::LValueBase Base
,
913 ArrayRef
<APValue::LValuePathEntry
> Path
) {
914 return ObjectsUnderConstruction
.lookup({Base
, Path
});
917 /// If we're currently speculatively evaluating, the outermost call stack
918 /// depth at which we can mutate state, otherwise 0.
919 unsigned SpeculativeEvaluationDepth
= 0;
921 /// The current array initialization index, if we're performing array
923 uint64_t ArrayInitIndex
= -1;
925 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
926 /// notes attached to it will also be stored, otherwise they will not be.
927 bool HasActiveDiagnostic
;
929 /// Have we emitted a diagnostic explaining why we couldn't constant
930 /// fold (not just why it's not strictly a constant expression)?
931 bool HasFoldFailureDiagnostic
;
933 /// Whether we're checking that an expression is a potential constant
934 /// expression. If so, do not fail on constructs that could become constant
935 /// later on (such as a use of an undefined global).
936 bool CheckingPotentialConstantExpression
= false;
938 /// Whether we're checking for an expression that has undefined behavior.
939 /// If so, we will produce warnings if we encounter an operation that is
940 /// always undefined.
942 /// Note that we still need to evaluate the expression normally when this
943 /// is set; this is used when evaluating ICEs in C.
944 bool CheckingForUndefinedBehavior
= false;
946 enum EvaluationMode
{
947 /// Evaluate as a constant expression. Stop if we find that the expression
948 /// is not a constant expression.
949 EM_ConstantExpression
,
951 /// Evaluate as a constant expression. Stop if we find that the expression
952 /// is not a constant expression. Some expressions can be retried in the
953 /// optimizer if we don't constant fold them here, but in an unevaluated
954 /// context we try to fold them immediately since the optimizer never
955 /// gets a chance to look at it.
956 EM_ConstantExpressionUnevaluated
,
958 /// Fold the expression to a constant. Stop if we hit a side-effect that
962 /// Evaluate in any way we know how. Don't worry about side-effects that
963 /// can't be modeled.
964 EM_IgnoreSideEffects
,
967 /// Are we checking whether the expression is a potential constant
969 bool checkingPotentialConstantExpression() const override
{
970 return CheckingPotentialConstantExpression
;
973 /// Are we checking an expression for overflow?
974 // FIXME: We should check for any kind of undefined or suspicious behavior
975 // in such constructs, not just overflow.
976 bool checkingForUndefinedBehavior() const override
{
977 return CheckingForUndefinedBehavior
;
980 EvalInfo(const ASTContext
&C
, Expr::EvalStatus
&S
, EvaluationMode Mode
)
981 : Ctx(const_cast<ASTContext
&>(C
)), EvalStatus(S
), CurrentCall(nullptr),
982 CallStackDepth(0), NextCallIndex(1),
983 StepsLeft(C
.getLangOpts().ConstexprStepLimit
),
984 EnableNewConstInterp(C
.getLangOpts().EnableNewConstInterp
),
985 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
987 /*CallExpr=*/nullptr, CallRef()),
988 EvaluatingDecl((const ValueDecl
*)nullptr),
989 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
990 HasFoldFailureDiagnostic(false), EvalMode(Mode
) {}
996 ASTContext
&getCtx() const override
{ return Ctx
; }
998 void setEvaluatingDecl(APValue::LValueBase Base
, APValue
&Value
,
999 EvaluatingDeclKind EDK
= EvaluatingDeclKind::Ctor
) {
1000 EvaluatingDecl
= Base
;
1001 IsEvaluatingDecl
= EDK
;
1002 EvaluatingDeclValue
= &Value
;
1005 bool CheckCallLimit(SourceLocation Loc
) {
1006 // Don't perform any constexpr calls (other than the call we're checking)
1007 // when checking a potential constant expression.
1008 if (checkingPotentialConstantExpression() && CallStackDepth
> 1)
1010 if (NextCallIndex
== 0) {
1011 // NextCallIndex has wrapped around.
1012 FFDiag(Loc
, diag::note_constexpr_call_limit_exceeded
);
1015 if (CallStackDepth
<= getLangOpts().ConstexprCallDepth
)
1017 FFDiag(Loc
, diag::note_constexpr_depth_limit_exceeded
)
1018 << getLangOpts().ConstexprCallDepth
;
1022 bool CheckArraySize(SourceLocation Loc
, unsigned BitWidth
,
1023 uint64_t ElemCount
, bool Diag
) {
1025 // APValue stores array extents as unsigned,
1026 // so anything that is greater that unsigned would overflow when
1027 // constructing the array, we catch this here.
1028 if (BitWidth
> ConstantArrayType::getMaxSizeBits(Ctx
) ||
1029 ElemCount
> uint64_t(std::numeric_limits
<unsigned>::max())) {
1031 FFDiag(Loc
, diag::note_constexpr_new_too_large
) << ElemCount
;
1036 // Arrays allocate an APValue per element.
1037 // We use the number of constexpr steps as a proxy for the maximum size
1038 // of arrays to avoid exhausting the system resources, as initialization
1039 // of each element is likely to take some number of steps anyway.
1040 uint64_t Limit
= Ctx
.getLangOpts().ConstexprStepLimit
;
1041 if (ElemCount
> Limit
) {
1043 FFDiag(Loc
, diag::note_constexpr_new_exceeds_limits
)
1044 << ElemCount
<< Limit
;
1050 std::pair
<CallStackFrame
*, unsigned>
1051 getCallFrameAndDepth(unsigned CallIndex
) {
1052 assert(CallIndex
&& "no call index in getCallFrameAndDepth");
1053 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1054 // be null in this loop.
1055 unsigned Depth
= CallStackDepth
;
1056 CallStackFrame
*Frame
= CurrentCall
;
1057 while (Frame
->Index
> CallIndex
) {
1058 Frame
= Frame
->Caller
;
1061 if (Frame
->Index
== CallIndex
)
1062 return {Frame
, Depth
};
1063 return {nullptr, 0};
1066 bool nextStep(const Stmt
*S
) {
1068 FFDiag(S
->getBeginLoc(), diag::note_constexpr_step_limit_exceeded
);
1075 APValue
*createHeapAlloc(const Expr
*E
, QualType T
, LValue
&LV
);
1077 std::optional
<DynAlloc
*> lookupDynamicAlloc(DynamicAllocLValue DA
) {
1078 std::optional
<DynAlloc
*> Result
;
1079 auto It
= HeapAllocs
.find(DA
);
1080 if (It
!= HeapAllocs
.end())
1081 Result
= &It
->second
;
1085 /// Get the allocated storage for the given parameter of the given call.
1086 APValue
*getParamSlot(CallRef Call
, const ParmVarDecl
*PVD
) {
1087 CallStackFrame
*Frame
= getCallFrameAndDepth(Call
.CallIndex
).first
;
1088 return Frame
? Frame
->getTemporary(Call
.getOrigParam(PVD
), Call
.Version
)
1092 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1093 struct StdAllocatorCaller
{
1094 unsigned FrameIndex
;
1096 explicit operator bool() const { return FrameIndex
!= 0; };
1099 StdAllocatorCaller
getStdAllocatorCaller(StringRef FnName
) const {
1100 for (const CallStackFrame
*Call
= CurrentCall
; Call
!= &BottomFrame
;
1101 Call
= Call
->Caller
) {
1102 const auto *MD
= dyn_cast_or_null
<CXXMethodDecl
>(Call
->Callee
);
1105 const IdentifierInfo
*FnII
= MD
->getIdentifier();
1106 if (!FnII
|| !FnII
->isStr(FnName
))
1110 dyn_cast
<ClassTemplateSpecializationDecl
>(MD
->getParent());
1114 const IdentifierInfo
*ClassII
= CTSD
->getIdentifier();
1115 const TemplateArgumentList
&TAL
= CTSD
->getTemplateArgs();
1116 if (CTSD
->isInStdNamespace() && ClassII
&&
1117 ClassII
->isStr("allocator") && TAL
.size() >= 1 &&
1118 TAL
[0].getKind() == TemplateArgument::Type
)
1119 return {Call
->Index
, TAL
[0].getAsType()};
1125 void performLifetimeExtension() {
1126 // Disable the cleanups for lifetime-extended temporaries.
1127 llvm::erase_if(CleanupStack
, [](Cleanup
&C
) {
1128 return !C
.isDestroyedAtEndOf(ScopeKind::FullExpression
);
1132 /// Throw away any remaining cleanups at the end of evaluation. If any
1133 /// cleanups would have had a side-effect, note that as an unmodeled
1134 /// side-effect and return false. Otherwise, return true.
1135 bool discardCleanups() {
1136 for (Cleanup
&C
: CleanupStack
) {
1137 if (C
.hasSideEffect() && !noteSideEffect()) {
1138 CleanupStack
.clear();
1142 CleanupStack
.clear();
1147 interp::Frame
*getCurrentFrame() override
{ return CurrentCall
; }
1148 const interp::Frame
*getBottomFrame() const override
{ return &BottomFrame
; }
1150 bool hasActiveDiagnostic() override
{ return HasActiveDiagnostic
; }
1151 void setActiveDiagnostic(bool Flag
) override
{ HasActiveDiagnostic
= Flag
; }
1153 void setFoldFailureDiagnostic(bool Flag
) override
{
1154 HasFoldFailureDiagnostic
= Flag
;
1157 Expr::EvalStatus
&getEvalStatus() const override
{ return EvalStatus
; }
1159 // If we have a prior diagnostic, it will be noting that the expression
1160 // isn't a constant expression. This diagnostic is more important,
1161 // unless we require this evaluation to produce a constant expression.
1163 // FIXME: We might want to show both diagnostics to the user in
1164 // EM_ConstantFold mode.
1165 bool hasPriorDiagnostic() override
{
1166 if (!EvalStatus
.Diag
->empty()) {
1168 case EM_ConstantFold
:
1169 case EM_IgnoreSideEffects
:
1170 if (!HasFoldFailureDiagnostic
)
1172 // We've already failed to fold something. Keep that diagnostic.
1174 case EM_ConstantExpression
:
1175 case EM_ConstantExpressionUnevaluated
:
1176 setActiveDiagnostic(false);
1183 unsigned getCallStackDepth() override
{ return CallStackDepth
; }
1186 /// Should we continue evaluation after encountering a side-effect that we
1188 bool keepEvaluatingAfterSideEffect() {
1190 case EM_IgnoreSideEffects
:
1193 case EM_ConstantExpression
:
1194 case EM_ConstantExpressionUnevaluated
:
1195 case EM_ConstantFold
:
1196 // By default, assume any side effect might be valid in some other
1197 // evaluation of this expression from a different context.
1198 return checkingPotentialConstantExpression() ||
1199 checkingForUndefinedBehavior();
1201 llvm_unreachable("Missed EvalMode case");
1204 /// Note that we have had a side-effect, and determine whether we should
1205 /// keep evaluating.
1206 bool noteSideEffect() {
1207 EvalStatus
.HasSideEffects
= true;
1208 return keepEvaluatingAfterSideEffect();
1211 /// Should we continue evaluation after encountering undefined behavior?
1212 bool keepEvaluatingAfterUndefinedBehavior() {
1214 case EM_IgnoreSideEffects
:
1215 case EM_ConstantFold
:
1218 case EM_ConstantExpression
:
1219 case EM_ConstantExpressionUnevaluated
:
1220 return checkingForUndefinedBehavior();
1222 llvm_unreachable("Missed EvalMode case");
1225 /// Note that we hit something that was technically undefined behavior, but
1226 /// that we can evaluate past it (such as signed overflow or floating-point
1227 /// division by zero.)
1228 bool noteUndefinedBehavior() override
{
1229 EvalStatus
.HasUndefinedBehavior
= true;
1230 return keepEvaluatingAfterUndefinedBehavior();
1233 /// Should we continue evaluation as much as possible after encountering a
1234 /// construct which can't be reduced to a value?
1235 bool keepEvaluatingAfterFailure() const override
{
1240 case EM_ConstantExpression
:
1241 case EM_ConstantExpressionUnevaluated
:
1242 case EM_ConstantFold
:
1243 case EM_IgnoreSideEffects
:
1244 return checkingPotentialConstantExpression() ||
1245 checkingForUndefinedBehavior();
1247 llvm_unreachable("Missed EvalMode case");
1250 /// Notes that we failed to evaluate an expression that other expressions
1251 /// directly depend on, and determine if we should keep evaluating. This
1252 /// should only be called if we actually intend to keep evaluating.
1254 /// Call noteSideEffect() instead if we may be able to ignore the value that
1255 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1257 /// (Foo(), 1) // use noteSideEffect
1258 /// (Foo() || true) // use noteSideEffect
1259 /// Foo() + 1 // use noteFailure
1260 [[nodiscard
]] bool noteFailure() {
1261 // Failure when evaluating some expression often means there is some
1262 // subexpression whose evaluation was skipped. Therefore, (because we
1263 // don't track whether we skipped an expression when unwinding after an
1264 // evaluation failure) every evaluation failure that bubbles up from a
1265 // subexpression implies that a side-effect has potentially happened. We
1266 // skip setting the HasSideEffects flag to true until we decide to
1267 // continue evaluating after that point, which happens here.
1268 bool KeepGoing
= keepEvaluatingAfterFailure();
1269 EvalStatus
.HasSideEffects
|= KeepGoing
;
1273 class ArrayInitLoopIndex
{
1275 uint64_t OuterIndex
;
1278 ArrayInitLoopIndex(EvalInfo
&Info
)
1279 : Info(Info
), OuterIndex(Info
.ArrayInitIndex
) {
1280 Info
.ArrayInitIndex
= 0;
1282 ~ArrayInitLoopIndex() { Info
.ArrayInitIndex
= OuterIndex
; }
1284 operator uint64_t&() { return Info
.ArrayInitIndex
; }
1288 /// Object used to treat all foldable expressions as constant expressions.
1289 struct FoldConstant
{
1292 bool HadNoPriorDiags
;
1293 EvalInfo::EvaluationMode OldMode
;
1295 explicit FoldConstant(EvalInfo
&Info
, bool Enabled
)
1298 HadNoPriorDiags(Info
.EvalStatus
.Diag
&&
1299 Info
.EvalStatus
.Diag
->empty() &&
1300 !Info
.EvalStatus
.HasSideEffects
),
1301 OldMode(Info
.EvalMode
) {
1303 Info
.EvalMode
= EvalInfo::EM_ConstantFold
;
1305 void keepDiagnostics() { Enabled
= false; }
1307 if (Enabled
&& HadNoPriorDiags
&& !Info
.EvalStatus
.Diag
->empty() &&
1308 !Info
.EvalStatus
.HasSideEffects
)
1309 Info
.EvalStatus
.Diag
->clear();
1310 Info
.EvalMode
= OldMode
;
1314 /// RAII object used to set the current evaluation mode to ignore
1316 struct IgnoreSideEffectsRAII
{
1318 EvalInfo::EvaluationMode OldMode
;
1319 explicit IgnoreSideEffectsRAII(EvalInfo
&Info
)
1320 : Info(Info
), OldMode(Info
.EvalMode
) {
1321 Info
.EvalMode
= EvalInfo::EM_IgnoreSideEffects
;
1324 ~IgnoreSideEffectsRAII() { Info
.EvalMode
= OldMode
; }
1327 /// RAII object used to optionally suppress diagnostics and side-effects from
1328 /// a speculative evaluation.
1329 class SpeculativeEvaluationRAII
{
1330 EvalInfo
*Info
= nullptr;
1331 Expr::EvalStatus OldStatus
;
1332 unsigned OldSpeculativeEvaluationDepth
= 0;
1334 void moveFromAndCancel(SpeculativeEvaluationRAII
&&Other
) {
1336 OldStatus
= Other
.OldStatus
;
1337 OldSpeculativeEvaluationDepth
= Other
.OldSpeculativeEvaluationDepth
;
1338 Other
.Info
= nullptr;
1341 void maybeRestoreState() {
1345 Info
->EvalStatus
= OldStatus
;
1346 Info
->SpeculativeEvaluationDepth
= OldSpeculativeEvaluationDepth
;
1350 SpeculativeEvaluationRAII() = default;
1352 SpeculativeEvaluationRAII(
1353 EvalInfo
&Info
, SmallVectorImpl
<PartialDiagnosticAt
> *NewDiag
= nullptr)
1354 : Info(&Info
), OldStatus(Info
.EvalStatus
),
1355 OldSpeculativeEvaluationDepth(Info
.SpeculativeEvaluationDepth
) {
1356 Info
.EvalStatus
.Diag
= NewDiag
;
1357 Info
.SpeculativeEvaluationDepth
= Info
.CallStackDepth
+ 1;
1360 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII
&Other
) = delete;
1361 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII
&&Other
) {
1362 moveFromAndCancel(std::move(Other
));
1365 SpeculativeEvaluationRAII
&operator=(SpeculativeEvaluationRAII
&&Other
) {
1366 maybeRestoreState();
1367 moveFromAndCancel(std::move(Other
));
1371 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1374 /// RAII object wrapping a full-expression or block scope, and handling
1375 /// the ending of the lifetime of temporaries created within it.
1376 template<ScopeKind Kind
>
1379 unsigned OldStackSize
;
1381 ScopeRAII(EvalInfo
&Info
)
1382 : Info(Info
), OldStackSize(Info
.CleanupStack
.size()) {
1383 // Push a new temporary version. This is needed to distinguish between
1384 // temporaries created in different iterations of a loop.
1385 Info
.CurrentCall
->pushTempVersion();
1387 bool destroy(bool RunDestructors
= true) {
1388 bool OK
= cleanup(Info
, RunDestructors
, OldStackSize
);
1393 if (OldStackSize
!= -1U)
1395 // Body moved to a static method to encourage the compiler to inline away
1396 // instances of this class.
1397 Info
.CurrentCall
->popTempVersion();
1400 static bool cleanup(EvalInfo
&Info
, bool RunDestructors
,
1401 unsigned OldStackSize
) {
1402 assert(OldStackSize
<= Info
.CleanupStack
.size() &&
1403 "running cleanups out of order?");
1405 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1406 // for a full-expression scope.
1407 bool Success
= true;
1408 for (unsigned I
= Info
.CleanupStack
.size(); I
> OldStackSize
; --I
) {
1409 if (Info
.CleanupStack
[I
- 1].isDestroyedAtEndOf(Kind
)) {
1410 if (!Info
.CleanupStack
[I
- 1].endLifetime(Info
, RunDestructors
)) {
1417 // Compact any retained cleanups.
1418 auto NewEnd
= Info
.CleanupStack
.begin() + OldStackSize
;
1419 if (Kind
!= ScopeKind::Block
)
1421 std::remove_if(NewEnd
, Info
.CleanupStack
.end(), [](Cleanup
&C
) {
1422 return C
.isDestroyedAtEndOf(Kind
);
1424 Info
.CleanupStack
.erase(NewEnd
, Info
.CleanupStack
.end());
1428 typedef ScopeRAII
<ScopeKind::Block
> BlockScopeRAII
;
1429 typedef ScopeRAII
<ScopeKind::FullExpression
> FullExpressionRAII
;
1430 typedef ScopeRAII
<ScopeKind::Call
> CallScopeRAII
;
1433 bool SubobjectDesignator::checkSubobject(EvalInfo
&Info
, const Expr
*E
,
1434 CheckSubobjectKind CSK
) {
1437 if (isOnePastTheEnd()) {
1438 Info
.CCEDiag(E
, diag::note_constexpr_past_end_subobject
)
1443 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1444 // must actually be at least one array element; even a VLA cannot have a
1445 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1449 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo
&Info
,
1451 Info
.CCEDiag(E
, diag::note_constexpr_unsized_array_indexed
);
1452 // Do not set the designator as invalid: we can represent this situation,
1453 // and correct handling of __builtin_object_size requires us to do so.
1456 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo
&Info
,
1459 // If we're complaining, we must be able to statically determine the size of
1460 // the most derived array.
1461 if (MostDerivedPathLength
== Entries
.size() && MostDerivedIsArrayElement
)
1462 Info
.CCEDiag(E
, diag::note_constexpr_array_index
)
1464 << static_cast<unsigned>(getMostDerivedArraySize());
1466 Info
.CCEDiag(E
, diag::note_constexpr_array_index
)
1467 << N
<< /*non-array*/ 1;
1471 CallStackFrame::CallStackFrame(EvalInfo
&Info
, SourceRange CallRange
,
1472 const FunctionDecl
*Callee
, const LValue
*This
,
1473 const Expr
*CallExpr
, CallRef Call
)
1474 : Info(Info
), Caller(Info
.CurrentCall
), Callee(Callee
), This(This
),
1475 CallExpr(CallExpr
), Arguments(Call
), CallRange(CallRange
),
1476 Index(Info
.NextCallIndex
++) {
1477 Info
.CurrentCall
= this;
1478 ++Info
.CallStackDepth
;
1481 CallStackFrame::~CallStackFrame() {
1482 assert(Info
.CurrentCall
== this && "calls retired out of order");
1483 --Info
.CallStackDepth
;
1484 Info
.CurrentCall
= Caller
;
1487 static bool isRead(AccessKinds AK
) {
1488 return AK
== AK_Read
|| AK
== AK_ReadObjectRepresentation
;
1491 static bool isModification(AccessKinds AK
) {
1494 case AK_ReadObjectRepresentation
:
1496 case AK_DynamicCast
:
1506 llvm_unreachable("unknown access kind");
1509 static bool isAnyAccess(AccessKinds AK
) {
1510 return isRead(AK
) || isModification(AK
);
1513 /// Is this an access per the C++ definition?
1514 static bool isFormalAccess(AccessKinds AK
) {
1515 return isAnyAccess(AK
) && AK
!= AK_Construct
&& AK
!= AK_Destroy
;
1518 /// Is this kind of axcess valid on an indeterminate object value?
1519 static bool isValidIndeterminateAccess(AccessKinds AK
) {
1524 // These need the object's value.
1527 case AK_ReadObjectRepresentation
:
1531 // Construction and destruction don't need the value.
1535 case AK_DynamicCast
:
1537 // These aren't really meaningful on scalars.
1540 llvm_unreachable("unknown access kind");
1544 struct ComplexValue
{
1549 APSInt IntReal
, IntImag
;
1550 APFloat FloatReal
, FloatImag
;
1552 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1554 void makeComplexFloat() { IsInt
= false; }
1555 bool isComplexFloat() const { return !IsInt
; }
1556 APFloat
&getComplexFloatReal() { return FloatReal
; }
1557 APFloat
&getComplexFloatImag() { return FloatImag
; }
1559 void makeComplexInt() { IsInt
= true; }
1560 bool isComplexInt() const { return IsInt
; }
1561 APSInt
&getComplexIntReal() { return IntReal
; }
1562 APSInt
&getComplexIntImag() { return IntImag
; }
1564 void moveInto(APValue
&v
) const {
1565 if (isComplexFloat())
1566 v
= APValue(FloatReal
, FloatImag
);
1568 v
= APValue(IntReal
, IntImag
);
1570 void setFrom(const APValue
&v
) {
1571 assert(v
.isComplexFloat() || v
.isComplexInt());
1572 if (v
.isComplexFloat()) {
1574 FloatReal
= v
.getComplexFloatReal();
1575 FloatImag
= v
.getComplexFloatImag();
1578 IntReal
= v
.getComplexIntReal();
1579 IntImag
= v
.getComplexIntImag();
1585 APValue::LValueBase Base
;
1587 SubobjectDesignator Designator
;
1589 bool InvalidBase
: 1;
1591 const APValue::LValueBase
getLValueBase() const { return Base
; }
1592 CharUnits
&getLValueOffset() { return Offset
; }
1593 const CharUnits
&getLValueOffset() const { return Offset
; }
1594 SubobjectDesignator
&getLValueDesignator() { return Designator
; }
1595 const SubobjectDesignator
&getLValueDesignator() const { return Designator
;}
1596 bool isNullPointer() const { return IsNullPtr
;}
1598 unsigned getLValueCallIndex() const { return Base
.getCallIndex(); }
1599 unsigned getLValueVersion() const { return Base
.getVersion(); }
1601 void moveInto(APValue
&V
) const {
1602 if (Designator
.Invalid
)
1603 V
= APValue(Base
, Offset
, APValue::NoLValuePath(), IsNullPtr
);
1605 assert(!InvalidBase
&& "APValues can't handle invalid LValue bases");
1606 V
= APValue(Base
, Offset
, Designator
.Entries
,
1607 Designator
.IsOnePastTheEnd
, IsNullPtr
);
1610 void setFrom(ASTContext
&Ctx
, const APValue
&V
) {
1611 assert(V
.isLValue() && "Setting LValue from a non-LValue?");
1612 Base
= V
.getLValueBase();
1613 Offset
= V
.getLValueOffset();
1614 InvalidBase
= false;
1615 Designator
= SubobjectDesignator(Ctx
, V
);
1616 IsNullPtr
= V
.isNullPointer();
1619 void set(APValue::LValueBase B
, bool BInvalid
= false) {
1621 // We only allow a few types of invalid bases. Enforce that here.
1623 const auto *E
= B
.get
<const Expr
*>();
1624 assert((isa
<MemberExpr
>(E
) || tryUnwrapAllocSizeCall(E
)) &&
1625 "Unexpected type of invalid base");
1630 Offset
= CharUnits::fromQuantity(0);
1631 InvalidBase
= BInvalid
;
1632 Designator
= SubobjectDesignator(getType(B
));
1636 void setNull(ASTContext
&Ctx
, QualType PointerTy
) {
1637 Base
= (const ValueDecl
*)nullptr;
1639 CharUnits::fromQuantity(Ctx
.getTargetNullPointerValue(PointerTy
));
1640 InvalidBase
= false;
1641 Designator
= SubobjectDesignator(PointerTy
->getPointeeType());
1645 void setInvalid(APValue::LValueBase B
, unsigned I
= 0) {
1649 std::string
toString(ASTContext
&Ctx
, QualType T
) const {
1651 moveInto(Printable
);
1652 return Printable
.getAsString(Ctx
, T
);
1656 // Check that this LValue is not based on a null pointer. If it is, produce
1657 // a diagnostic and mark the designator as invalid.
1658 template <typename GenDiagType
>
1659 bool checkNullPointerDiagnosingWith(const GenDiagType
&GenDiag
) {
1660 if (Designator
.Invalid
)
1664 Designator
.setInvalid();
1671 bool checkNullPointer(EvalInfo
&Info
, const Expr
*E
,
1672 CheckSubobjectKind CSK
) {
1673 return checkNullPointerDiagnosingWith([&Info
, E
, CSK
] {
1674 Info
.CCEDiag(E
, diag::note_constexpr_null_subobject
) << CSK
;
1678 bool checkNullPointerForFoldAccess(EvalInfo
&Info
, const Expr
*E
,
1680 return checkNullPointerDiagnosingWith([&Info
, E
, AK
] {
1681 Info
.FFDiag(E
, diag::note_constexpr_access_null
) << AK
;
1685 // Check this LValue refers to an object. If not, set the designator to be
1686 // invalid and emit a diagnostic.
1687 bool checkSubobject(EvalInfo
&Info
, const Expr
*E
, CheckSubobjectKind CSK
) {
1688 return (CSK
== CSK_ArrayToPointer
|| checkNullPointer(Info
, E
, CSK
)) &&
1689 Designator
.checkSubobject(Info
, E
, CSK
);
1692 void addDecl(EvalInfo
&Info
, const Expr
*E
,
1693 const Decl
*D
, bool Virtual
= false) {
1694 if (checkSubobject(Info
, E
, isa
<FieldDecl
>(D
) ? CSK_Field
: CSK_Base
))
1695 Designator
.addDeclUnchecked(D
, Virtual
);
1697 void addUnsizedArray(EvalInfo
&Info
, const Expr
*E
, QualType ElemTy
) {
1698 if (!Designator
.Entries
.empty()) {
1699 Info
.CCEDiag(E
, diag::note_constexpr_unsupported_unsized_array
);
1700 Designator
.setInvalid();
1703 if (checkSubobject(Info
, E
, CSK_ArrayToPointer
)) {
1704 assert(getType(Base
)->isPointerType() || getType(Base
)->isArrayType());
1705 Designator
.FirstEntryIsAnUnsizedArray
= true;
1706 Designator
.addUnsizedArrayUnchecked(ElemTy
);
1709 void addArray(EvalInfo
&Info
, const Expr
*E
, const ConstantArrayType
*CAT
) {
1710 if (checkSubobject(Info
, E
, CSK_ArrayToPointer
))
1711 Designator
.addArrayUnchecked(CAT
);
1713 void addComplex(EvalInfo
&Info
, const Expr
*E
, QualType EltTy
, bool Imag
) {
1714 if (checkSubobject(Info
, E
, Imag
? CSK_Imag
: CSK_Real
))
1715 Designator
.addComplexUnchecked(EltTy
, Imag
);
1717 void clearIsNullPointer() {
1720 void adjustOffsetAndIndex(EvalInfo
&Info
, const Expr
*E
,
1721 const APSInt
&Index
, CharUnits ElementSize
) {
1722 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1723 // but we're not required to diagnose it and it's valid in C++.)
1727 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1728 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1730 uint64_t Offset64
= Offset
.getQuantity();
1731 uint64_t ElemSize64
= ElementSize
.getQuantity();
1732 uint64_t Index64
= Index
.extOrTrunc(64).getZExtValue();
1733 Offset
= CharUnits::fromQuantity(Offset64
+ ElemSize64
* Index64
);
1735 if (checkNullPointer(Info
, E
, CSK_ArrayIndex
))
1736 Designator
.adjustIndex(Info
, E
, Index
);
1737 clearIsNullPointer();
1739 void adjustOffset(CharUnits N
) {
1741 if (N
.getQuantity())
1742 clearIsNullPointer();
1748 explicit MemberPtr(const ValueDecl
*Decl
)
1749 : DeclAndIsDerivedMember(Decl
, false) {}
1751 /// The member or (direct or indirect) field referred to by this member
1752 /// pointer, or 0 if this is a null member pointer.
1753 const ValueDecl
*getDecl() const {
1754 return DeclAndIsDerivedMember
.getPointer();
1756 /// Is this actually a member of some type derived from the relevant class?
1757 bool isDerivedMember() const {
1758 return DeclAndIsDerivedMember
.getInt();
1760 /// Get the class which the declaration actually lives in.
1761 const CXXRecordDecl
*getContainingRecord() const {
1762 return cast
<CXXRecordDecl
>(
1763 DeclAndIsDerivedMember
.getPointer()->getDeclContext());
1766 void moveInto(APValue
&V
) const {
1767 V
= APValue(getDecl(), isDerivedMember(), Path
);
1769 void setFrom(const APValue
&V
) {
1770 assert(V
.isMemberPointer());
1771 DeclAndIsDerivedMember
.setPointer(V
.getMemberPointerDecl());
1772 DeclAndIsDerivedMember
.setInt(V
.isMemberPointerToDerivedMember());
1774 ArrayRef
<const CXXRecordDecl
*> P
= V
.getMemberPointerPath();
1775 Path
.insert(Path
.end(), P
.begin(), P
.end());
1778 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1779 /// whether the member is a member of some class derived from the class type
1780 /// of the member pointer.
1781 llvm::PointerIntPair
<const ValueDecl
*, 1, bool> DeclAndIsDerivedMember
;
1782 /// Path - The path of base/derived classes from the member declaration's
1783 /// class (exclusive) to the class type of the member pointer (inclusive).
1784 SmallVector
<const CXXRecordDecl
*, 4> Path
;
1786 /// Perform a cast towards the class of the Decl (either up or down the
1788 bool castBack(const CXXRecordDecl
*Class
) {
1789 assert(!Path
.empty());
1790 const CXXRecordDecl
*Expected
;
1791 if (Path
.size() >= 2)
1792 Expected
= Path
[Path
.size() - 2];
1794 Expected
= getContainingRecord();
1795 if (Expected
->getCanonicalDecl() != Class
->getCanonicalDecl()) {
1796 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1797 // if B does not contain the original member and is not a base or
1798 // derived class of the class containing the original member, the result
1799 // of the cast is undefined.
1800 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1801 // (D::*). We consider that to be a language defect.
1807 /// Perform a base-to-derived member pointer cast.
1808 bool castToDerived(const CXXRecordDecl
*Derived
) {
1811 if (!isDerivedMember()) {
1812 Path
.push_back(Derived
);
1815 if (!castBack(Derived
))
1818 DeclAndIsDerivedMember
.setInt(false);
1821 /// Perform a derived-to-base member pointer cast.
1822 bool castToBase(const CXXRecordDecl
*Base
) {
1826 DeclAndIsDerivedMember
.setInt(true);
1827 if (isDerivedMember()) {
1828 Path
.push_back(Base
);
1831 return castBack(Base
);
1835 /// Compare two member pointers, which are assumed to be of the same type.
1836 static bool operator==(const MemberPtr
&LHS
, const MemberPtr
&RHS
) {
1837 if (!LHS
.getDecl() || !RHS
.getDecl())
1838 return !LHS
.getDecl() && !RHS
.getDecl();
1839 if (LHS
.getDecl()->getCanonicalDecl() != RHS
.getDecl()->getCanonicalDecl())
1841 return LHS
.Path
== RHS
.Path
;
1845 static bool Evaluate(APValue
&Result
, EvalInfo
&Info
, const Expr
*E
);
1846 static bool EvaluateInPlace(APValue
&Result
, EvalInfo
&Info
,
1847 const LValue
&This
, const Expr
*E
,
1848 bool AllowNonLiteralTypes
= false);
1849 static bool EvaluateLValue(const Expr
*E
, LValue
&Result
, EvalInfo
&Info
,
1850 bool InvalidBaseOK
= false);
1851 static bool EvaluatePointer(const Expr
*E
, LValue
&Result
, EvalInfo
&Info
,
1852 bool InvalidBaseOK
= false);
1853 static bool EvaluateMemberPointer(const Expr
*E
, MemberPtr
&Result
,
1855 static bool EvaluateTemporary(const Expr
*E
, LValue
&Result
, EvalInfo
&Info
);
1856 static bool EvaluateInteger(const Expr
*E
, APSInt
&Result
, EvalInfo
&Info
);
1857 static bool EvaluateIntegerOrLValue(const Expr
*E
, APValue
&Result
,
1859 static bool EvaluateFloat(const Expr
*E
, APFloat
&Result
, EvalInfo
&Info
);
1860 static bool EvaluateComplex(const Expr
*E
, ComplexValue
&Res
, EvalInfo
&Info
);
1861 static bool EvaluateAtomic(const Expr
*E
, const LValue
*This
, APValue
&Result
,
1863 static bool EvaluateAsRValue(EvalInfo
&Info
, const Expr
*E
, APValue
&Result
);
1864 static bool EvaluateBuiltinStrLen(const Expr
*E
, uint64_t &Result
,
1867 /// Evaluate an integer or fixed point expression into an APResult.
1868 static bool EvaluateFixedPointOrInteger(const Expr
*E
, APFixedPoint
&Result
,
1871 /// Evaluate only a fixed point expression into an APResult.
1872 static bool EvaluateFixedPoint(const Expr
*E
, APFixedPoint
&Result
,
1875 //===----------------------------------------------------------------------===//
1877 //===----------------------------------------------------------------------===//
1879 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1880 /// preserving its value (by extending by up to one bit as needed).
1881 static void negateAsSigned(APSInt
&Int
) {
1882 if (Int
.isUnsigned() || Int
.isMinSignedValue()) {
1883 Int
= Int
.extend(Int
.getBitWidth() + 1);
1884 Int
.setIsSigned(true);
1889 template<typename KeyT
>
1890 APValue
&CallStackFrame::createTemporary(const KeyT
*Key
, QualType T
,
1891 ScopeKind Scope
, LValue
&LV
) {
1892 unsigned Version
= getTempVersion();
1893 APValue::LValueBase
Base(Key
, Index
, Version
);
1895 return createLocal(Base
, Key
, T
, Scope
);
1898 /// Allocate storage for a parameter of a function call made in this frame.
1899 APValue
&CallStackFrame::createParam(CallRef Args
, const ParmVarDecl
*PVD
,
1901 assert(Args
.CallIndex
== Index
&& "creating parameter in wrong frame");
1902 APValue::LValueBase
Base(PVD
, Index
, Args
.Version
);
1904 // We always destroy parameters at the end of the call, even if we'd allow
1905 // them to live to the end of the full-expression at runtime, in order to
1906 // give portable results and match other compilers.
1907 return createLocal(Base
, PVD
, PVD
->getType(), ScopeKind::Call
);
1910 APValue
&CallStackFrame::createLocal(APValue::LValueBase Base
, const void *Key
,
1911 QualType T
, ScopeKind Scope
) {
1912 assert(Base
.getCallIndex() == Index
&& "lvalue for wrong frame");
1913 unsigned Version
= Base
.getVersion();
1914 APValue
&Result
= Temporaries
[MapKeyTy(Key
, Version
)];
1915 assert(Result
.isAbsent() && "local created multiple times");
1917 // If we're creating a local immediately in the operand of a speculative
1918 // evaluation, don't register a cleanup to be run outside the speculative
1919 // evaluation context, since we won't actually be able to initialize this
1921 if (Index
<= Info
.SpeculativeEvaluationDepth
) {
1922 if (T
.isDestructedType())
1923 Info
.noteSideEffect();
1925 Info
.CleanupStack
.push_back(Cleanup(&Result
, Base
, T
, Scope
));
1930 APValue
*EvalInfo::createHeapAlloc(const Expr
*E
, QualType T
, LValue
&LV
) {
1931 if (NumHeapAllocs
> DynamicAllocLValue::getMaxIndex()) {
1932 FFDiag(E
, diag::note_constexpr_heap_alloc_limit_exceeded
);
1936 DynamicAllocLValue
DA(NumHeapAllocs
++);
1937 LV
.set(APValue::LValueBase::getDynamicAlloc(DA
, T
));
1938 auto Result
= HeapAllocs
.emplace(std::piecewise_construct
,
1939 std::forward_as_tuple(DA
), std::tuple
<>());
1940 assert(Result
.second
&& "reused a heap alloc index?");
1941 Result
.first
->second
.AllocExpr
= E
;
1942 return &Result
.first
->second
.Value
;
1945 /// Produce a string describing the given constexpr call.
1946 void CallStackFrame::describe(raw_ostream
&Out
) const {
1947 unsigned ArgIndex
= 0;
1949 isa
<CXXMethodDecl
>(Callee
) && !isa
<CXXConstructorDecl
>(Callee
) &&
1950 cast
<CXXMethodDecl
>(Callee
)->isImplicitObjectMemberFunction();
1953 Callee
->getNameForDiagnostic(Out
, Info
.Ctx
.getPrintingPolicy(),
1954 /*Qualified=*/false);
1956 if (This
&& IsMemberCall
) {
1957 if (const auto *MCE
= dyn_cast_if_present
<CXXMemberCallExpr
>(CallExpr
)) {
1958 const Expr
*Object
= MCE
->getImplicitObjectArgument();
1959 Object
->printPretty(Out
, /*Helper=*/nullptr, Info
.Ctx
.getPrintingPolicy(),
1961 if (Object
->getType()->isPointerType())
1965 } else if (const auto *OCE
=
1966 dyn_cast_if_present
<CXXOperatorCallExpr
>(CallExpr
)) {
1967 OCE
->getArg(0)->printPretty(Out
, /*Helper=*/nullptr,
1968 Info
.Ctx
.getPrintingPolicy(),
1973 This
->moveInto(Val
);
1976 Info
.Ctx
.getLValueReferenceType(This
->Designator
.MostDerivedType
));
1979 Callee
->getNameForDiagnostic(Out
, Info
.Ctx
.getPrintingPolicy(),
1980 /*Qualified=*/false);
1981 IsMemberCall
= false;
1986 for (FunctionDecl::param_const_iterator I
= Callee
->param_begin(),
1987 E
= Callee
->param_end(); I
!= E
; ++I
, ++ArgIndex
) {
1988 if (ArgIndex
> (unsigned)IsMemberCall
)
1991 const ParmVarDecl
*Param
= *I
;
1992 APValue
*V
= Info
.getParamSlot(Arguments
, Param
);
1994 V
->printPretty(Out
, Info
.Ctx
, Param
->getType());
1998 if (ArgIndex
== 0 && IsMemberCall
)
1999 Out
<< "->" << *Callee
<< '(';
2005 /// Evaluate an expression to see if it had side-effects, and discard its
2007 /// \return \c true if the caller should keep evaluating.
2008 static bool EvaluateIgnoredValue(EvalInfo
&Info
, const Expr
*E
) {
2009 assert(!E
->isValueDependent());
2011 if (!Evaluate(Scratch
, Info
, E
))
2012 // We don't need the value, but we might have skipped a side effect here.
2013 return Info
.noteSideEffect();
2017 /// Should this call expression be treated as a no-op?
2018 static bool IsNoOpCall(const CallExpr
*E
) {
2019 unsigned Builtin
= E
->getBuiltinCallee();
2020 return (Builtin
== Builtin::BI__builtin___CFStringMakeConstantString
||
2021 Builtin
== Builtin::BI__builtin___NSStringMakeConstantString
||
2022 Builtin
== Builtin::BI__builtin_function_start
);
2025 static bool IsGlobalLValue(APValue::LValueBase B
) {
2026 // C++11 [expr.const]p3 An address constant expression is a prvalue core
2027 // constant expression of pointer type that evaluates to...
2029 // ... a null pointer value, or a prvalue core constant expression of type
2034 if (const ValueDecl
*D
= B
.dyn_cast
<const ValueDecl
*>()) {
2035 // ... the address of an object with static storage duration,
2036 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(D
))
2037 return VD
->hasGlobalStorage();
2038 if (isa
<TemplateParamObjectDecl
>(D
))
2040 // ... the address of a function,
2041 // ... the address of a GUID [MS extension],
2042 // ... the address of an unnamed global constant
2043 return isa
<FunctionDecl
, MSGuidDecl
, UnnamedGlobalConstantDecl
>(D
);
2046 if (B
.is
<TypeInfoLValue
>() || B
.is
<DynamicAllocLValue
>())
2049 const Expr
*E
= B
.get
<const Expr
*>();
2050 switch (E
->getStmtClass()) {
2053 case Expr::CompoundLiteralExprClass
: {
2054 const CompoundLiteralExpr
*CLE
= cast
<CompoundLiteralExpr
>(E
);
2055 return CLE
->isFileScope() && CLE
->isLValue();
2057 case Expr::MaterializeTemporaryExprClass
:
2058 // A materialized temporary might have been lifetime-extended to static
2059 // storage duration.
2060 return cast
<MaterializeTemporaryExpr
>(E
)->getStorageDuration() == SD_Static
;
2061 // A string literal has static storage duration.
2062 case Expr::StringLiteralClass
:
2063 case Expr::PredefinedExprClass
:
2064 case Expr::ObjCStringLiteralClass
:
2065 case Expr::ObjCEncodeExprClass
:
2067 case Expr::ObjCBoxedExprClass
:
2068 return cast
<ObjCBoxedExpr
>(E
)->isExpressibleAsConstantInitializer();
2069 case Expr::CallExprClass
:
2070 return IsNoOpCall(cast
<CallExpr
>(E
));
2071 // For GCC compatibility, &&label has static storage duration.
2072 case Expr::AddrLabelExprClass
:
2074 // A Block literal expression may be used as the initialization value for
2075 // Block variables at global or local static scope.
2076 case Expr::BlockExprClass
:
2077 return !cast
<BlockExpr
>(E
)->getBlockDecl()->hasCaptures();
2078 // The APValue generated from a __builtin_source_location will be emitted as a
2080 case Expr::SourceLocExprClass
:
2082 case Expr::ImplicitValueInitExprClass
:
2084 // We can never form an lvalue with an implicit value initialization as its
2085 // base through expression evaluation, so these only appear in one case: the
2086 // implicit variable declaration we invent when checking whether a constexpr
2087 // constructor can produce a constant expression. We must assume that such
2088 // an expression might be a global lvalue.
2093 static const ValueDecl
*GetLValueBaseDecl(const LValue
&LVal
) {
2094 return LVal
.Base
.dyn_cast
<const ValueDecl
*>();
2097 static bool IsLiteralLValue(const LValue
&Value
) {
2098 if (Value
.getLValueCallIndex())
2100 const Expr
*E
= Value
.Base
.dyn_cast
<const Expr
*>();
2101 return E
&& !isa
<MaterializeTemporaryExpr
>(E
);
2104 static bool IsWeakLValue(const LValue
&Value
) {
2105 const ValueDecl
*Decl
= GetLValueBaseDecl(Value
);
2106 return Decl
&& Decl
->isWeak();
2109 static bool isZeroSized(const LValue
&Value
) {
2110 const ValueDecl
*Decl
= GetLValueBaseDecl(Value
);
2111 if (Decl
&& isa
<VarDecl
>(Decl
)) {
2112 QualType Ty
= Decl
->getType();
2113 if (Ty
->isArrayType())
2114 return Ty
->isIncompleteType() ||
2115 Decl
->getASTContext().getTypeSize(Ty
) == 0;
2120 static bool HasSameBase(const LValue
&A
, const LValue
&B
) {
2121 if (!A
.getLValueBase())
2122 return !B
.getLValueBase();
2123 if (!B
.getLValueBase())
2126 if (A
.getLValueBase().getOpaqueValue() !=
2127 B
.getLValueBase().getOpaqueValue())
2130 return A
.getLValueCallIndex() == B
.getLValueCallIndex() &&
2131 A
.getLValueVersion() == B
.getLValueVersion();
2134 static void NoteLValueLocation(EvalInfo
&Info
, APValue::LValueBase Base
) {
2135 assert(Base
&& "no location for a null lvalue");
2136 const ValueDecl
*VD
= Base
.dyn_cast
<const ValueDecl
*>();
2138 // For a parameter, find the corresponding call stack frame (if it still
2139 // exists), and point at the parameter of the function definition we actually
2141 if (auto *PVD
= dyn_cast_or_null
<ParmVarDecl
>(VD
)) {
2142 unsigned Idx
= PVD
->getFunctionScopeIndex();
2143 for (CallStackFrame
*F
= Info
.CurrentCall
; F
; F
= F
->Caller
) {
2144 if (F
->Arguments
.CallIndex
== Base
.getCallIndex() &&
2145 F
->Arguments
.Version
== Base
.getVersion() && F
->Callee
&&
2146 Idx
< F
->Callee
->getNumParams()) {
2147 VD
= F
->Callee
->getParamDecl(Idx
);
2154 Info
.Note(VD
->getLocation(), diag::note_declared_at
);
2155 else if (const Expr
*E
= Base
.dyn_cast
<const Expr
*>())
2156 Info
.Note(E
->getExprLoc(), diag::note_constexpr_temporary_here
);
2157 else if (DynamicAllocLValue DA
= Base
.dyn_cast
<DynamicAllocLValue
>()) {
2158 // FIXME: Produce a note for dangling pointers too.
2159 if (std::optional
<DynAlloc
*> Alloc
= Info
.lookupDynamicAlloc(DA
))
2160 Info
.Note((*Alloc
)->AllocExpr
->getExprLoc(),
2161 diag::note_constexpr_dynamic_alloc_here
);
2164 // We have no information to show for a typeid(T) object.
2167 enum class CheckEvaluationResultKind
{
2172 /// Materialized temporaries that we've already checked to determine if they're
2173 /// initializsed by a constant expression.
2174 using CheckedTemporaries
=
2175 llvm::SmallPtrSet
<const MaterializeTemporaryExpr
*, 8>;
2177 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK
,
2178 EvalInfo
&Info
, SourceLocation DiagLoc
,
2179 QualType Type
, const APValue
&Value
,
2180 ConstantExprKind Kind
,
2181 const FieldDecl
*SubobjectDecl
,
2182 CheckedTemporaries
&CheckedTemps
);
2184 /// Check that this reference or pointer core constant expression is a valid
2185 /// value for an address or reference constant expression. Return true if we
2186 /// can fold this expression, whether or not it's a constant expression.
2187 static bool CheckLValueConstantExpression(EvalInfo
&Info
, SourceLocation Loc
,
2188 QualType Type
, const LValue
&LVal
,
2189 ConstantExprKind Kind
,
2190 CheckedTemporaries
&CheckedTemps
) {
2191 bool IsReferenceType
= Type
->isReferenceType();
2193 APValue::LValueBase Base
= LVal
.getLValueBase();
2194 const SubobjectDesignator
&Designator
= LVal
.getLValueDesignator();
2196 const Expr
*BaseE
= Base
.dyn_cast
<const Expr
*>();
2197 const ValueDecl
*BaseVD
= Base
.dyn_cast
<const ValueDecl
*>();
2199 // Additional restrictions apply in a template argument. We only enforce the
2200 // C++20 restrictions here; additional syntactic and semantic restrictions
2201 // are applied elsewhere.
2202 if (isTemplateArgument(Kind
)) {
2203 int InvalidBaseKind
= -1;
2205 if (Base
.is
<TypeInfoLValue
>())
2206 InvalidBaseKind
= 0;
2207 else if (isa_and_nonnull
<StringLiteral
>(BaseE
))
2208 InvalidBaseKind
= 1;
2209 else if (isa_and_nonnull
<MaterializeTemporaryExpr
>(BaseE
) ||
2210 isa_and_nonnull
<LifetimeExtendedTemporaryDecl
>(BaseVD
))
2211 InvalidBaseKind
= 2;
2212 else if (auto *PE
= dyn_cast_or_null
<PredefinedExpr
>(BaseE
)) {
2213 InvalidBaseKind
= 3;
2214 Ident
= PE
->getIdentKindName();
2217 if (InvalidBaseKind
!= -1) {
2218 Info
.FFDiag(Loc
, diag::note_constexpr_invalid_template_arg
)
2219 << IsReferenceType
<< !Designator
.Entries
.empty() << InvalidBaseKind
2225 if (auto *FD
= dyn_cast_or_null
<FunctionDecl
>(BaseVD
);
2226 FD
&& FD
->isImmediateFunction()) {
2227 Info
.FFDiag(Loc
, diag::note_consteval_address_accessible
)
2228 << !Type
->isAnyPointerType();
2229 Info
.Note(FD
->getLocation(), diag::note_declared_at
);
2233 // Check that the object is a global. Note that the fake 'this' object we
2234 // manufacture when checking potential constant expressions is conservatively
2235 // assumed to be global here.
2236 if (!IsGlobalLValue(Base
)) {
2237 if (Info
.getLangOpts().CPlusPlus11
) {
2238 Info
.FFDiag(Loc
, diag::note_constexpr_non_global
, 1)
2239 << IsReferenceType
<< !Designator
.Entries
.empty() << !!BaseVD
2241 auto *VarD
= dyn_cast_or_null
<VarDecl
>(BaseVD
);
2242 if (VarD
&& VarD
->isConstexpr()) {
2243 // Non-static local constexpr variables have unintuitive semantics:
2244 // constexpr int a = 1;
2245 // constexpr const int *p = &a;
2246 // ... is invalid because the address of 'a' is not constant. Suggest
2247 // adding a 'static' in this case.
2248 Info
.Note(VarD
->getLocation(), diag::note_constexpr_not_static
)
2250 << FixItHint::CreateInsertion(VarD
->getBeginLoc(), "static ");
2252 NoteLValueLocation(Info
, Base
);
2257 // Don't allow references to temporaries to escape.
2260 assert((Info
.checkingPotentialConstantExpression() ||
2261 LVal
.getLValueCallIndex() == 0) &&
2262 "have call index for global lvalue");
2264 if (Base
.is
<DynamicAllocLValue
>()) {
2265 Info
.FFDiag(Loc
, diag::note_constexpr_dynamic_alloc
)
2266 << IsReferenceType
<< !Designator
.Entries
.empty();
2267 NoteLValueLocation(Info
, Base
);
2272 if (const VarDecl
*Var
= dyn_cast
<const VarDecl
>(BaseVD
)) {
2273 // Check if this is a thread-local variable.
2274 if (Var
->getTLSKind())
2275 // FIXME: Diagnostic!
2278 // A dllimport variable never acts like a constant, unless we're
2279 // evaluating a value for use only in name mangling.
2280 if (!isForManglingOnly(Kind
) && Var
->hasAttr
<DLLImportAttr
>())
2281 // FIXME: Diagnostic!
2284 // In CUDA/HIP device compilation, only device side variables have
2285 // constant addresses.
2286 if (Info
.getCtx().getLangOpts().CUDA
&&
2287 Info
.getCtx().getLangOpts().CUDAIsDevice
&&
2288 Info
.getCtx().CUDAConstantEvalCtx
.NoWrongSidedVars
) {
2289 if ((!Var
->hasAttr
<CUDADeviceAttr
>() &&
2290 !Var
->hasAttr
<CUDAConstantAttr
>() &&
2291 !Var
->getType()->isCUDADeviceBuiltinSurfaceType() &&
2292 !Var
->getType()->isCUDADeviceBuiltinTextureType()) ||
2293 Var
->hasAttr
<HIPManagedAttr
>())
2297 if (const auto *FD
= dyn_cast
<const FunctionDecl
>(BaseVD
)) {
2298 // __declspec(dllimport) must be handled very carefully:
2299 // We must never initialize an expression with the thunk in C++.
2300 // Doing otherwise would allow the same id-expression to yield
2301 // different addresses for the same function in different translation
2302 // units. However, this means that we must dynamically initialize the
2303 // expression with the contents of the import address table at runtime.
2305 // The C language has no notion of ODR; furthermore, it has no notion of
2306 // dynamic initialization. This means that we are permitted to
2307 // perform initialization with the address of the thunk.
2308 if (Info
.getLangOpts().CPlusPlus
&& !isForManglingOnly(Kind
) &&
2309 FD
->hasAttr
<DLLImportAttr
>())
2310 // FIXME: Diagnostic!
2313 } else if (const auto *MTE
=
2314 dyn_cast_or_null
<MaterializeTemporaryExpr
>(BaseE
)) {
2315 if (CheckedTemps
.insert(MTE
).second
) {
2316 QualType TempType
= getType(Base
);
2317 if (TempType
.isDestructedType()) {
2318 Info
.FFDiag(MTE
->getExprLoc(),
2319 diag::note_constexpr_unsupported_temporary_nontrivial_dtor
)
2324 APValue
*V
= MTE
->getOrCreateValue(false);
2325 assert(V
&& "evasluation result refers to uninitialised temporary");
2326 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression
,
2327 Info
, MTE
->getExprLoc(), TempType
, *V
, Kind
,
2328 /*SubobjectDecl=*/nullptr, CheckedTemps
))
2333 // Allow address constant expressions to be past-the-end pointers. This is
2334 // an extension: the standard requires them to point to an object.
2335 if (!IsReferenceType
)
2338 // A reference constant expression must refer to an object.
2340 // FIXME: diagnostic
2345 // Does this refer one past the end of some object?
2346 if (!Designator
.Invalid
&& Designator
.isOnePastTheEnd()) {
2347 Info
.FFDiag(Loc
, diag::note_constexpr_past_end
, 1)
2348 << !Designator
.Entries
.empty() << !!BaseVD
<< BaseVD
;
2349 NoteLValueLocation(Info
, Base
);
2355 /// Member pointers are constant expressions unless they point to a
2356 /// non-virtual dllimport member function.
2357 static bool CheckMemberPointerConstantExpression(EvalInfo
&Info
,
2360 const APValue
&Value
,
2361 ConstantExprKind Kind
) {
2362 const ValueDecl
*Member
= Value
.getMemberPointerDecl();
2363 const auto *FD
= dyn_cast_or_null
<CXXMethodDecl
>(Member
);
2366 if (FD
->isImmediateFunction()) {
2367 Info
.FFDiag(Loc
, diag::note_consteval_address_accessible
) << /*pointer*/ 0;
2368 Info
.Note(FD
->getLocation(), diag::note_declared_at
);
2371 return isForManglingOnly(Kind
) || FD
->isVirtual() ||
2372 !FD
->hasAttr
<DLLImportAttr
>();
2375 /// Check that this core constant expression is of literal type, and if not,
2376 /// produce an appropriate diagnostic.
2377 static bool CheckLiteralType(EvalInfo
&Info
, const Expr
*E
,
2378 const LValue
*This
= nullptr) {
2379 if (!E
->isPRValue() || E
->getType()->isLiteralType(Info
.Ctx
))
2382 // C++1y: A constant initializer for an object o [...] may also invoke
2383 // constexpr constructors for o and its subobjects even if those objects
2384 // are of non-literal class types.
2386 // C++11 missed this detail for aggregates, so classes like this:
2387 // struct foo_t { union { int i; volatile int j; } u; };
2388 // are not (obviously) initializable like so:
2389 // __attribute__((__require_constant_initialization__))
2390 // static const foo_t x = {{0}};
2391 // because "i" is a subobject with non-literal initialization (due to the
2392 // volatile member of the union). See:
2393 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2394 // Therefore, we use the C++1y behavior.
2395 if (This
&& Info
.EvaluatingDecl
== This
->getLValueBase())
2398 // Prvalue constant expressions must be of literal types.
2399 if (Info
.getLangOpts().CPlusPlus11
)
2400 Info
.FFDiag(E
, diag::note_constexpr_nonliteral
)
2403 Info
.FFDiag(E
, diag::note_invalid_subexpr_in_const_expr
);
2407 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK
,
2408 EvalInfo
&Info
, SourceLocation DiagLoc
,
2409 QualType Type
, const APValue
&Value
,
2410 ConstantExprKind Kind
,
2411 const FieldDecl
*SubobjectDecl
,
2412 CheckedTemporaries
&CheckedTemps
) {
2413 if (!Value
.hasValue()) {
2414 if (SubobjectDecl
) {
2415 Info
.FFDiag(DiagLoc
, diag::note_constexpr_uninitialized
)
2416 << /*(name)*/ 1 << SubobjectDecl
;
2417 Info
.Note(SubobjectDecl
->getLocation(),
2418 diag::note_constexpr_subobject_declared_here
);
2420 Info
.FFDiag(DiagLoc
, diag::note_constexpr_uninitialized
)
2421 << /*of type*/ 0 << Type
;
2426 // We allow _Atomic(T) to be initialized from anything that T can be
2427 // initialized from.
2428 if (const AtomicType
*AT
= Type
->getAs
<AtomicType
>())
2429 Type
= AT
->getValueType();
2431 // Core issue 1454: For a literal constant expression of array or class type,
2432 // each subobject of its value shall have been initialized by a constant
2434 if (Value
.isArray()) {
2435 QualType EltTy
= Type
->castAsArrayTypeUnsafe()->getElementType();
2436 for (unsigned I
= 0, N
= Value
.getArrayInitializedElts(); I
!= N
; ++I
) {
2437 if (!CheckEvaluationResult(CERK
, Info
, DiagLoc
, EltTy
,
2438 Value
.getArrayInitializedElt(I
), Kind
,
2439 SubobjectDecl
, CheckedTemps
))
2442 if (!Value
.hasArrayFiller())
2444 return CheckEvaluationResult(CERK
, Info
, DiagLoc
, EltTy
,
2445 Value
.getArrayFiller(), Kind
, SubobjectDecl
,
2448 if (Value
.isUnion() && Value
.getUnionField()) {
2449 return CheckEvaluationResult(
2450 CERK
, Info
, DiagLoc
, Value
.getUnionField()->getType(),
2451 Value
.getUnionValue(), Kind
, Value
.getUnionField(), CheckedTemps
);
2453 if (Value
.isStruct()) {
2454 RecordDecl
*RD
= Type
->castAs
<RecordType
>()->getDecl();
2455 if (const CXXRecordDecl
*CD
= dyn_cast
<CXXRecordDecl
>(RD
)) {
2456 unsigned BaseIndex
= 0;
2457 for (const CXXBaseSpecifier
&BS
: CD
->bases()) {
2458 const APValue
&BaseValue
= Value
.getStructBase(BaseIndex
);
2459 if (!BaseValue
.hasValue()) {
2460 SourceLocation TypeBeginLoc
= BS
.getBaseTypeLoc();
2461 Info
.FFDiag(TypeBeginLoc
, diag::note_constexpr_uninitialized_base
)
2462 << BS
.getType() << SourceRange(TypeBeginLoc
, BS
.getEndLoc());
2465 if (!CheckEvaluationResult(CERK
, Info
, DiagLoc
, BS
.getType(), BaseValue
,
2466 Kind
, /*SubobjectDecl=*/nullptr,
2472 for (const auto *I
: RD
->fields()) {
2473 if (I
->isUnnamedBitfield())
2476 if (!CheckEvaluationResult(CERK
, Info
, DiagLoc
, I
->getType(),
2477 Value
.getStructField(I
->getFieldIndex()), Kind
,
2483 if (Value
.isLValue() &&
2484 CERK
== CheckEvaluationResultKind::ConstantExpression
) {
2486 LVal
.setFrom(Info
.Ctx
, Value
);
2487 return CheckLValueConstantExpression(Info
, DiagLoc
, Type
, LVal
, Kind
,
2491 if (Value
.isMemberPointer() &&
2492 CERK
== CheckEvaluationResultKind::ConstantExpression
)
2493 return CheckMemberPointerConstantExpression(Info
, DiagLoc
, Type
, Value
, Kind
);
2495 // Everything else is fine.
2499 /// Check that this core constant expression value is a valid value for a
2500 /// constant expression. If not, report an appropriate diagnostic. Does not
2501 /// check that the expression is of literal type.
2502 static bool CheckConstantExpression(EvalInfo
&Info
, SourceLocation DiagLoc
,
2503 QualType Type
, const APValue
&Value
,
2504 ConstantExprKind Kind
) {
2505 // Nothing to check for a constant expression of type 'cv void'.
2506 if (Type
->isVoidType())
2509 CheckedTemporaries CheckedTemps
;
2510 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression
,
2511 Info
, DiagLoc
, Type
, Value
, Kind
,
2512 /*SubobjectDecl=*/nullptr, CheckedTemps
);
2515 /// Check that this evaluated value is fully-initialized and can be loaded by
2516 /// an lvalue-to-rvalue conversion.
2517 static bool CheckFullyInitialized(EvalInfo
&Info
, SourceLocation DiagLoc
,
2518 QualType Type
, const APValue
&Value
) {
2519 CheckedTemporaries CheckedTemps
;
2520 return CheckEvaluationResult(
2521 CheckEvaluationResultKind::FullyInitialized
, Info
, DiagLoc
, Type
, Value
,
2522 ConstantExprKind::Normal
, /*SubobjectDecl=*/nullptr, CheckedTemps
);
2525 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2526 /// "the allocated storage is deallocated within the evaluation".
2527 static bool CheckMemoryLeaks(EvalInfo
&Info
) {
2528 if (!Info
.HeapAllocs
.empty()) {
2529 // We can still fold to a constant despite a compile-time memory leak,
2530 // so long as the heap allocation isn't referenced in the result (we check
2531 // that in CheckConstantExpression).
2532 Info
.CCEDiag(Info
.HeapAllocs
.begin()->second
.AllocExpr
,
2533 diag::note_constexpr_memory_leak
)
2534 << unsigned(Info
.HeapAllocs
.size() - 1);
2539 static bool EvalPointerValueAsBool(const APValue
&Value
, bool &Result
) {
2540 // A null base expression indicates a null pointer. These are always
2541 // evaluatable, and they are false unless the offset is zero.
2542 if (!Value
.getLValueBase()) {
2543 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2544 Result
= !Value
.getLValueOffset().isZero();
2548 // We have a non-null base. These are generally known to be true, but if it's
2549 // a weak declaration it can be null at runtime.
2551 const ValueDecl
*Decl
= Value
.getLValueBase().dyn_cast
<const ValueDecl
*>();
2552 return !Decl
|| !Decl
->isWeak();
2555 static bool HandleConversionToBool(const APValue
&Val
, bool &Result
) {
2556 // TODO: This function should produce notes if it fails.
2557 switch (Val
.getKind()) {
2559 case APValue::Indeterminate
:
2562 Result
= Val
.getInt().getBoolValue();
2564 case APValue::FixedPoint
:
2565 Result
= Val
.getFixedPoint().getBoolValue();
2567 case APValue::Float
:
2568 Result
= !Val
.getFloat().isZero();
2570 case APValue::ComplexInt
:
2571 Result
= Val
.getComplexIntReal().getBoolValue() ||
2572 Val
.getComplexIntImag().getBoolValue();
2574 case APValue::ComplexFloat
:
2575 Result
= !Val
.getComplexFloatReal().isZero() ||
2576 !Val
.getComplexFloatImag().isZero();
2578 case APValue::LValue
:
2579 return EvalPointerValueAsBool(Val
, Result
);
2580 case APValue::MemberPointer
:
2581 if (Val
.getMemberPointerDecl() && Val
.getMemberPointerDecl()->isWeak()) {
2584 Result
= Val
.getMemberPointerDecl();
2586 case APValue::Vector
:
2587 case APValue::Array
:
2588 case APValue::Struct
:
2589 case APValue::Union
:
2590 case APValue::AddrLabelDiff
:
2594 llvm_unreachable("unknown APValue kind");
2597 static bool EvaluateAsBooleanCondition(const Expr
*E
, bool &Result
,
2599 assert(!E
->isValueDependent());
2600 assert(E
->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2602 if (!Evaluate(Val
, Info
, E
))
2604 return HandleConversionToBool(Val
, Result
);
2607 template<typename T
>
2608 static bool HandleOverflow(EvalInfo
&Info
, const Expr
*E
,
2609 const T
&SrcValue
, QualType DestType
) {
2610 Info
.CCEDiag(E
, diag::note_constexpr_overflow
)
2611 << SrcValue
<< DestType
;
2612 return Info
.noteUndefinedBehavior();
2615 static bool HandleFloatToIntCast(EvalInfo
&Info
, const Expr
*E
,
2616 QualType SrcType
, const APFloat
&Value
,
2617 QualType DestType
, APSInt
&Result
) {
2618 unsigned DestWidth
= Info
.Ctx
.getIntWidth(DestType
);
2619 // Determine whether we are converting to unsigned or signed.
2620 bool DestSigned
= DestType
->isSignedIntegerOrEnumerationType();
2622 Result
= APSInt(DestWidth
, !DestSigned
);
2624 if (Value
.convertToInteger(Result
, llvm::APFloat::rmTowardZero
, &ignored
)
2625 & APFloat::opInvalidOp
)
2626 return HandleOverflow(Info
, E
, Value
, DestType
);
2630 /// Get rounding mode to use in evaluation of the specified expression.
2632 /// If rounding mode is unknown at compile time, still try to evaluate the
2633 /// expression. If the result is exact, it does not depend on rounding mode.
2634 /// So return "tonearest" mode instead of "dynamic".
2635 static llvm::RoundingMode
getActiveRoundingMode(EvalInfo
&Info
, const Expr
*E
) {
2636 llvm::RoundingMode RM
=
2637 E
->getFPFeaturesInEffect(Info
.Ctx
.getLangOpts()).getRoundingMode();
2638 if (RM
== llvm::RoundingMode::Dynamic
)
2639 RM
= llvm::RoundingMode::NearestTiesToEven
;
2643 /// Check if the given evaluation result is allowed for constant evaluation.
2644 static bool checkFloatingPointResult(EvalInfo
&Info
, const Expr
*E
,
2645 APFloat::opStatus St
) {
2646 // In a constant context, assume that any dynamic rounding mode or FP
2647 // exception state matches the default floating-point environment.
2648 if (Info
.InConstantContext
)
2651 FPOptions FPO
= E
->getFPFeaturesInEffect(Info
.Ctx
.getLangOpts());
2652 if ((St
& APFloat::opInexact
) &&
2653 FPO
.getRoundingMode() == llvm::RoundingMode::Dynamic
) {
2654 // Inexact result means that it depends on rounding mode. If the requested
2655 // mode is dynamic, the evaluation cannot be made in compile time.
2656 Info
.FFDiag(E
, diag::note_constexpr_dynamic_rounding
);
2660 if ((St
!= APFloat::opOK
) &&
2661 (FPO
.getRoundingMode() == llvm::RoundingMode::Dynamic
||
2662 FPO
.getExceptionMode() != LangOptions::FPE_Ignore
||
2663 FPO
.getAllowFEnvAccess())) {
2664 Info
.FFDiag(E
, diag::note_constexpr_float_arithmetic_strict
);
2668 if ((St
& APFloat::opStatus::opInvalidOp
) &&
2669 FPO
.getExceptionMode() != LangOptions::FPE_Ignore
) {
2670 // There is no usefully definable result.
2676 // - evaluation triggered other FP exception, and
2677 // - exception mode is not "ignore", and
2678 // - the expression being evaluated is not a part of global variable
2680 // the evaluation probably need to be rejected.
2684 static bool HandleFloatToFloatCast(EvalInfo
&Info
, const Expr
*E
,
2685 QualType SrcType
, QualType DestType
,
2687 assert(isa
<CastExpr
>(E
) || isa
<CompoundAssignOperator
>(E
));
2688 llvm::RoundingMode RM
= getActiveRoundingMode(Info
, E
);
2689 APFloat::opStatus St
;
2690 APFloat Value
= Result
;
2692 St
= Result
.convert(Info
.Ctx
.getFloatTypeSemantics(DestType
), RM
, &ignored
);
2693 return checkFloatingPointResult(Info
, E
, St
);
2696 static APSInt
HandleIntToIntCast(EvalInfo
&Info
, const Expr
*E
,
2697 QualType DestType
, QualType SrcType
,
2698 const APSInt
&Value
) {
2699 unsigned DestWidth
= Info
.Ctx
.getIntWidth(DestType
);
2700 // Figure out if this is a truncate, extend or noop cast.
2701 // If the input is signed, do a sign extend, noop, or truncate.
2702 APSInt Result
= Value
.extOrTrunc(DestWidth
);
2703 Result
.setIsUnsigned(DestType
->isUnsignedIntegerOrEnumerationType());
2704 if (DestType
->isBooleanType())
2705 Result
= Value
.getBoolValue();
2709 static bool HandleIntToFloatCast(EvalInfo
&Info
, const Expr
*E
,
2710 const FPOptions FPO
,
2711 QualType SrcType
, const APSInt
&Value
,
2712 QualType DestType
, APFloat
&Result
) {
2713 Result
= APFloat(Info
.Ctx
.getFloatTypeSemantics(DestType
), 1);
2714 llvm::RoundingMode RM
= getActiveRoundingMode(Info
, E
);
2715 APFloat::opStatus St
= Result
.convertFromAPInt(Value
, Value
.isSigned(), RM
);
2716 return checkFloatingPointResult(Info
, E
, St
);
2719 static bool truncateBitfieldValue(EvalInfo
&Info
, const Expr
*E
,
2720 APValue
&Value
, const FieldDecl
*FD
) {
2721 assert(FD
->isBitField() && "truncateBitfieldValue on non-bitfield");
2723 if (!Value
.isInt()) {
2724 // Trying to store a pointer-cast-to-integer into a bitfield.
2725 // FIXME: In this case, we should provide the diagnostic for casting
2726 // a pointer to an integer.
2727 assert(Value
.isLValue() && "integral value neither int nor lvalue?");
2732 APSInt
&Int
= Value
.getInt();
2733 unsigned OldBitWidth
= Int
.getBitWidth();
2734 unsigned NewBitWidth
= FD
->getBitWidthValue(Info
.Ctx
);
2735 if (NewBitWidth
< OldBitWidth
)
2736 Int
= Int
.trunc(NewBitWidth
).extend(OldBitWidth
);
2740 /// Perform the given integer operation, which is known to need at most BitWidth
2741 /// bits, and check for overflow in the original type (if that type was not an
2743 template<typename Operation
>
2744 static bool CheckedIntArithmetic(EvalInfo
&Info
, const Expr
*E
,
2745 const APSInt
&LHS
, const APSInt
&RHS
,
2746 unsigned BitWidth
, Operation Op
,
2748 if (LHS
.isUnsigned()) {
2749 Result
= Op(LHS
, RHS
);
2753 APSInt
Value(Op(LHS
.extend(BitWidth
), RHS
.extend(BitWidth
)), false);
2754 Result
= Value
.trunc(LHS
.getBitWidth());
2755 if (Result
.extend(BitWidth
) != Value
) {
2756 if (Info
.checkingForUndefinedBehavior())
2757 Info
.Ctx
.getDiagnostics().Report(E
->getExprLoc(),
2758 diag::warn_integer_constant_overflow
)
2759 << toString(Result
, 10) << E
->getType() << E
->getSourceRange();
2760 return HandleOverflow(Info
, E
, Value
, E
->getType());
2765 /// Perform the given binary integer operation.
2766 static bool handleIntIntBinOp(EvalInfo
&Info
, const BinaryOperator
*E
,
2767 const APSInt
&LHS
, BinaryOperatorKind Opcode
,
2768 APSInt RHS
, APSInt
&Result
) {
2769 bool HandleOverflowResult
= true;
2775 return CheckedIntArithmetic(Info
, E
, LHS
, RHS
, LHS
.getBitWidth() * 2,
2776 std::multiplies
<APSInt
>(), Result
);
2778 return CheckedIntArithmetic(Info
, E
, LHS
, RHS
, LHS
.getBitWidth() + 1,
2779 std::plus
<APSInt
>(), Result
);
2781 return CheckedIntArithmetic(Info
, E
, LHS
, RHS
, LHS
.getBitWidth() + 1,
2782 std::minus
<APSInt
>(), Result
);
2783 case BO_And
: Result
= LHS
& RHS
; return true;
2784 case BO_Xor
: Result
= LHS
^ RHS
; return true;
2785 case BO_Or
: Result
= LHS
| RHS
; return true;
2789 Info
.FFDiag(E
, diag::note_expr_divide_by_zero
)
2790 << E
->getRHS()->getSourceRange();
2793 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2794 // this operation and gives the two's complement result.
2795 if (RHS
.isNegative() && RHS
.isAllOnes() && LHS
.isSigned() &&
2796 LHS
.isMinSignedValue())
2797 HandleOverflowResult
= HandleOverflow(
2798 Info
, E
, -LHS
.extend(LHS
.getBitWidth() + 1), E
->getType());
2799 Result
= (Opcode
== BO_Rem
? LHS
% RHS
: LHS
/ RHS
);
2800 return HandleOverflowResult
;
2802 if (Info
.getLangOpts().OpenCL
)
2803 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2804 RHS
&= APSInt(llvm::APInt(RHS
.getBitWidth(),
2805 static_cast<uint64_t>(LHS
.getBitWidth() - 1)),
2807 else if (RHS
.isSigned() && RHS
.isNegative()) {
2808 // During constant-folding, a negative shift is an opposite shift. Such
2809 // a shift is not a constant expression.
2810 Info
.CCEDiag(E
, diag::note_constexpr_negative_shift
) << RHS
;
2815 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2816 // the shifted type.
2817 unsigned SA
= (unsigned) RHS
.getLimitedValue(LHS
.getBitWidth()-1);
2819 Info
.CCEDiag(E
, diag::note_constexpr_large_shift
)
2820 << RHS
<< E
->getType() << LHS
.getBitWidth();
2821 } else if (LHS
.isSigned() && !Info
.getLangOpts().CPlusPlus20
) {
2822 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2823 // operand, and must not overflow the corresponding unsigned type.
2824 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2825 // E1 x 2^E2 module 2^N.
2826 if (LHS
.isNegative())
2827 Info
.CCEDiag(E
, diag::note_constexpr_lshift_of_negative
) << LHS
;
2828 else if (LHS
.countl_zero() < SA
)
2829 Info
.CCEDiag(E
, diag::note_constexpr_lshift_discards
);
2835 if (Info
.getLangOpts().OpenCL
)
2836 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2837 RHS
&= APSInt(llvm::APInt(RHS
.getBitWidth(),
2838 static_cast<uint64_t>(LHS
.getBitWidth() - 1)),
2840 else if (RHS
.isSigned() && RHS
.isNegative()) {
2841 // During constant-folding, a negative shift is an opposite shift. Such a
2842 // shift is not a constant expression.
2843 Info
.CCEDiag(E
, diag::note_constexpr_negative_shift
) << RHS
;
2848 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2850 unsigned SA
= (unsigned) RHS
.getLimitedValue(LHS
.getBitWidth()-1);
2852 Info
.CCEDiag(E
, diag::note_constexpr_large_shift
)
2853 << RHS
<< E
->getType() << LHS
.getBitWidth();
2858 case BO_LT
: Result
= LHS
< RHS
; return true;
2859 case BO_GT
: Result
= LHS
> RHS
; return true;
2860 case BO_LE
: Result
= LHS
<= RHS
; return true;
2861 case BO_GE
: Result
= LHS
>= RHS
; return true;
2862 case BO_EQ
: Result
= LHS
== RHS
; return true;
2863 case BO_NE
: Result
= LHS
!= RHS
; return true;
2865 llvm_unreachable("BO_Cmp should be handled elsewhere");
2869 /// Perform the given binary floating-point operation, in-place, on LHS.
2870 static bool handleFloatFloatBinOp(EvalInfo
&Info
, const BinaryOperator
*E
,
2871 APFloat
&LHS
, BinaryOperatorKind Opcode
,
2872 const APFloat
&RHS
) {
2873 llvm::RoundingMode RM
= getActiveRoundingMode(Info
, E
);
2874 APFloat::opStatus St
;
2880 St
= LHS
.multiply(RHS
, RM
);
2883 St
= LHS
.add(RHS
, RM
);
2886 St
= LHS
.subtract(RHS
, RM
);
2890 // If the second operand of / or % is zero the behavior is undefined.
2892 Info
.CCEDiag(E
, diag::note_expr_divide_by_zero
);
2893 St
= LHS
.divide(RHS
, RM
);
2898 // If during the evaluation of an expression, the result is not
2899 // mathematically defined [...], the behavior is undefined.
2900 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2902 Info
.CCEDiag(E
, diag::note_constexpr_float_arithmetic
) << LHS
.isNaN();
2903 return Info
.noteUndefinedBehavior();
2906 return checkFloatingPointResult(Info
, E
, St
);
2909 static bool handleLogicalOpForVector(const APInt
&LHSValue
,
2910 BinaryOperatorKind Opcode
,
2911 const APInt
&RHSValue
, APInt
&Result
) {
2912 bool LHS
= (LHSValue
!= 0);
2913 bool RHS
= (RHSValue
!= 0);
2915 if (Opcode
== BO_LAnd
)
2916 Result
= LHS
&& RHS
;
2918 Result
= LHS
|| RHS
;
2921 static bool handleLogicalOpForVector(const APFloat
&LHSValue
,
2922 BinaryOperatorKind Opcode
,
2923 const APFloat
&RHSValue
, APInt
&Result
) {
2924 bool LHS
= !LHSValue
.isZero();
2925 bool RHS
= !RHSValue
.isZero();
2927 if (Opcode
== BO_LAnd
)
2928 Result
= LHS
&& RHS
;
2930 Result
= LHS
|| RHS
;
2934 static bool handleLogicalOpForVector(const APValue
&LHSValue
,
2935 BinaryOperatorKind Opcode
,
2936 const APValue
&RHSValue
, APInt
&Result
) {
2937 // The result is always an int type, however operands match the first.
2938 if (LHSValue
.getKind() == APValue::Int
)
2939 return handleLogicalOpForVector(LHSValue
.getInt(), Opcode
,
2940 RHSValue
.getInt(), Result
);
2941 assert(LHSValue
.getKind() == APValue::Float
&& "Should be no other options");
2942 return handleLogicalOpForVector(LHSValue
.getFloat(), Opcode
,
2943 RHSValue
.getFloat(), Result
);
2946 template <typename APTy
>
2948 handleCompareOpForVectorHelper(const APTy
&LHSValue
, BinaryOperatorKind Opcode
,
2949 const APTy
&RHSValue
, APInt
&Result
) {
2952 llvm_unreachable("unsupported binary operator");
2954 Result
= (LHSValue
== RHSValue
);
2957 Result
= (LHSValue
!= RHSValue
);
2960 Result
= (LHSValue
< RHSValue
);
2963 Result
= (LHSValue
> RHSValue
);
2966 Result
= (LHSValue
<= RHSValue
);
2969 Result
= (LHSValue
>= RHSValue
);
2973 // The boolean operations on these vector types use an instruction that
2974 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
2975 // to -1 to make sure that we produce the correct value.
2981 static bool handleCompareOpForVector(const APValue
&LHSValue
,
2982 BinaryOperatorKind Opcode
,
2983 const APValue
&RHSValue
, APInt
&Result
) {
2984 // The result is always an int type, however operands match the first.
2985 if (LHSValue
.getKind() == APValue::Int
)
2986 return handleCompareOpForVectorHelper(LHSValue
.getInt(), Opcode
,
2987 RHSValue
.getInt(), Result
);
2988 assert(LHSValue
.getKind() == APValue::Float
&& "Should be no other options");
2989 return handleCompareOpForVectorHelper(LHSValue
.getFloat(), Opcode
,
2990 RHSValue
.getFloat(), Result
);
2993 // Perform binary operations for vector types, in place on the LHS.
2994 static bool handleVectorVectorBinOp(EvalInfo
&Info
, const BinaryOperator
*E
,
2995 BinaryOperatorKind Opcode
,
2997 const APValue
&RHSValue
) {
2998 assert(Opcode
!= BO_PtrMemD
&& Opcode
!= BO_PtrMemI
&&
2999 "Operation not supported on vector types");
3001 const auto *VT
= E
->getType()->castAs
<VectorType
>();
3002 unsigned NumElements
= VT
->getNumElements();
3003 QualType EltTy
= VT
->getElementType();
3005 // In the cases (typically C as I've observed) where we aren't evaluating
3006 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3008 if (!LHSValue
.isVector()) {
3009 assert(LHSValue
.isLValue() &&
3010 "A vector result that isn't a vector OR uncalculated LValue");
3015 assert(LHSValue
.getVectorLength() == NumElements
&&
3016 RHSValue
.getVectorLength() == NumElements
&& "Different vector sizes");
3018 SmallVector
<APValue
, 4> ResultElements
;
3020 for (unsigned EltNum
= 0; EltNum
< NumElements
; ++EltNum
) {
3021 APValue LHSElt
= LHSValue
.getVectorElt(EltNum
);
3022 APValue RHSElt
= RHSValue
.getVectorElt(EltNum
);
3024 if (EltTy
->isIntegerType()) {
3025 APSInt EltResult
{Info
.Ctx
.getIntWidth(EltTy
),
3026 EltTy
->isUnsignedIntegerType()};
3027 bool Success
= true;
3029 if (BinaryOperator::isLogicalOp(Opcode
))
3030 Success
= handleLogicalOpForVector(LHSElt
, Opcode
, RHSElt
, EltResult
);
3031 else if (BinaryOperator::isComparisonOp(Opcode
))
3032 Success
= handleCompareOpForVector(LHSElt
, Opcode
, RHSElt
, EltResult
);
3034 Success
= handleIntIntBinOp(Info
, E
, LHSElt
.getInt(), Opcode
,
3035 RHSElt
.getInt(), EltResult
);
3041 ResultElements
.emplace_back(EltResult
);
3043 } else if (EltTy
->isFloatingType()) {
3044 assert(LHSElt
.getKind() == APValue::Float
&&
3045 RHSElt
.getKind() == APValue::Float
&&
3046 "Mismatched LHS/RHS/Result Type");
3047 APFloat LHSFloat
= LHSElt
.getFloat();
3049 if (!handleFloatFloatBinOp(Info
, E
, LHSFloat
, Opcode
,
3050 RHSElt
.getFloat())) {
3055 ResultElements
.emplace_back(LHSFloat
);
3059 LHSValue
= APValue(ResultElements
.data(), ResultElements
.size());
3063 /// Cast an lvalue referring to a base subobject to a derived class, by
3064 /// truncating the lvalue's path to the given length.
3065 static bool CastToDerivedClass(EvalInfo
&Info
, const Expr
*E
, LValue
&Result
,
3066 const RecordDecl
*TruncatedType
,
3067 unsigned TruncatedElements
) {
3068 SubobjectDesignator
&D
= Result
.Designator
;
3070 // Check we actually point to a derived class object.
3071 if (TruncatedElements
== D
.Entries
.size())
3073 assert(TruncatedElements
>= D
.MostDerivedPathLength
&&
3074 "not casting to a derived class");
3075 if (!Result
.checkSubobject(Info
, E
, CSK_Derived
))
3078 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3079 const RecordDecl
*RD
= TruncatedType
;
3080 for (unsigned I
= TruncatedElements
, N
= D
.Entries
.size(); I
!= N
; ++I
) {
3081 if (RD
->isInvalidDecl()) return false;
3082 const ASTRecordLayout
&Layout
= Info
.Ctx
.getASTRecordLayout(RD
);
3083 const CXXRecordDecl
*Base
= getAsBaseClass(D
.Entries
[I
]);
3084 if (isVirtualBaseClass(D
.Entries
[I
]))
3085 Result
.Offset
-= Layout
.getVBaseClassOffset(Base
);
3087 Result
.Offset
-= Layout
.getBaseClassOffset(Base
);
3090 D
.Entries
.resize(TruncatedElements
);
3094 static bool HandleLValueDirectBase(EvalInfo
&Info
, const Expr
*E
, LValue
&Obj
,
3095 const CXXRecordDecl
*Derived
,
3096 const CXXRecordDecl
*Base
,
3097 const ASTRecordLayout
*RL
= nullptr) {
3099 if (Derived
->isInvalidDecl()) return false;
3100 RL
= &Info
.Ctx
.getASTRecordLayout(Derived
);
3103 Obj
.getLValueOffset() += RL
->getBaseClassOffset(Base
);
3104 Obj
.addDecl(Info
, E
, Base
, /*Virtual*/ false);
3108 static bool HandleLValueBase(EvalInfo
&Info
, const Expr
*E
, LValue
&Obj
,
3109 const CXXRecordDecl
*DerivedDecl
,
3110 const CXXBaseSpecifier
*Base
) {
3111 const CXXRecordDecl
*BaseDecl
= Base
->getType()->getAsCXXRecordDecl();
3113 if (!Base
->isVirtual())
3114 return HandleLValueDirectBase(Info
, E
, Obj
, DerivedDecl
, BaseDecl
);
3116 SubobjectDesignator
&D
= Obj
.Designator
;
3120 // Extract most-derived object and corresponding type.
3121 DerivedDecl
= D
.MostDerivedType
->getAsCXXRecordDecl();
3122 if (!CastToDerivedClass(Info
, E
, Obj
, DerivedDecl
, D
.MostDerivedPathLength
))
3125 // Find the virtual base class.
3126 if (DerivedDecl
->isInvalidDecl()) return false;
3127 const ASTRecordLayout
&Layout
= Info
.Ctx
.getASTRecordLayout(DerivedDecl
);
3128 Obj
.getLValueOffset() += Layout
.getVBaseClassOffset(BaseDecl
);
3129 Obj
.addDecl(Info
, E
, BaseDecl
, /*Virtual*/ true);
3133 static bool HandleLValueBasePath(EvalInfo
&Info
, const CastExpr
*E
,
3134 QualType Type
, LValue
&Result
) {
3135 for (CastExpr::path_const_iterator PathI
= E
->path_begin(),
3136 PathE
= E
->path_end();
3137 PathI
!= PathE
; ++PathI
) {
3138 if (!HandleLValueBase(Info
, E
, Result
, Type
->getAsCXXRecordDecl(),
3141 Type
= (*PathI
)->getType();
3146 /// Cast an lvalue referring to a derived class to a known base subobject.
3147 static bool CastToBaseClass(EvalInfo
&Info
, const Expr
*E
, LValue
&Result
,
3148 const CXXRecordDecl
*DerivedRD
,
3149 const CXXRecordDecl
*BaseRD
) {
3150 CXXBasePaths
Paths(/*FindAmbiguities=*/false,
3151 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3152 if (!DerivedRD
->isDerivedFrom(BaseRD
, Paths
))
3153 llvm_unreachable("Class must be derived from the passed in base class!");
3155 for (CXXBasePathElement
&Elem
: Paths
.front())
3156 if (!HandleLValueBase(Info
, E
, Result
, Elem
.Class
, Elem
.Base
))
3161 /// Update LVal to refer to the given field, which must be a member of the type
3162 /// currently described by LVal.
3163 static bool HandleLValueMember(EvalInfo
&Info
, const Expr
*E
, LValue
&LVal
,
3164 const FieldDecl
*FD
,
3165 const ASTRecordLayout
*RL
= nullptr) {
3167 if (FD
->getParent()->isInvalidDecl()) return false;
3168 RL
= &Info
.Ctx
.getASTRecordLayout(FD
->getParent());
3171 unsigned I
= FD
->getFieldIndex();
3172 LVal
.adjustOffset(Info
.Ctx
.toCharUnitsFromBits(RL
->getFieldOffset(I
)));
3173 LVal
.addDecl(Info
, E
, FD
);
3177 /// Update LVal to refer to the given indirect field.
3178 static bool HandleLValueIndirectMember(EvalInfo
&Info
, const Expr
*E
,
3180 const IndirectFieldDecl
*IFD
) {
3181 for (const auto *C
: IFD
->chain())
3182 if (!HandleLValueMember(Info
, E
, LVal
, cast
<FieldDecl
>(C
)))
3187 /// Get the size of the given type in char units.
3188 static bool HandleSizeof(EvalInfo
&Info
, SourceLocation Loc
,
3189 QualType Type
, CharUnits
&Size
) {
3190 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3192 if (Type
->isVoidType() || Type
->isFunctionType()) {
3193 Size
= CharUnits::One();
3197 if (Type
->isDependentType()) {
3202 if (!Type
->isConstantSizeType()) {
3203 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3204 // FIXME: Better diagnostic.
3209 Size
= Info
.Ctx
.getTypeSizeInChars(Type
);
3213 /// Update a pointer value to model pointer arithmetic.
3214 /// \param Info - Information about the ongoing evaluation.
3215 /// \param E - The expression being evaluated, for diagnostic purposes.
3216 /// \param LVal - The pointer value to be updated.
3217 /// \param EltTy - The pointee type represented by LVal.
3218 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3219 static bool HandleLValueArrayAdjustment(EvalInfo
&Info
, const Expr
*E
,
3220 LValue
&LVal
, QualType EltTy
,
3221 APSInt Adjustment
) {
3222 CharUnits SizeOfPointee
;
3223 if (!HandleSizeof(Info
, E
->getExprLoc(), EltTy
, SizeOfPointee
))
3226 LVal
.adjustOffsetAndIndex(Info
, E
, Adjustment
, SizeOfPointee
);
3230 static bool HandleLValueArrayAdjustment(EvalInfo
&Info
, const Expr
*E
,
3231 LValue
&LVal
, QualType EltTy
,
3232 int64_t Adjustment
) {
3233 return HandleLValueArrayAdjustment(Info
, E
, LVal
, EltTy
,
3234 APSInt::get(Adjustment
));
3237 /// Update an lvalue to refer to a component of a complex number.
3238 /// \param Info - Information about the ongoing evaluation.
3239 /// \param LVal - The lvalue to be updated.
3240 /// \param EltTy - The complex number's component type.
3241 /// \param Imag - False for the real component, true for the imaginary.
3242 static bool HandleLValueComplexElement(EvalInfo
&Info
, const Expr
*E
,
3243 LValue
&LVal
, QualType EltTy
,
3246 CharUnits SizeOfComponent
;
3247 if (!HandleSizeof(Info
, E
->getExprLoc(), EltTy
, SizeOfComponent
))
3249 LVal
.Offset
+= SizeOfComponent
;
3251 LVal
.addComplex(Info
, E
, EltTy
, Imag
);
3255 /// Try to evaluate the initializer for a variable declaration.
3257 /// \param Info Information about the ongoing evaluation.
3258 /// \param E An expression to be used when printing diagnostics.
3259 /// \param VD The variable whose initializer should be obtained.
3260 /// \param Version The version of the variable within the frame.
3261 /// \param Frame The frame in which the variable was created. Must be null
3262 /// if this variable is not local to the evaluation.
3263 /// \param Result Filled in with a pointer to the value of the variable.
3264 static bool evaluateVarDeclInit(EvalInfo
&Info
, const Expr
*E
,
3265 const VarDecl
*VD
, CallStackFrame
*Frame
,
3266 unsigned Version
, APValue
*&Result
) {
3267 APValue::LValueBase
Base(VD
, Frame
? Frame
->Index
: 0, Version
);
3269 // If this is a local variable, dig out its value.
3271 Result
= Frame
->getTemporary(VD
, Version
);
3275 if (!isa
<ParmVarDecl
>(VD
)) {
3276 // Assume variables referenced within a lambda's call operator that were
3277 // not declared within the call operator are captures and during checking
3278 // of a potential constant expression, assume they are unknown constant
3280 assert(isLambdaCallOperator(Frame
->Callee
) &&
3281 (VD
->getDeclContext() != Frame
->Callee
|| VD
->isInitCapture()) &&
3282 "missing value for local variable");
3283 if (Info
.checkingPotentialConstantExpression())
3285 // FIXME: This diagnostic is bogus; we do support captures. Is this code
3286 // still reachable at all?
3287 Info
.FFDiag(E
->getBeginLoc(),
3288 diag::note_unimplemented_constexpr_lambda_feature_ast
)
3289 << "captures not currently allowed";
3294 // If we're currently evaluating the initializer of this declaration, use that
3296 if (Info
.EvaluatingDecl
== Base
) {
3297 Result
= Info
.EvaluatingDeclValue
;
3301 if (isa
<ParmVarDecl
>(VD
)) {
3302 // Assume parameters of a potential constant expression are usable in
3303 // constant expressions.
3304 if (!Info
.checkingPotentialConstantExpression() ||
3305 !Info
.CurrentCall
->Callee
||
3306 !Info
.CurrentCall
->Callee
->Equals(VD
->getDeclContext())) {
3307 if (Info
.getLangOpts().CPlusPlus11
) {
3308 Info
.FFDiag(E
, diag::note_constexpr_function_param_value_unknown
)
3310 NoteLValueLocation(Info
, Base
);
3318 if (E
->isValueDependent())
3321 // Dig out the initializer, and use the declaration which it's attached to.
3322 // FIXME: We should eventually check whether the variable has a reachable
3323 // initializing declaration.
3324 const Expr
*Init
= VD
->getAnyInitializer(VD
);
3326 // Don't diagnose during potential constant expression checking; an
3327 // initializer might be added later.
3328 if (!Info
.checkingPotentialConstantExpression()) {
3329 Info
.FFDiag(E
, diag::note_constexpr_var_init_unknown
, 1)
3331 NoteLValueLocation(Info
, Base
);
3336 if (Init
->isValueDependent()) {
3337 // The DeclRefExpr is not value-dependent, but the variable it refers to
3338 // has a value-dependent initializer. This should only happen in
3339 // constant-folding cases, where the variable is not actually of a suitable
3340 // type for use in a constant expression (otherwise the DeclRefExpr would
3341 // have been value-dependent too), so diagnose that.
3342 assert(!VD
->mightBeUsableInConstantExpressions(Info
.Ctx
));
3343 if (!Info
.checkingPotentialConstantExpression()) {
3344 Info
.FFDiag(E
, Info
.getLangOpts().CPlusPlus11
3345 ? diag::note_constexpr_ltor_non_constexpr
3346 : diag::note_constexpr_ltor_non_integral
, 1)
3347 << VD
<< VD
->getType();
3348 NoteLValueLocation(Info
, Base
);
3353 // Check that we can fold the initializer. In C++, we will have already done
3354 // this in the cases where it matters for conformance.
3355 if (!VD
->evaluateValue()) {
3356 Info
.FFDiag(E
, diag::note_constexpr_var_init_non_constant
, 1) << VD
;
3357 NoteLValueLocation(Info
, Base
);
3361 // Check that the variable is actually usable in constant expressions. For a
3362 // const integral variable or a reference, we might have a non-constant
3363 // initializer that we can nonetheless evaluate the initializer for. Such
3364 // variables are not usable in constant expressions. In C++98, the
3365 // initializer also syntactically needs to be an ICE.
3367 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3368 // expressions here; doing so would regress diagnostics for things like
3369 // reading from a volatile constexpr variable.
3370 if ((Info
.getLangOpts().CPlusPlus
&& !VD
->hasConstantInitialization() &&
3371 VD
->mightBeUsableInConstantExpressions(Info
.Ctx
)) ||
3372 ((Info
.getLangOpts().CPlusPlus
|| Info
.getLangOpts().OpenCL
) &&
3373 !Info
.getLangOpts().CPlusPlus11
&& !VD
->hasICEInitializer(Info
.Ctx
))) {
3374 Info
.CCEDiag(E
, diag::note_constexpr_var_init_non_constant
, 1) << VD
;
3375 NoteLValueLocation(Info
, Base
);
3378 // Never use the initializer of a weak variable, not even for constant
3379 // folding. We can't be sure that this is the definition that will be used.
3381 Info
.FFDiag(E
, diag::note_constexpr_var_init_weak
) << VD
;
3382 NoteLValueLocation(Info
, Base
);
3386 Result
= VD
->getEvaluatedValue();
3390 /// Get the base index of the given base class within an APValue representing
3391 /// the given derived class.
3392 static unsigned getBaseIndex(const CXXRecordDecl
*Derived
,
3393 const CXXRecordDecl
*Base
) {
3394 Base
= Base
->getCanonicalDecl();
3396 for (CXXRecordDecl::base_class_const_iterator I
= Derived
->bases_begin(),
3397 E
= Derived
->bases_end(); I
!= E
; ++I
, ++Index
) {
3398 if (I
->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base
)
3402 llvm_unreachable("base class missing from derived class's bases list");
3405 /// Extract the value of a character from a string literal.
3406 static APSInt
extractStringLiteralCharacter(EvalInfo
&Info
, const Expr
*Lit
,
3408 assert(!isa
<SourceLocExpr
>(Lit
) &&
3409 "SourceLocExpr should have already been converted to a StringLiteral");
3411 // FIXME: Support MakeStringConstant
3412 if (const auto *ObjCEnc
= dyn_cast
<ObjCEncodeExpr
>(Lit
)) {
3414 Info
.Ctx
.getObjCEncodingForType(ObjCEnc
->getEncodedType(), Str
);
3415 assert(Index
<= Str
.size() && "Index too large");
3416 return APSInt::getUnsigned(Str
.c_str()[Index
]);
3419 if (auto PE
= dyn_cast
<PredefinedExpr
>(Lit
))
3420 Lit
= PE
->getFunctionName();
3421 const StringLiteral
*S
= cast
<StringLiteral
>(Lit
);
3422 const ConstantArrayType
*CAT
=
3423 Info
.Ctx
.getAsConstantArrayType(S
->getType());
3424 assert(CAT
&& "string literal isn't an array");
3425 QualType CharType
= CAT
->getElementType();
3426 assert(CharType
->isIntegerType() && "unexpected character type");
3427 APSInt
Value(Info
.Ctx
.getTypeSize(CharType
),
3428 CharType
->isUnsignedIntegerType());
3429 if (Index
< S
->getLength())
3430 Value
= S
->getCodeUnit(Index
);
3434 // Expand a string literal into an array of characters.
3436 // FIXME: This is inefficient; we should probably introduce something similar
3437 // to the LLVM ConstantDataArray to make this cheaper.
3438 static void expandStringLiteral(EvalInfo
&Info
, const StringLiteral
*S
,
3440 QualType AllocType
= QualType()) {
3441 const ConstantArrayType
*CAT
= Info
.Ctx
.getAsConstantArrayType(
3442 AllocType
.isNull() ? S
->getType() : AllocType
);
3443 assert(CAT
&& "string literal isn't an array");
3444 QualType CharType
= CAT
->getElementType();
3445 assert(CharType
->isIntegerType() && "unexpected character type");
3447 unsigned Elts
= CAT
->getSize().getZExtValue();
3448 Result
= APValue(APValue::UninitArray(),
3449 std::min(S
->getLength(), Elts
), Elts
);
3450 APSInt
Value(Info
.Ctx
.getTypeSize(CharType
),
3451 CharType
->isUnsignedIntegerType());
3452 if (Result
.hasArrayFiller())
3453 Result
.getArrayFiller() = APValue(Value
);
3454 for (unsigned I
= 0, N
= Result
.getArrayInitializedElts(); I
!= N
; ++I
) {
3455 Value
= S
->getCodeUnit(I
);
3456 Result
.getArrayInitializedElt(I
) = APValue(Value
);
3460 // Expand an array so that it has more than Index filled elements.
3461 static void expandArray(APValue
&Array
, unsigned Index
) {
3462 unsigned Size
= Array
.getArraySize();
3463 assert(Index
< Size
);
3465 // Always at least double the number of elements for which we store a value.
3466 unsigned OldElts
= Array
.getArrayInitializedElts();
3467 unsigned NewElts
= std::max(Index
+1, OldElts
* 2);
3468 NewElts
= std::min(Size
, std::max(NewElts
, 8u));
3470 // Copy the data across.
3471 APValue
NewValue(APValue::UninitArray(), NewElts
, Size
);
3472 for (unsigned I
= 0; I
!= OldElts
; ++I
)
3473 NewValue
.getArrayInitializedElt(I
).swap(Array
.getArrayInitializedElt(I
));
3474 for (unsigned I
= OldElts
; I
!= NewElts
; ++I
)
3475 NewValue
.getArrayInitializedElt(I
) = Array
.getArrayFiller();
3476 if (NewValue
.hasArrayFiller())
3477 NewValue
.getArrayFiller() = Array
.getArrayFiller();
3478 Array
.swap(NewValue
);
3481 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3482 /// conversion. If it's of class type, we may assume that the copy operation
3483 /// is trivial. Note that this is never true for a union type with fields
3484 /// (because the copy always "reads" the active member) and always true for
3485 /// a non-class type.
3486 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl
*RD
);
3487 static bool isReadByLvalueToRvalueConversion(QualType T
) {
3488 CXXRecordDecl
*RD
= T
->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3489 return !RD
|| isReadByLvalueToRvalueConversion(RD
);
3491 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl
*RD
) {
3492 // FIXME: A trivial copy of a union copies the object representation, even if
3493 // the union is empty.
3495 return !RD
->field_empty();
3499 for (auto *Field
: RD
->fields())
3500 if (!Field
->isUnnamedBitfield() &&
3501 isReadByLvalueToRvalueConversion(Field
->getType()))
3504 for (auto &BaseSpec
: RD
->bases())
3505 if (isReadByLvalueToRvalueConversion(BaseSpec
.getType()))
3511 /// Diagnose an attempt to read from any unreadable field within the specified
3512 /// type, which might be a class type.
3513 static bool diagnoseMutableFields(EvalInfo
&Info
, const Expr
*E
, AccessKinds AK
,
3515 CXXRecordDecl
*RD
= T
->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3519 if (!RD
->hasMutableFields())
3522 for (auto *Field
: RD
->fields()) {
3523 // If we're actually going to read this field in some way, then it can't
3524 // be mutable. If we're in a union, then assigning to a mutable field
3525 // (even an empty one) can change the active member, so that's not OK.
3526 // FIXME: Add core issue number for the union case.
3527 if (Field
->isMutable() &&
3528 (RD
->isUnion() || isReadByLvalueToRvalueConversion(Field
->getType()))) {
3529 Info
.FFDiag(E
, diag::note_constexpr_access_mutable
, 1) << AK
<< Field
;
3530 Info
.Note(Field
->getLocation(), diag::note_declared_at
);
3534 if (diagnoseMutableFields(Info
, E
, AK
, Field
->getType()))
3538 for (auto &BaseSpec
: RD
->bases())
3539 if (diagnoseMutableFields(Info
, E
, AK
, BaseSpec
.getType()))
3542 // All mutable fields were empty, and thus not actually read.
3546 static bool lifetimeStartedInEvaluation(EvalInfo
&Info
,
3547 APValue::LValueBase Base
,
3548 bool MutableSubobject
= false) {
3549 // A temporary or transient heap allocation we created.
3550 if (Base
.getCallIndex() || Base
.is
<DynamicAllocLValue
>())
3553 switch (Info
.IsEvaluatingDecl
) {
3554 case EvalInfo::EvaluatingDeclKind::None
:
3557 case EvalInfo::EvaluatingDeclKind::Ctor
:
3558 // The variable whose initializer we're evaluating.
3559 if (Info
.EvaluatingDecl
== Base
)
3562 // A temporary lifetime-extended by the variable whose initializer we're
3564 if (auto *BaseE
= Base
.dyn_cast
<const Expr
*>())
3565 if (auto *BaseMTE
= dyn_cast
<MaterializeTemporaryExpr
>(BaseE
))
3566 return Info
.EvaluatingDecl
== BaseMTE
->getExtendingDecl();
3569 case EvalInfo::EvaluatingDeclKind::Dtor
:
3570 // C++2a [expr.const]p6:
3571 // [during constant destruction] the lifetime of a and its non-mutable
3572 // subobjects (but not its mutable subobjects) [are] considered to start
3574 if (MutableSubobject
|| Base
!= Info
.EvaluatingDecl
)
3576 // FIXME: We can meaningfully extend this to cover non-const objects, but
3577 // we will need special handling: we should be able to access only
3578 // subobjects of such objects that are themselves declared const.
3579 QualType T
= getType(Base
);
3580 return T
.isConstQualified() || T
->isReferenceType();
3583 llvm_unreachable("unknown evaluating decl kind");
3586 static bool CheckArraySize(EvalInfo
&Info
, const ConstantArrayType
*CAT
,
3587 SourceLocation CallLoc
= {}) {
3588 return Info
.CheckArraySize(
3589 CAT
->getSizeExpr() ? CAT
->getSizeExpr()->getBeginLoc() : CallLoc
,
3590 CAT
->getNumAddressingBits(Info
.Ctx
), CAT
->getSize().getZExtValue(),
3595 /// A handle to a complete object (an object that is not a subobject of
3596 /// another object).
3597 struct CompleteObject
{
3598 /// The identity of the object.
3599 APValue::LValueBase Base
;
3600 /// The value of the complete object.
3602 /// The type of the complete object.
3605 CompleteObject() : Value(nullptr) {}
3606 CompleteObject(APValue::LValueBase Base
, APValue
*Value
, QualType Type
)
3607 : Base(Base
), Value(Value
), Type(Type
) {}
3609 bool mayAccessMutableMembers(EvalInfo
&Info
, AccessKinds AK
) const {
3610 // If this isn't a "real" access (eg, if it's just accessing the type
3611 // info), allow it. We assume the type doesn't change dynamically for
3612 // subobjects of constexpr objects (even though we'd hit UB here if it
3613 // did). FIXME: Is this right?
3614 if (!isAnyAccess(AK
))
3617 // In C++14 onwards, it is permitted to read a mutable member whose
3618 // lifetime began within the evaluation.
3619 // FIXME: Should we also allow this in C++11?
3620 if (!Info
.getLangOpts().CPlusPlus14
)
3622 return lifetimeStartedInEvaluation(Info
, Base
, /*MutableSubobject*/true);
3625 explicit operator bool() const { return !Type
.isNull(); }
3627 } // end anonymous namespace
3629 static QualType
getSubobjectType(QualType ObjType
, QualType SubobjType
,
3630 bool IsMutable
= false) {
3631 // C++ [basic.type.qualifier]p1:
3632 // - A const object is an object of type const T or a non-mutable subobject
3633 // of a const object.
3634 if (ObjType
.isConstQualified() && !IsMutable
)
3635 SubobjType
.addConst();
3636 // - A volatile object is an object of type const T or a subobject of a
3638 if (ObjType
.isVolatileQualified())
3639 SubobjType
.addVolatile();
3643 /// Find the designated sub-object of an rvalue.
3644 template<typename SubobjectHandler
>
3645 typename
SubobjectHandler::result_type
3646 findSubobject(EvalInfo
&Info
, const Expr
*E
, const CompleteObject
&Obj
,
3647 const SubobjectDesignator
&Sub
, SubobjectHandler
&handler
) {
3649 // A diagnostic will have already been produced.
3650 return handler
.failed();
3651 if (Sub
.isOnePastTheEnd() || Sub
.isMostDerivedAnUnsizedArray()) {
3652 if (Info
.getLangOpts().CPlusPlus11
)
3653 Info
.FFDiag(E
, Sub
.isOnePastTheEnd()
3654 ? diag::note_constexpr_access_past_end
3655 : diag::note_constexpr_access_unsized_array
)
3656 << handler
.AccessKind
;
3659 return handler
.failed();
3662 APValue
*O
= Obj
.Value
;
3663 QualType ObjType
= Obj
.Type
;
3664 const FieldDecl
*LastField
= nullptr;
3665 const FieldDecl
*VolatileField
= nullptr;
3667 // Walk the designator's path to find the subobject.
3668 for (unsigned I
= 0, N
= Sub
.Entries
.size(); /**/; ++I
) {
3669 // Reading an indeterminate value is undefined, but assigning over one is OK.
3670 if ((O
->isAbsent() && !(handler
.AccessKind
== AK_Construct
&& I
== N
)) ||
3671 (O
->isIndeterminate() &&
3672 !isValidIndeterminateAccess(handler
.AccessKind
))) {
3673 if (!Info
.checkingPotentialConstantExpression())
3674 Info
.FFDiag(E
, diag::note_constexpr_access_uninit
)
3675 << handler
.AccessKind
<< O
->isIndeterminate()
3676 << E
->getSourceRange();
3677 return handler
.failed();
3680 // C++ [class.ctor]p5, C++ [class.dtor]p5:
3681 // const and volatile semantics are not applied on an object under
3682 // {con,de}struction.
3683 if ((ObjType
.isConstQualified() || ObjType
.isVolatileQualified()) &&
3684 ObjType
->isRecordType() &&
3685 Info
.isEvaluatingCtorDtor(
3687 llvm::ArrayRef(Sub
.Entries
.begin(), Sub
.Entries
.begin() + I
)) !=
3688 ConstructionPhase::None
) {
3689 ObjType
= Info
.Ctx
.getCanonicalType(ObjType
);
3690 ObjType
.removeLocalConst();
3691 ObjType
.removeLocalVolatile();
3694 // If this is our last pass, check that the final object type is OK.
3695 if (I
== N
|| (I
== N
- 1 && ObjType
->isAnyComplexType())) {
3696 // Accesses to volatile objects are prohibited.
3697 if (ObjType
.isVolatileQualified() && isFormalAccess(handler
.AccessKind
)) {
3698 if (Info
.getLangOpts().CPlusPlus
) {
3701 const NamedDecl
*Decl
= nullptr;
3702 if (VolatileField
) {
3704 Loc
= VolatileField
->getLocation();
3705 Decl
= VolatileField
;
3706 } else if (auto *VD
= Obj
.Base
.dyn_cast
<const ValueDecl
*>()) {
3708 Loc
= VD
->getLocation();
3712 if (auto *E
= Obj
.Base
.dyn_cast
<const Expr
*>())
3713 Loc
= E
->getExprLoc();
3715 Info
.FFDiag(E
, diag::note_constexpr_access_volatile_obj
, 1)
3716 << handler
.AccessKind
<< DiagKind
<< Decl
;
3717 Info
.Note(Loc
, diag::note_constexpr_volatile_here
) << DiagKind
;
3719 Info
.FFDiag(E
, diag::note_invalid_subexpr_in_const_expr
);
3721 return handler
.failed();
3724 // If we are reading an object of class type, there may still be more
3725 // things we need to check: if there are any mutable subobjects, we
3726 // cannot perform this read. (This only happens when performing a trivial
3727 // copy or assignment.)
3728 if (ObjType
->isRecordType() &&
3729 !Obj
.mayAccessMutableMembers(Info
, handler
.AccessKind
) &&
3730 diagnoseMutableFields(Info
, E
, handler
.AccessKind
, ObjType
))
3731 return handler
.failed();
3735 if (!handler
.found(*O
, ObjType
))
3738 // If we modified a bit-field, truncate it to the right width.
3739 if (isModification(handler
.AccessKind
) &&
3740 LastField
&& LastField
->isBitField() &&
3741 !truncateBitfieldValue(Info
, E
, *O
, LastField
))
3747 LastField
= nullptr;
3748 if (ObjType
->isArrayType()) {
3749 // Next subobject is an array element.
3750 const ConstantArrayType
*CAT
= Info
.Ctx
.getAsConstantArrayType(ObjType
);
3751 assert(CAT
&& "vla in literal type?");
3752 uint64_t Index
= Sub
.Entries
[I
].getAsArrayIndex();
3753 if (CAT
->getSize().ule(Index
)) {
3754 // Note, it should not be possible to form a pointer with a valid
3755 // designator which points more than one past the end of the array.
3756 if (Info
.getLangOpts().CPlusPlus11
)
3757 Info
.FFDiag(E
, diag::note_constexpr_access_past_end
)
3758 << handler
.AccessKind
;
3761 return handler
.failed();
3764 ObjType
= CAT
->getElementType();
3766 if (O
->getArrayInitializedElts() > Index
)
3767 O
= &O
->getArrayInitializedElt(Index
);
3768 else if (!isRead(handler
.AccessKind
)) {
3769 if (!CheckArraySize(Info
, CAT
, E
->getExprLoc()))
3770 return handler
.failed();
3772 expandArray(*O
, Index
);
3773 O
= &O
->getArrayInitializedElt(Index
);
3775 O
= &O
->getArrayFiller();
3776 } else if (ObjType
->isAnyComplexType()) {
3777 // Next subobject is a complex number.
3778 uint64_t Index
= Sub
.Entries
[I
].getAsArrayIndex();
3780 if (Info
.getLangOpts().CPlusPlus11
)
3781 Info
.FFDiag(E
, diag::note_constexpr_access_past_end
)
3782 << handler
.AccessKind
;
3785 return handler
.failed();
3788 ObjType
= getSubobjectType(
3789 ObjType
, ObjType
->castAs
<ComplexType
>()->getElementType());
3791 assert(I
== N
- 1 && "extracting subobject of scalar?");
3792 if (O
->isComplexInt()) {
3793 return handler
.found(Index
? O
->getComplexIntImag()
3794 : O
->getComplexIntReal(), ObjType
);
3796 assert(O
->isComplexFloat());
3797 return handler
.found(Index
? O
->getComplexFloatImag()
3798 : O
->getComplexFloatReal(), ObjType
);
3800 } else if (const FieldDecl
*Field
= getAsField(Sub
.Entries
[I
])) {
3801 if (Field
->isMutable() &&
3802 !Obj
.mayAccessMutableMembers(Info
, handler
.AccessKind
)) {
3803 Info
.FFDiag(E
, diag::note_constexpr_access_mutable
, 1)
3804 << handler
.AccessKind
<< Field
;
3805 Info
.Note(Field
->getLocation(), diag::note_declared_at
);
3806 return handler
.failed();
3809 // Next subobject is a class, struct or union field.
3810 RecordDecl
*RD
= ObjType
->castAs
<RecordType
>()->getDecl();
3811 if (RD
->isUnion()) {
3812 const FieldDecl
*UnionField
= O
->getUnionField();
3814 UnionField
->getCanonicalDecl() != Field
->getCanonicalDecl()) {
3815 if (I
== N
- 1 && handler
.AccessKind
== AK_Construct
) {
3816 // Placement new onto an inactive union member makes it active.
3817 O
->setUnion(Field
, APValue());
3819 // FIXME: If O->getUnionValue() is absent, report that there's no
3820 // active union member rather than reporting the prior active union
3821 // member. We'll need to fix nullptr_t to not use APValue() as its
3822 // representation first.
3823 Info
.FFDiag(E
, diag::note_constexpr_access_inactive_union_member
)
3824 << handler
.AccessKind
<< Field
<< !UnionField
<< UnionField
;
3825 return handler
.failed();
3828 O
= &O
->getUnionValue();
3830 O
= &O
->getStructField(Field
->getFieldIndex());
3832 ObjType
= getSubobjectType(ObjType
, Field
->getType(), Field
->isMutable());
3834 if (Field
->getType().isVolatileQualified())
3835 VolatileField
= Field
;
3837 // Next subobject is a base class.
3838 const CXXRecordDecl
*Derived
= ObjType
->getAsCXXRecordDecl();
3839 const CXXRecordDecl
*Base
= getAsBaseClass(Sub
.Entries
[I
]);
3840 O
= &O
->getStructBase(getBaseIndex(Derived
, Base
));
3842 ObjType
= getSubobjectType(ObjType
, Info
.Ctx
.getRecordType(Base
));
3848 struct ExtractSubobjectHandler
{
3852 const AccessKinds AccessKind
;
3854 typedef bool result_type
;
3855 bool failed() { return false; }
3856 bool found(APValue
&Subobj
, QualType SubobjType
) {
3858 if (AccessKind
== AK_ReadObjectRepresentation
)
3860 return CheckFullyInitialized(Info
, E
->getExprLoc(), SubobjType
, Result
);
3862 bool found(APSInt
&Value
, QualType SubobjType
) {
3863 Result
= APValue(Value
);
3866 bool found(APFloat
&Value
, QualType SubobjType
) {
3867 Result
= APValue(Value
);
3871 } // end anonymous namespace
3873 /// Extract the designated sub-object of an rvalue.
3874 static bool extractSubobject(EvalInfo
&Info
, const Expr
*E
,
3875 const CompleteObject
&Obj
,
3876 const SubobjectDesignator
&Sub
, APValue
&Result
,
3877 AccessKinds AK
= AK_Read
) {
3878 assert(AK
== AK_Read
|| AK
== AK_ReadObjectRepresentation
);
3879 ExtractSubobjectHandler Handler
= {Info
, E
, Result
, AK
};
3880 return findSubobject(Info
, E
, Obj
, Sub
, Handler
);
3884 struct ModifySubobjectHandler
{
3889 typedef bool result_type
;
3890 static const AccessKinds AccessKind
= AK_Assign
;
3892 bool checkConst(QualType QT
) {
3893 // Assigning to a const object has undefined behavior.
3894 if (QT
.isConstQualified()) {
3895 Info
.FFDiag(E
, diag::note_constexpr_modify_const_type
) << QT
;
3901 bool failed() { return false; }
3902 bool found(APValue
&Subobj
, QualType SubobjType
) {
3903 if (!checkConst(SubobjType
))
3905 // We've been given ownership of NewVal, so just swap it in.
3906 Subobj
.swap(NewVal
);
3909 bool found(APSInt
&Value
, QualType SubobjType
) {
3910 if (!checkConst(SubobjType
))
3912 if (!NewVal
.isInt()) {
3913 // Maybe trying to write a cast pointer value into a complex?
3917 Value
= NewVal
.getInt();
3920 bool found(APFloat
&Value
, QualType SubobjType
) {
3921 if (!checkConst(SubobjType
))
3923 Value
= NewVal
.getFloat();
3927 } // end anonymous namespace
3929 const AccessKinds
ModifySubobjectHandler::AccessKind
;
3931 /// Update the designated sub-object of an rvalue to the given value.
3932 static bool modifySubobject(EvalInfo
&Info
, const Expr
*E
,
3933 const CompleteObject
&Obj
,
3934 const SubobjectDesignator
&Sub
,
3936 ModifySubobjectHandler Handler
= { Info
, NewVal
, E
};
3937 return findSubobject(Info
, E
, Obj
, Sub
, Handler
);
3940 /// Find the position where two subobject designators diverge, or equivalently
3941 /// the length of the common initial subsequence.
3942 static unsigned FindDesignatorMismatch(QualType ObjType
,
3943 const SubobjectDesignator
&A
,
3944 const SubobjectDesignator
&B
,
3945 bool &WasArrayIndex
) {
3946 unsigned I
= 0, N
= std::min(A
.Entries
.size(), B
.Entries
.size());
3947 for (/**/; I
!= N
; ++I
) {
3948 if (!ObjType
.isNull() &&
3949 (ObjType
->isArrayType() || ObjType
->isAnyComplexType())) {
3950 // Next subobject is an array element.
3951 if (A
.Entries
[I
].getAsArrayIndex() != B
.Entries
[I
].getAsArrayIndex()) {
3952 WasArrayIndex
= true;
3955 if (ObjType
->isAnyComplexType())
3956 ObjType
= ObjType
->castAs
<ComplexType
>()->getElementType();
3958 ObjType
= ObjType
->castAsArrayTypeUnsafe()->getElementType();
3960 if (A
.Entries
[I
].getAsBaseOrMember() !=
3961 B
.Entries
[I
].getAsBaseOrMember()) {
3962 WasArrayIndex
= false;
3965 if (const FieldDecl
*FD
= getAsField(A
.Entries
[I
]))
3966 // Next subobject is a field.
3967 ObjType
= FD
->getType();
3969 // Next subobject is a base class.
3970 ObjType
= QualType();
3973 WasArrayIndex
= false;
3977 /// Determine whether the given subobject designators refer to elements of the
3978 /// same array object.
3979 static bool AreElementsOfSameArray(QualType ObjType
,
3980 const SubobjectDesignator
&A
,
3981 const SubobjectDesignator
&B
) {
3982 if (A
.Entries
.size() != B
.Entries
.size())
3985 bool IsArray
= A
.MostDerivedIsArrayElement
;
3986 if (IsArray
&& A
.MostDerivedPathLength
!= A
.Entries
.size())
3987 // A is a subobject of the array element.
3990 // If A (and B) designates an array element, the last entry will be the array
3991 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3992 // of length 1' case, and the entire path must match.
3994 unsigned CommonLength
= FindDesignatorMismatch(ObjType
, A
, B
, WasArrayIndex
);
3995 return CommonLength
>= A
.Entries
.size() - IsArray
;
3998 /// Find the complete object to which an LValue refers.
3999 static CompleteObject
findCompleteObject(EvalInfo
&Info
, const Expr
*E
,
4000 AccessKinds AK
, const LValue
&LVal
,
4001 QualType LValType
) {
4002 if (LVal
.InvalidBase
) {
4004 return CompleteObject();
4008 Info
.FFDiag(E
, diag::note_constexpr_access_null
) << AK
;
4009 return CompleteObject();
4012 CallStackFrame
*Frame
= nullptr;
4014 if (LVal
.getLValueCallIndex()) {
4015 std::tie(Frame
, Depth
) =
4016 Info
.getCallFrameAndDepth(LVal
.getLValueCallIndex());
4018 Info
.FFDiag(E
, diag::note_constexpr_lifetime_ended
, 1)
4019 << AK
<< LVal
.Base
.is
<const ValueDecl
*>();
4020 NoteLValueLocation(Info
, LVal
.Base
);
4021 return CompleteObject();
4025 bool IsAccess
= isAnyAccess(AK
);
4027 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4028 // is not a constant expression (even if the object is non-volatile). We also
4029 // apply this rule to C++98, in order to conform to the expected 'volatile'
4031 if (isFormalAccess(AK
) && LValType
.isVolatileQualified()) {
4032 if (Info
.getLangOpts().CPlusPlus
)
4033 Info
.FFDiag(E
, diag::note_constexpr_access_volatile_type
)
4037 return CompleteObject();
4040 // Compute value storage location and type of base object.
4041 APValue
*BaseVal
= nullptr;
4042 QualType BaseType
= getType(LVal
.Base
);
4044 if (Info
.getLangOpts().CPlusPlus14
&& LVal
.Base
== Info
.EvaluatingDecl
&&
4045 lifetimeStartedInEvaluation(Info
, LVal
.Base
)) {
4046 // This is the object whose initializer we're evaluating, so its lifetime
4047 // started in the current evaluation.
4048 BaseVal
= Info
.EvaluatingDeclValue
;
4049 } else if (const ValueDecl
*D
= LVal
.Base
.dyn_cast
<const ValueDecl
*>()) {
4050 // Allow reading from a GUID declaration.
4051 if (auto *GD
= dyn_cast
<MSGuidDecl
>(D
)) {
4052 if (isModification(AK
)) {
4053 // All the remaining cases do not permit modification of the object.
4054 Info
.FFDiag(E
, diag::note_constexpr_modify_global
);
4055 return CompleteObject();
4057 APValue
&V
= GD
->getAsAPValue();
4059 Info
.FFDiag(E
, diag::note_constexpr_unsupported_layout
)
4061 return CompleteObject();
4063 return CompleteObject(LVal
.Base
, &V
, GD
->getType());
4066 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4067 if (auto *GCD
= dyn_cast
<UnnamedGlobalConstantDecl
>(D
)) {
4068 if (isModification(AK
)) {
4069 Info
.FFDiag(E
, diag::note_constexpr_modify_global
);
4070 return CompleteObject();
4072 return CompleteObject(LVal
.Base
, const_cast<APValue
*>(&GCD
->getValue()),
4076 // Allow reading from template parameter objects.
4077 if (auto *TPO
= dyn_cast
<TemplateParamObjectDecl
>(D
)) {
4078 if (isModification(AK
)) {
4079 Info
.FFDiag(E
, diag::note_constexpr_modify_global
);
4080 return CompleteObject();
4082 return CompleteObject(LVal
.Base
, const_cast<APValue
*>(&TPO
->getValue()),
4086 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4087 // In C++11, constexpr, non-volatile variables initialized with constant
4088 // expressions are constant expressions too. Inside constexpr functions,
4089 // parameters are constant expressions even if they're non-const.
4090 // In C++1y, objects local to a constant expression (those with a Frame) are
4091 // both readable and writable inside constant expressions.
4092 // In C, such things can also be folded, although they are not ICEs.
4093 const VarDecl
*VD
= dyn_cast
<VarDecl
>(D
);
4095 if (const VarDecl
*VDef
= VD
->getDefinition(Info
.Ctx
))
4098 if (!VD
|| VD
->isInvalidDecl()) {
4100 return CompleteObject();
4103 bool IsConstant
= BaseType
.isConstant(Info
.Ctx
);
4105 // Unless we're looking at a local variable or argument in a constexpr call,
4106 // the variable we're reading must be const.
4108 if (IsAccess
&& isa
<ParmVarDecl
>(VD
)) {
4109 // Access of a parameter that's not associated with a frame isn't going
4110 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4111 // suitable diagnostic.
4112 } else if (Info
.getLangOpts().CPlusPlus14
&&
4113 lifetimeStartedInEvaluation(Info
, LVal
.Base
)) {
4114 // OK, we can read and modify an object if we're in the process of
4115 // evaluating its initializer, because its lifetime began in this
4117 } else if (isModification(AK
)) {
4118 // All the remaining cases do not permit modification of the object.
4119 Info
.FFDiag(E
, diag::note_constexpr_modify_global
);
4120 return CompleteObject();
4121 } else if (VD
->isConstexpr()) {
4122 // OK, we can read this variable.
4123 } else if (BaseType
->isIntegralOrEnumerationType()) {
4126 return CompleteObject(LVal
.getLValueBase(), nullptr, BaseType
);
4127 if (Info
.getLangOpts().CPlusPlus
) {
4128 Info
.FFDiag(E
, diag::note_constexpr_ltor_non_const_int
, 1) << VD
;
4129 Info
.Note(VD
->getLocation(), diag::note_declared_at
);
4133 return CompleteObject();
4135 } else if (!IsAccess
) {
4136 return CompleteObject(LVal
.getLValueBase(), nullptr, BaseType
);
4137 } else if (IsConstant
&& Info
.checkingPotentialConstantExpression() &&
4138 BaseType
->isLiteralType(Info
.Ctx
) && !VD
->hasDefinition()) {
4139 // This variable might end up being constexpr. Don't diagnose it yet.
4140 } else if (IsConstant
) {
4141 // Keep evaluating to see what we can do. In particular, we support
4142 // folding of const floating-point types, in order to make static const
4143 // data members of such types (supported as an extension) more useful.
4144 if (Info
.getLangOpts().CPlusPlus
) {
4145 Info
.CCEDiag(E
, Info
.getLangOpts().CPlusPlus11
4146 ? diag::note_constexpr_ltor_non_constexpr
4147 : diag::note_constexpr_ltor_non_integral
, 1)
4149 Info
.Note(VD
->getLocation(), diag::note_declared_at
);
4154 // Never allow reading a non-const value.
4155 if (Info
.getLangOpts().CPlusPlus
) {
4156 Info
.FFDiag(E
, Info
.getLangOpts().CPlusPlus11
4157 ? diag::note_constexpr_ltor_non_constexpr
4158 : diag::note_constexpr_ltor_non_integral
, 1)
4160 Info
.Note(VD
->getLocation(), diag::note_declared_at
);
4164 return CompleteObject();
4168 if (!evaluateVarDeclInit(Info
, E
, VD
, Frame
, LVal
.getLValueVersion(), BaseVal
))
4169 return CompleteObject();
4170 } else if (DynamicAllocLValue DA
= LVal
.Base
.dyn_cast
<DynamicAllocLValue
>()) {
4171 std::optional
<DynAlloc
*> Alloc
= Info
.lookupDynamicAlloc(DA
);
4173 Info
.FFDiag(E
, diag::note_constexpr_access_deleted_object
) << AK
;
4174 return CompleteObject();
4176 return CompleteObject(LVal
.Base
, &(*Alloc
)->Value
,
4177 LVal
.Base
.getDynamicAllocType());
4179 const Expr
*Base
= LVal
.Base
.dyn_cast
<const Expr
*>();
4182 if (const MaterializeTemporaryExpr
*MTE
=
4183 dyn_cast_or_null
<MaterializeTemporaryExpr
>(Base
)) {
4184 assert(MTE
->getStorageDuration() == SD_Static
&&
4185 "should have a frame for a non-global materialized temporary");
4187 // C++20 [expr.const]p4: [DR2126]
4188 // An object or reference is usable in constant expressions if it is
4189 // - a temporary object of non-volatile const-qualified literal type
4190 // whose lifetime is extended to that of a variable that is usable
4191 // in constant expressions
4193 // C++20 [expr.const]p5:
4194 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4195 // - a non-volatile glvalue that refers to an object that is usable
4196 // in constant expressions, or
4197 // - a non-volatile glvalue of literal type that refers to a
4198 // non-volatile object whose lifetime began within the evaluation
4201 // C++11 misses the 'began within the evaluation of e' check and
4202 // instead allows all temporaries, including things like:
4205 // constexpr int k = r;
4206 // Therefore we use the C++14-onwards rules in C++11 too.
4208 // Note that temporaries whose lifetimes began while evaluating a
4209 // variable's constructor are not usable while evaluating the
4210 // corresponding destructor, not even if they're of const-qualified
4212 if (!MTE
->isUsableInConstantExpressions(Info
.Ctx
) &&
4213 !lifetimeStartedInEvaluation(Info
, LVal
.Base
)) {
4215 return CompleteObject(LVal
.getLValueBase(), nullptr, BaseType
);
4216 Info
.FFDiag(E
, diag::note_constexpr_access_static_temporary
, 1) << AK
;
4217 Info
.Note(MTE
->getExprLoc(), diag::note_constexpr_temporary_here
);
4218 return CompleteObject();
4221 BaseVal
= MTE
->getOrCreateValue(false);
4222 assert(BaseVal
&& "got reference to unevaluated temporary");
4225 return CompleteObject(LVal
.getLValueBase(), nullptr, BaseType
);
4228 Info
.FFDiag(E
, diag::note_constexpr_access_unreadable_object
)
4230 << Val
.getAsString(Info
.Ctx
,
4231 Info
.Ctx
.getLValueReferenceType(LValType
));
4232 NoteLValueLocation(Info
, LVal
.Base
);
4233 return CompleteObject();
4236 BaseVal
= Frame
->getTemporary(Base
, LVal
.Base
.getVersion());
4237 assert(BaseVal
&& "missing value for temporary");
4241 // In C++14, we can't safely access any mutable state when we might be
4242 // evaluating after an unmodeled side effect. Parameters are modeled as state
4243 // in the caller, but aren't visible once the call returns, so they can be
4244 // modified in a speculatively-evaluated call.
4246 // FIXME: Not all local state is mutable. Allow local constant subobjects
4247 // to be read here (but take care with 'mutable' fields).
4248 unsigned VisibleDepth
= Depth
;
4249 if (llvm::isa_and_nonnull
<ParmVarDecl
>(
4250 LVal
.Base
.dyn_cast
<const ValueDecl
*>()))
4252 if ((Frame
&& Info
.getLangOpts().CPlusPlus14
&&
4253 Info
.EvalStatus
.HasSideEffects
) ||
4254 (isModification(AK
) && VisibleDepth
< Info
.SpeculativeEvaluationDepth
))
4255 return CompleteObject();
4257 return CompleteObject(LVal
.getLValueBase(), BaseVal
, BaseType
);
4260 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4261 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4262 /// glvalue referred to by an entity of reference type.
4264 /// \param Info - Information about the ongoing evaluation.
4265 /// \param Conv - The expression for which we are performing the conversion.
4266 /// Used for diagnostics.
4267 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4268 /// case of a non-class type).
4269 /// \param LVal - The glvalue on which we are attempting to perform this action.
4270 /// \param RVal - The produced value will be placed here.
4271 /// \param WantObjectRepresentation - If true, we're looking for the object
4272 /// representation rather than the value, and in particular,
4273 /// there is no requirement that the result be fully initialized.
4275 handleLValueToRValueConversion(EvalInfo
&Info
, const Expr
*Conv
, QualType Type
,
4276 const LValue
&LVal
, APValue
&RVal
,
4277 bool WantObjectRepresentation
= false) {
4278 if (LVal
.Designator
.Invalid
)
4281 // Check for special cases where there is no existing APValue to look at.
4282 const Expr
*Base
= LVal
.Base
.dyn_cast
<const Expr
*>();
4285 WantObjectRepresentation
? AK_ReadObjectRepresentation
: AK_Read
;
4287 if (Base
&& !LVal
.getLValueCallIndex() && !Type
.isVolatileQualified()) {
4288 if (const CompoundLiteralExpr
*CLE
= dyn_cast
<CompoundLiteralExpr
>(Base
)) {
4289 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4290 // initializer until now for such expressions. Such an expression can't be
4291 // an ICE in C, so this only matters for fold.
4292 if (Type
.isVolatileQualified()) {
4298 if (!Evaluate(Lit
, Info
, CLE
->getInitializer()))
4301 // According to GCC info page:
4303 // 6.28 Compound Literals
4305 // As an optimization, G++ sometimes gives array compound literals longer
4306 // lifetimes: when the array either appears outside a function or has a
4307 // const-qualified type. If foo and its initializer had elements of type
4308 // char *const rather than char *, or if foo were a global variable, the
4309 // array would have static storage duration. But it is probably safest
4310 // just to avoid the use of array compound literals in C++ code.
4312 // Obey that rule by checking constness for converted array types.
4314 QualType CLETy
= CLE
->getType();
4315 if (CLETy
->isArrayType() && !Type
->isArrayType()) {
4316 if (!CLETy
.isConstant(Info
.Ctx
)) {
4318 Info
.Note(CLE
->getExprLoc(), diag::note_declared_at
);
4323 CompleteObject
LitObj(LVal
.Base
, &Lit
, Base
->getType());
4324 return extractSubobject(Info
, Conv
, LitObj
, LVal
.Designator
, RVal
, AK
);
4325 } else if (isa
<StringLiteral
>(Base
) || isa
<PredefinedExpr
>(Base
)) {
4326 // Special-case character extraction so we don't have to construct an
4327 // APValue for the whole string.
4328 assert(LVal
.Designator
.Entries
.size() <= 1 &&
4329 "Can only read characters from string literals");
4330 if (LVal
.Designator
.Entries
.empty()) {
4331 // Fail for now for LValue to RValue conversion of an array.
4332 // (This shouldn't show up in C/C++, but it could be triggered by a
4333 // weird EvaluateAsRValue call from a tool.)
4337 if (LVal
.Designator
.isOnePastTheEnd()) {
4338 if (Info
.getLangOpts().CPlusPlus11
)
4339 Info
.FFDiag(Conv
, diag::note_constexpr_access_past_end
) << AK
;
4344 uint64_t CharIndex
= LVal
.Designator
.Entries
[0].getAsArrayIndex();
4345 RVal
= APValue(extractStringLiteralCharacter(Info
, Base
, CharIndex
));
4350 CompleteObject Obj
= findCompleteObject(Info
, Conv
, AK
, LVal
, Type
);
4351 return Obj
&& extractSubobject(Info
, Conv
, Obj
, LVal
.Designator
, RVal
, AK
);
4354 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4355 static bool handleAssignment(EvalInfo
&Info
, const Expr
*E
, const LValue
&LVal
,
4356 QualType LValType
, APValue
&Val
) {
4357 if (LVal
.Designator
.Invalid
)
4360 if (!Info
.getLangOpts().CPlusPlus14
) {
4365 CompleteObject Obj
= findCompleteObject(Info
, E
, AK_Assign
, LVal
, LValType
);
4366 return Obj
&& modifySubobject(Info
, E
, Obj
, LVal
.Designator
, Val
);
4370 struct CompoundAssignSubobjectHandler
{
4372 const CompoundAssignOperator
*E
;
4373 QualType PromotedLHSType
;
4374 BinaryOperatorKind Opcode
;
4377 static const AccessKinds AccessKind
= AK_Assign
;
4379 typedef bool result_type
;
4381 bool checkConst(QualType QT
) {
4382 // Assigning to a const object has undefined behavior.
4383 if (QT
.isConstQualified()) {
4384 Info
.FFDiag(E
, diag::note_constexpr_modify_const_type
) << QT
;
4390 bool failed() { return false; }
4391 bool found(APValue
&Subobj
, QualType SubobjType
) {
4392 switch (Subobj
.getKind()) {
4394 return found(Subobj
.getInt(), SubobjType
);
4395 case APValue::Float
:
4396 return found(Subobj
.getFloat(), SubobjType
);
4397 case APValue::ComplexInt
:
4398 case APValue::ComplexFloat
:
4399 // FIXME: Implement complex compound assignment.
4402 case APValue::LValue
:
4403 return foundPointer(Subobj
, SubobjType
);
4404 case APValue::Vector
:
4405 return foundVector(Subobj
, SubobjType
);
4406 case APValue::Indeterminate
:
4407 Info
.FFDiag(E
, diag::note_constexpr_access_uninit
)
4408 << /*read of=*/0 << /*uninitialized object=*/1
4409 << E
->getLHS()->getSourceRange();
4412 // FIXME: can this happen?
4418 bool foundVector(APValue
&Value
, QualType SubobjType
) {
4419 if (!checkConst(SubobjType
))
4422 if (!SubobjType
->isVectorType()) {
4426 return handleVectorVectorBinOp(Info
, E
, Opcode
, Value
, RHS
);
4429 bool found(APSInt
&Value
, QualType SubobjType
) {
4430 if (!checkConst(SubobjType
))
4433 if (!SubobjType
->isIntegerType()) {
4434 // We don't support compound assignment on integer-cast-to-pointer
4442 HandleIntToIntCast(Info
, E
, PromotedLHSType
, SubobjType
, Value
);
4443 if (!handleIntIntBinOp(Info
, E
, LHS
, Opcode
, RHS
.getInt(), LHS
))
4445 Value
= HandleIntToIntCast(Info
, E
, SubobjType
, PromotedLHSType
, LHS
);
4447 } else if (RHS
.isFloat()) {
4448 const FPOptions FPO
= E
->getFPFeaturesInEffect(
4449 Info
.Ctx
.getLangOpts());
4450 APFloat
FValue(0.0);
4451 return HandleIntToFloatCast(Info
, E
, FPO
, SubobjType
, Value
,
4452 PromotedLHSType
, FValue
) &&
4453 handleFloatFloatBinOp(Info
, E
, FValue
, Opcode
, RHS
.getFloat()) &&
4454 HandleFloatToIntCast(Info
, E
, PromotedLHSType
, FValue
, SubobjType
,
4461 bool found(APFloat
&Value
, QualType SubobjType
) {
4462 return checkConst(SubobjType
) &&
4463 HandleFloatToFloatCast(Info
, E
, SubobjType
, PromotedLHSType
,
4465 handleFloatFloatBinOp(Info
, E
, Value
, Opcode
, RHS
.getFloat()) &&
4466 HandleFloatToFloatCast(Info
, E
, PromotedLHSType
, SubobjType
, Value
);
4468 bool foundPointer(APValue
&Subobj
, QualType SubobjType
) {
4469 if (!checkConst(SubobjType
))
4472 QualType PointeeType
;
4473 if (const PointerType
*PT
= SubobjType
->getAs
<PointerType
>())
4474 PointeeType
= PT
->getPointeeType();
4476 if (PointeeType
.isNull() || !RHS
.isInt() ||
4477 (Opcode
!= BO_Add
&& Opcode
!= BO_Sub
)) {
4482 APSInt Offset
= RHS
.getInt();
4483 if (Opcode
== BO_Sub
)
4484 negateAsSigned(Offset
);
4487 LVal
.setFrom(Info
.Ctx
, Subobj
);
4488 if (!HandleLValueArrayAdjustment(Info
, E
, LVal
, PointeeType
, Offset
))
4490 LVal
.moveInto(Subobj
);
4494 } // end anonymous namespace
4496 const AccessKinds
CompoundAssignSubobjectHandler::AccessKind
;
4498 /// Perform a compound assignment of LVal <op>= RVal.
4499 static bool handleCompoundAssignment(EvalInfo
&Info
,
4500 const CompoundAssignOperator
*E
,
4501 const LValue
&LVal
, QualType LValType
,
4502 QualType PromotedLValType
,
4503 BinaryOperatorKind Opcode
,
4504 const APValue
&RVal
) {
4505 if (LVal
.Designator
.Invalid
)
4508 if (!Info
.getLangOpts().CPlusPlus14
) {
4513 CompleteObject Obj
= findCompleteObject(Info
, E
, AK_Assign
, LVal
, LValType
);
4514 CompoundAssignSubobjectHandler Handler
= { Info
, E
, PromotedLValType
, Opcode
,
4516 return Obj
&& findSubobject(Info
, E
, Obj
, LVal
.Designator
, Handler
);
4520 struct IncDecSubobjectHandler
{
4522 const UnaryOperator
*E
;
4523 AccessKinds AccessKind
;
4526 typedef bool result_type
;
4528 bool checkConst(QualType QT
) {
4529 // Assigning to a const object has undefined behavior.
4530 if (QT
.isConstQualified()) {
4531 Info
.FFDiag(E
, diag::note_constexpr_modify_const_type
) << QT
;
4537 bool failed() { return false; }
4538 bool found(APValue
&Subobj
, QualType SubobjType
) {
4539 // Stash the old value. Also clear Old, so we don't clobber it later
4540 // if we're post-incrementing a complex.
4546 switch (Subobj
.getKind()) {
4548 return found(Subobj
.getInt(), SubobjType
);
4549 case APValue::Float
:
4550 return found(Subobj
.getFloat(), SubobjType
);
4551 case APValue::ComplexInt
:
4552 return found(Subobj
.getComplexIntReal(),
4553 SubobjType
->castAs
<ComplexType
>()->getElementType()
4554 .withCVRQualifiers(SubobjType
.getCVRQualifiers()));
4555 case APValue::ComplexFloat
:
4556 return found(Subobj
.getComplexFloatReal(),
4557 SubobjType
->castAs
<ComplexType
>()->getElementType()
4558 .withCVRQualifiers(SubobjType
.getCVRQualifiers()));
4559 case APValue::LValue
:
4560 return foundPointer(Subobj
, SubobjType
);
4562 // FIXME: can this happen?
4567 bool found(APSInt
&Value
, QualType SubobjType
) {
4568 if (!checkConst(SubobjType
))
4571 if (!SubobjType
->isIntegerType()) {
4572 // We don't support increment / decrement on integer-cast-to-pointer
4578 if (Old
) *Old
= APValue(Value
);
4580 // bool arithmetic promotes to int, and the conversion back to bool
4581 // doesn't reduce mod 2^n, so special-case it.
4582 if (SubobjType
->isBooleanType()) {
4583 if (AccessKind
== AK_Increment
)
4590 bool WasNegative
= Value
.isNegative();
4591 if (AccessKind
== AK_Increment
) {
4594 if (!WasNegative
&& Value
.isNegative() && E
->canOverflow()) {
4595 APSInt
ActualValue(Value
, /*IsUnsigned*/true);
4596 return HandleOverflow(Info
, E
, ActualValue
, SubobjType
);
4601 if (WasNegative
&& !Value
.isNegative() && E
->canOverflow()) {
4602 unsigned BitWidth
= Value
.getBitWidth();
4603 APSInt
ActualValue(Value
.sext(BitWidth
+ 1), /*IsUnsigned*/false);
4604 ActualValue
.setBit(BitWidth
);
4605 return HandleOverflow(Info
, E
, ActualValue
, SubobjType
);
4610 bool found(APFloat
&Value
, QualType SubobjType
) {
4611 if (!checkConst(SubobjType
))
4614 if (Old
) *Old
= APValue(Value
);
4616 APFloat
One(Value
.getSemantics(), 1);
4617 if (AccessKind
== AK_Increment
)
4618 Value
.add(One
, APFloat::rmNearestTiesToEven
);
4620 Value
.subtract(One
, APFloat::rmNearestTiesToEven
);
4623 bool foundPointer(APValue
&Subobj
, QualType SubobjType
) {
4624 if (!checkConst(SubobjType
))
4627 QualType PointeeType
;
4628 if (const PointerType
*PT
= SubobjType
->getAs
<PointerType
>())
4629 PointeeType
= PT
->getPointeeType();
4636 LVal
.setFrom(Info
.Ctx
, Subobj
);
4637 if (!HandleLValueArrayAdjustment(Info
, E
, LVal
, PointeeType
,
4638 AccessKind
== AK_Increment
? 1 : -1))
4640 LVal
.moveInto(Subobj
);
4644 } // end anonymous namespace
4646 /// Perform an increment or decrement on LVal.
4647 static bool handleIncDec(EvalInfo
&Info
, const Expr
*E
, const LValue
&LVal
,
4648 QualType LValType
, bool IsIncrement
, APValue
*Old
) {
4649 if (LVal
.Designator
.Invalid
)
4652 if (!Info
.getLangOpts().CPlusPlus14
) {
4657 AccessKinds AK
= IsIncrement
? AK_Increment
: AK_Decrement
;
4658 CompleteObject Obj
= findCompleteObject(Info
, E
, AK
, LVal
, LValType
);
4659 IncDecSubobjectHandler Handler
= {Info
, cast
<UnaryOperator
>(E
), AK
, Old
};
4660 return Obj
&& findSubobject(Info
, E
, Obj
, LVal
.Designator
, Handler
);
4663 /// Build an lvalue for the object argument of a member function call.
4664 static bool EvaluateObjectArgument(EvalInfo
&Info
, const Expr
*Object
,
4666 if (Object
->getType()->isPointerType() && Object
->isPRValue())
4667 return EvaluatePointer(Object
, This
, Info
);
4669 if (Object
->isGLValue())
4670 return EvaluateLValue(Object
, This
, Info
);
4672 if (Object
->getType()->isLiteralType(Info
.Ctx
))
4673 return EvaluateTemporary(Object
, This
, Info
);
4675 if (Object
->getType()->isRecordType() && Object
->isPRValue())
4676 return EvaluateTemporary(Object
, This
, Info
);
4678 Info
.FFDiag(Object
, diag::note_constexpr_nonliteral
) << Object
->getType();
4682 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4683 /// lvalue referring to the result.
4685 /// \param Info - Information about the ongoing evaluation.
4686 /// \param LV - An lvalue referring to the base of the member pointer.
4687 /// \param RHS - The member pointer expression.
4688 /// \param IncludeMember - Specifies whether the member itself is included in
4689 /// the resulting LValue subobject designator. This is not possible when
4690 /// creating a bound member function.
4691 /// \return The field or method declaration to which the member pointer refers,
4692 /// or 0 if evaluation fails.
4693 static const ValueDecl
*HandleMemberPointerAccess(EvalInfo
&Info
,
4697 bool IncludeMember
= true) {
4699 if (!EvaluateMemberPointer(RHS
, MemPtr
, Info
))
4702 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4703 // member value, the behavior is undefined.
4704 if (!MemPtr
.getDecl()) {
4705 // FIXME: Specific diagnostic.
4710 if (MemPtr
.isDerivedMember()) {
4711 // This is a member of some derived class. Truncate LV appropriately.
4712 // The end of the derived-to-base path for the base object must match the
4713 // derived-to-base path for the member pointer.
4714 if (LV
.Designator
.MostDerivedPathLength
+ MemPtr
.Path
.size() >
4715 LV
.Designator
.Entries
.size()) {
4719 unsigned PathLengthToMember
=
4720 LV
.Designator
.Entries
.size() - MemPtr
.Path
.size();
4721 for (unsigned I
= 0, N
= MemPtr
.Path
.size(); I
!= N
; ++I
) {
4722 const CXXRecordDecl
*LVDecl
= getAsBaseClass(
4723 LV
.Designator
.Entries
[PathLengthToMember
+ I
]);
4724 const CXXRecordDecl
*MPDecl
= MemPtr
.Path
[I
];
4725 if (LVDecl
->getCanonicalDecl() != MPDecl
->getCanonicalDecl()) {
4731 // Truncate the lvalue to the appropriate derived class.
4732 if (!CastToDerivedClass(Info
, RHS
, LV
, MemPtr
.getContainingRecord(),
4733 PathLengthToMember
))
4735 } else if (!MemPtr
.Path
.empty()) {
4736 // Extend the LValue path with the member pointer's path.
4737 LV
.Designator
.Entries
.reserve(LV
.Designator
.Entries
.size() +
4738 MemPtr
.Path
.size() + IncludeMember
);
4740 // Walk down to the appropriate base class.
4741 if (const PointerType
*PT
= LVType
->getAs
<PointerType
>())
4742 LVType
= PT
->getPointeeType();
4743 const CXXRecordDecl
*RD
= LVType
->getAsCXXRecordDecl();
4744 assert(RD
&& "member pointer access on non-class-type expression");
4745 // The first class in the path is that of the lvalue.
4746 for (unsigned I
= 1, N
= MemPtr
.Path
.size(); I
!= N
; ++I
) {
4747 const CXXRecordDecl
*Base
= MemPtr
.Path
[N
- I
- 1];
4748 if (!HandleLValueDirectBase(Info
, RHS
, LV
, RD
, Base
))
4752 // Finally cast to the class containing the member.
4753 if (!HandleLValueDirectBase(Info
, RHS
, LV
, RD
,
4754 MemPtr
.getContainingRecord()))
4758 // Add the member. Note that we cannot build bound member functions here.
4759 if (IncludeMember
) {
4760 if (const FieldDecl
*FD
= dyn_cast
<FieldDecl
>(MemPtr
.getDecl())) {
4761 if (!HandleLValueMember(Info
, RHS
, LV
, FD
))
4763 } else if (const IndirectFieldDecl
*IFD
=
4764 dyn_cast
<IndirectFieldDecl
>(MemPtr
.getDecl())) {
4765 if (!HandleLValueIndirectMember(Info
, RHS
, LV
, IFD
))
4768 llvm_unreachable("can't construct reference to bound member function");
4772 return MemPtr
.getDecl();
4775 static const ValueDecl
*HandleMemberPointerAccess(EvalInfo
&Info
,
4776 const BinaryOperator
*BO
,
4778 bool IncludeMember
= true) {
4779 assert(BO
->getOpcode() == BO_PtrMemD
|| BO
->getOpcode() == BO_PtrMemI
);
4781 if (!EvaluateObjectArgument(Info
, BO
->getLHS(), LV
)) {
4782 if (Info
.noteFailure()) {
4784 EvaluateMemberPointer(BO
->getRHS(), MemPtr
, Info
);
4789 return HandleMemberPointerAccess(Info
, BO
->getLHS()->getType(), LV
,
4790 BO
->getRHS(), IncludeMember
);
4793 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4794 /// the provided lvalue, which currently refers to the base object.
4795 static bool HandleBaseToDerivedCast(EvalInfo
&Info
, const CastExpr
*E
,
4797 SubobjectDesignator
&D
= Result
.Designator
;
4798 if (D
.Invalid
|| !Result
.checkNullPointer(Info
, E
, CSK_Derived
))
4801 QualType TargetQT
= E
->getType();
4802 if (const PointerType
*PT
= TargetQT
->getAs
<PointerType
>())
4803 TargetQT
= PT
->getPointeeType();
4805 // Check this cast lands within the final derived-to-base subobject path.
4806 if (D
.MostDerivedPathLength
+ E
->path_size() > D
.Entries
.size()) {
4807 Info
.CCEDiag(E
, diag::note_constexpr_invalid_downcast
)
4808 << D
.MostDerivedType
<< TargetQT
;
4812 // Check the type of the final cast. We don't need to check the path,
4813 // since a cast can only be formed if the path is unique.
4814 unsigned NewEntriesSize
= D
.Entries
.size() - E
->path_size();
4815 const CXXRecordDecl
*TargetType
= TargetQT
->getAsCXXRecordDecl();
4816 const CXXRecordDecl
*FinalType
;
4817 if (NewEntriesSize
== D
.MostDerivedPathLength
)
4818 FinalType
= D
.MostDerivedType
->getAsCXXRecordDecl();
4820 FinalType
= getAsBaseClass(D
.Entries
[NewEntriesSize
- 1]);
4821 if (FinalType
->getCanonicalDecl() != TargetType
->getCanonicalDecl()) {
4822 Info
.CCEDiag(E
, diag::note_constexpr_invalid_downcast
)
4823 << D
.MostDerivedType
<< TargetQT
;
4827 // Truncate the lvalue to the appropriate derived class.
4828 return CastToDerivedClass(Info
, E
, Result
, TargetType
, NewEntriesSize
);
4831 /// Get the value to use for a default-initialized object of type T.
4832 /// Return false if it encounters something invalid.
4833 static bool handleDefaultInitValue(QualType T
, APValue
&Result
) {
4834 bool Success
= true;
4836 // If there is already a value present don't overwrite it.
4837 if (!Result
.isAbsent())
4840 if (auto *RD
= T
->getAsCXXRecordDecl()) {
4841 if (RD
->isInvalidDecl()) {
4845 if (RD
->isUnion()) {
4846 Result
= APValue((const FieldDecl
*)nullptr);
4849 Result
= APValue(APValue::UninitStruct(), RD
->getNumBases(),
4850 std::distance(RD
->field_begin(), RD
->field_end()));
4853 for (CXXRecordDecl::base_class_const_iterator I
= RD
->bases_begin(),
4854 End
= RD
->bases_end();
4855 I
!= End
; ++I
, ++Index
)
4857 handleDefaultInitValue(I
->getType(), Result
.getStructBase(Index
));
4859 for (const auto *I
: RD
->fields()) {
4860 if (I
->isUnnamedBitfield())
4862 Success
&= handleDefaultInitValue(
4863 I
->getType(), Result
.getStructField(I
->getFieldIndex()));
4869 dyn_cast_or_null
<ConstantArrayType
>(T
->getAsArrayTypeUnsafe())) {
4870 Result
= APValue(APValue::UninitArray(), 0, AT
->getSize().getZExtValue());
4871 if (Result
.hasArrayFiller())
4873 handleDefaultInitValue(AT
->getElementType(), Result
.getArrayFiller());
4878 Result
= APValue::IndeterminateValue();
4883 enum EvalStmtResult
{
4884 /// Evaluation failed.
4886 /// Hit a 'return' statement.
4888 /// Evaluation succeeded.
4890 /// Hit a 'continue' statement.
4892 /// Hit a 'break' statement.
4894 /// Still scanning for 'case' or 'default' statement.
4899 static bool EvaluateVarDecl(EvalInfo
&Info
, const VarDecl
*VD
) {
4900 if (VD
->isInvalidDecl())
4902 // We don't need to evaluate the initializer for a static local.
4903 if (!VD
->hasLocalStorage())
4907 APValue
&Val
= Info
.CurrentCall
->createTemporary(VD
, VD
->getType(),
4908 ScopeKind::Block
, Result
);
4910 const Expr
*InitE
= VD
->getInit();
4912 if (VD
->getType()->isDependentType())
4913 return Info
.noteSideEffect();
4914 return handleDefaultInitValue(VD
->getType(), Val
);
4916 if (InitE
->isValueDependent())
4919 if (!EvaluateInPlace(Val
, Info
, Result
, InitE
)) {
4920 // Wipe out any partially-computed value, to allow tracking that this
4921 // evaluation failed.
4929 static bool EvaluateDecl(EvalInfo
&Info
, const Decl
*D
) {
4932 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(D
))
4933 OK
&= EvaluateVarDecl(Info
, VD
);
4935 if (const DecompositionDecl
*DD
= dyn_cast
<DecompositionDecl
>(D
))
4936 for (auto *BD
: DD
->bindings())
4937 if (auto *VD
= BD
->getHoldingVar())
4938 OK
&= EvaluateDecl(Info
, VD
);
4943 static bool EvaluateDependentExpr(const Expr
*E
, EvalInfo
&Info
) {
4944 assert(E
->isValueDependent());
4945 if (Info
.noteSideEffect())
4947 assert(E
->containsErrors() && "valid value-dependent expression should never "
4948 "reach invalid code path.");
4952 /// Evaluate a condition (either a variable declaration or an expression).
4953 static bool EvaluateCond(EvalInfo
&Info
, const VarDecl
*CondDecl
,
4954 const Expr
*Cond
, bool &Result
) {
4955 if (Cond
->isValueDependent())
4957 FullExpressionRAII
Scope(Info
);
4958 if (CondDecl
&& !EvaluateDecl(Info
, CondDecl
))
4960 if (!EvaluateAsBooleanCondition(Cond
, Result
, Info
))
4962 return Scope
.destroy();
4966 /// A location where the result (returned value) of evaluating a
4967 /// statement should be stored.
4969 /// The APValue that should be filled in with the returned value.
4971 /// The location containing the result, if any (used to support RVO).
4975 struct TempVersionRAII
{
4976 CallStackFrame
&Frame
;
4978 TempVersionRAII(CallStackFrame
&Frame
) : Frame(Frame
) {
4979 Frame
.pushTempVersion();
4982 ~TempVersionRAII() {
4983 Frame
.popTempVersion();
4989 static EvalStmtResult
EvaluateStmt(StmtResult
&Result
, EvalInfo
&Info
,
4991 const SwitchCase
*SC
= nullptr);
4993 /// Evaluate the body of a loop, and translate the result as appropriate.
4994 static EvalStmtResult
EvaluateLoopBody(StmtResult
&Result
, EvalInfo
&Info
,
4996 const SwitchCase
*Case
= nullptr) {
4997 BlockScopeRAII
Scope(Info
);
4999 EvalStmtResult ESR
= EvaluateStmt(Result
, Info
, Body
, Case
);
5000 if (ESR
!= ESR_Failed
&& ESR
!= ESR_CaseNotFound
&& !Scope
.destroy())
5005 return ESR_Succeeded
;
5008 return ESR_Continue
;
5011 case ESR_CaseNotFound
:
5014 llvm_unreachable("Invalid EvalStmtResult!");
5017 /// Evaluate a switch statement.
5018 static EvalStmtResult
EvaluateSwitch(StmtResult
&Result
, EvalInfo
&Info
,
5019 const SwitchStmt
*SS
) {
5020 BlockScopeRAII
Scope(Info
);
5022 // Evaluate the switch condition.
5025 if (const Stmt
*Init
= SS
->getInit()) {
5026 EvalStmtResult ESR
= EvaluateStmt(Result
, Info
, Init
);
5027 if (ESR
!= ESR_Succeeded
) {
5028 if (ESR
!= ESR_Failed
&& !Scope
.destroy())
5034 FullExpressionRAII
CondScope(Info
);
5035 if (SS
->getConditionVariable() &&
5036 !EvaluateDecl(Info
, SS
->getConditionVariable()))
5038 if (SS
->getCond()->isValueDependent()) {
5039 // We don't know what the value is, and which branch should jump to.
5040 EvaluateDependentExpr(SS
->getCond(), Info
);
5043 if (!EvaluateInteger(SS
->getCond(), Value
, Info
))
5046 if (!CondScope
.destroy())
5050 // Find the switch case corresponding to the value of the condition.
5051 // FIXME: Cache this lookup.
5052 const SwitchCase
*Found
= nullptr;
5053 for (const SwitchCase
*SC
= SS
->getSwitchCaseList(); SC
;
5054 SC
= SC
->getNextSwitchCase()) {
5055 if (isa
<DefaultStmt
>(SC
)) {
5060 const CaseStmt
*CS
= cast
<CaseStmt
>(SC
);
5061 APSInt LHS
= CS
->getLHS()->EvaluateKnownConstInt(Info
.Ctx
);
5062 APSInt RHS
= CS
->getRHS() ? CS
->getRHS()->EvaluateKnownConstInt(Info
.Ctx
)
5064 if (LHS
<= Value
&& Value
<= RHS
) {
5071 return Scope
.destroy() ? ESR_Succeeded
: ESR_Failed
;
5073 // Search the switch body for the switch case and evaluate it from there.
5074 EvalStmtResult ESR
= EvaluateStmt(Result
, Info
, SS
->getBody(), Found
);
5075 if (ESR
!= ESR_Failed
&& ESR
!= ESR_CaseNotFound
&& !Scope
.destroy())
5080 return ESR_Succeeded
;
5086 case ESR_CaseNotFound
:
5087 // This can only happen if the switch case is nested within a statement
5088 // expression. We have no intention of supporting that.
5089 Info
.FFDiag(Found
->getBeginLoc(),
5090 diag::note_constexpr_stmt_expr_unsupported
);
5093 llvm_unreachable("Invalid EvalStmtResult!");
5096 static bool CheckLocalVariableDeclaration(EvalInfo
&Info
, const VarDecl
*VD
) {
5097 // An expression E is a core constant expression unless the evaluation of E
5098 // would evaluate one of the following: [C++23] - a control flow that passes
5099 // through a declaration of a variable with static or thread storage duration
5100 // unless that variable is usable in constant expressions.
5101 if (VD
->isLocalVarDecl() && VD
->isStaticLocal() &&
5102 !VD
->isUsableInConstantExpressions(Info
.Ctx
)) {
5103 Info
.CCEDiag(VD
->getLocation(), diag::note_constexpr_static_local
)
5104 << (VD
->getTSCSpec() == TSCS_unspecified
? 0 : 1) << VD
;
5110 // Evaluate a statement.
5111 static EvalStmtResult
EvaluateStmt(StmtResult
&Result
, EvalInfo
&Info
,
5112 const Stmt
*S
, const SwitchCase
*Case
) {
5113 if (!Info
.nextStep(S
))
5116 // If we're hunting down a 'case' or 'default' label, recurse through
5117 // substatements until we hit the label.
5119 switch (S
->getStmtClass()) {
5120 case Stmt::CompoundStmtClass
:
5121 // FIXME: Precompute which substatement of a compound statement we
5122 // would jump to, and go straight there rather than performing a
5123 // linear scan each time.
5124 case Stmt::LabelStmtClass
:
5125 case Stmt::AttributedStmtClass
:
5126 case Stmt::DoStmtClass
:
5129 case Stmt::CaseStmtClass
:
5130 case Stmt::DefaultStmtClass
:
5135 case Stmt::IfStmtClass
: {
5136 // FIXME: Precompute which side of an 'if' we would jump to, and go
5137 // straight there rather than scanning both sides.
5138 const IfStmt
*IS
= cast
<IfStmt
>(S
);
5140 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5141 // preceded by our switch label.
5142 BlockScopeRAII
Scope(Info
);
5144 // Step into the init statement in case it brings an (uninitialized)
5145 // variable into scope.
5146 if (const Stmt
*Init
= IS
->getInit()) {
5147 EvalStmtResult ESR
= EvaluateStmt(Result
, Info
, Init
, Case
);
5148 if (ESR
!= ESR_CaseNotFound
) {
5149 assert(ESR
!= ESR_Succeeded
);
5154 // Condition variable must be initialized if it exists.
5155 // FIXME: We can skip evaluating the body if there's a condition
5156 // variable, as there can't be any case labels within it.
5157 // (The same is true for 'for' statements.)
5159 EvalStmtResult ESR
= EvaluateStmt(Result
, Info
, IS
->getThen(), Case
);
5160 if (ESR
== ESR_Failed
)
5162 if (ESR
!= ESR_CaseNotFound
)
5163 return Scope
.destroy() ? ESR
: ESR_Failed
;
5165 return ESR_CaseNotFound
;
5167 ESR
= EvaluateStmt(Result
, Info
, IS
->getElse(), Case
);
5168 if (ESR
== ESR_Failed
)
5170 if (ESR
!= ESR_CaseNotFound
)
5171 return Scope
.destroy() ? ESR
: ESR_Failed
;
5172 return ESR_CaseNotFound
;
5175 case Stmt::WhileStmtClass
: {
5176 EvalStmtResult ESR
=
5177 EvaluateLoopBody(Result
, Info
, cast
<WhileStmt
>(S
)->getBody(), Case
);
5178 if (ESR
!= ESR_Continue
)
5183 case Stmt::ForStmtClass
: {
5184 const ForStmt
*FS
= cast
<ForStmt
>(S
);
5185 BlockScopeRAII
Scope(Info
);
5187 // Step into the init statement in case it brings an (uninitialized)
5188 // variable into scope.
5189 if (const Stmt
*Init
= FS
->getInit()) {
5190 EvalStmtResult ESR
= EvaluateStmt(Result
, Info
, Init
, Case
);
5191 if (ESR
!= ESR_CaseNotFound
) {
5192 assert(ESR
!= ESR_Succeeded
);
5197 EvalStmtResult ESR
=
5198 EvaluateLoopBody(Result
, Info
, FS
->getBody(), Case
);
5199 if (ESR
!= ESR_Continue
)
5201 if (const auto *Inc
= FS
->getInc()) {
5202 if (Inc
->isValueDependent()) {
5203 if (!EvaluateDependentExpr(Inc
, Info
))
5206 FullExpressionRAII
IncScope(Info
);
5207 if (!EvaluateIgnoredValue(Info
, Inc
) || !IncScope
.destroy())
5214 case Stmt::DeclStmtClass
: {
5215 // Start the lifetime of any uninitialized variables we encounter. They
5216 // might be used by the selected branch of the switch.
5217 const DeclStmt
*DS
= cast
<DeclStmt
>(S
);
5218 for (const auto *D
: DS
->decls()) {
5219 if (const auto *VD
= dyn_cast
<VarDecl
>(D
)) {
5220 if (!CheckLocalVariableDeclaration(Info
, VD
))
5222 if (VD
->hasLocalStorage() && !VD
->getInit())
5223 if (!EvaluateVarDecl(Info
, VD
))
5225 // FIXME: If the variable has initialization that can't be jumped
5226 // over, bail out of any immediately-surrounding compound-statement
5227 // too. There can't be any case labels here.
5230 return ESR_CaseNotFound
;
5234 return ESR_CaseNotFound
;
5238 switch (S
->getStmtClass()) {
5240 if (const Expr
*E
= dyn_cast
<Expr
>(S
)) {
5241 if (E
->isValueDependent()) {
5242 if (!EvaluateDependentExpr(E
, Info
))
5245 // Don't bother evaluating beyond an expression-statement which couldn't
5247 // FIXME: Do we need the FullExpressionRAII object here?
5248 // VisitExprWithCleanups should create one when necessary.
5249 FullExpressionRAII
Scope(Info
);
5250 if (!EvaluateIgnoredValue(Info
, E
) || !Scope
.destroy())
5253 return ESR_Succeeded
;
5256 Info
.FFDiag(S
->getBeginLoc()) << S
->getSourceRange();
5259 case Stmt::NullStmtClass
:
5260 return ESR_Succeeded
;
5262 case Stmt::DeclStmtClass
: {
5263 const DeclStmt
*DS
= cast
<DeclStmt
>(S
);
5264 for (const auto *D
: DS
->decls()) {
5265 const VarDecl
*VD
= dyn_cast_or_null
<VarDecl
>(D
);
5266 if (VD
&& !CheckLocalVariableDeclaration(Info
, VD
))
5268 // Each declaration initialization is its own full-expression.
5269 FullExpressionRAII
Scope(Info
);
5270 if (!EvaluateDecl(Info
, D
) && !Info
.noteFailure())
5272 if (!Scope
.destroy())
5275 return ESR_Succeeded
;
5278 case Stmt::ReturnStmtClass
: {
5279 const Expr
*RetExpr
= cast
<ReturnStmt
>(S
)->getRetValue();
5280 FullExpressionRAII
Scope(Info
);
5281 if (RetExpr
&& RetExpr
->isValueDependent()) {
5282 EvaluateDependentExpr(RetExpr
, Info
);
5283 // We know we returned, but we don't know what the value is.
5288 ? EvaluateInPlace(Result
.Value
, Info
, *Result
.Slot
, RetExpr
)
5289 : Evaluate(Result
.Value
, Info
, RetExpr
)))
5291 return Scope
.destroy() ? ESR_Returned
: ESR_Failed
;
5294 case Stmt::CompoundStmtClass
: {
5295 BlockScopeRAII
Scope(Info
);
5297 const CompoundStmt
*CS
= cast
<CompoundStmt
>(S
);
5298 for (const auto *BI
: CS
->body()) {
5299 EvalStmtResult ESR
= EvaluateStmt(Result
, Info
, BI
, Case
);
5300 if (ESR
== ESR_Succeeded
)
5302 else if (ESR
!= ESR_CaseNotFound
) {
5303 if (ESR
!= ESR_Failed
&& !Scope
.destroy())
5309 return ESR_CaseNotFound
;
5310 return Scope
.destroy() ? ESR_Succeeded
: ESR_Failed
;
5313 case Stmt::IfStmtClass
: {
5314 const IfStmt
*IS
= cast
<IfStmt
>(S
);
5316 // Evaluate the condition, as either a var decl or as an expression.
5317 BlockScopeRAII
Scope(Info
);
5318 if (const Stmt
*Init
= IS
->getInit()) {
5319 EvalStmtResult ESR
= EvaluateStmt(Result
, Info
, Init
);
5320 if (ESR
!= ESR_Succeeded
) {
5321 if (ESR
!= ESR_Failed
&& !Scope
.destroy())
5327 if (IS
->isConsteval()) {
5328 Cond
= IS
->isNonNegatedConsteval();
5329 // If we are not in a constant context, if consteval should not evaluate
5331 if (!Info
.InConstantContext
)
5333 } else if (!EvaluateCond(Info
, IS
->getConditionVariable(), IS
->getCond(),
5337 if (const Stmt
*SubStmt
= Cond
? IS
->getThen() : IS
->getElse()) {
5338 EvalStmtResult ESR
= EvaluateStmt(Result
, Info
, SubStmt
);
5339 if (ESR
!= ESR_Succeeded
) {
5340 if (ESR
!= ESR_Failed
&& !Scope
.destroy())
5345 return Scope
.destroy() ? ESR_Succeeded
: ESR_Failed
;
5348 case Stmt::WhileStmtClass
: {
5349 const WhileStmt
*WS
= cast
<WhileStmt
>(S
);
5351 BlockScopeRAII
Scope(Info
);
5353 if (!EvaluateCond(Info
, WS
->getConditionVariable(), WS
->getCond(),
5359 EvalStmtResult ESR
= EvaluateLoopBody(Result
, Info
, WS
->getBody());
5360 if (ESR
!= ESR_Continue
) {
5361 if (ESR
!= ESR_Failed
&& !Scope
.destroy())
5365 if (!Scope
.destroy())
5368 return ESR_Succeeded
;
5371 case Stmt::DoStmtClass
: {
5372 const DoStmt
*DS
= cast
<DoStmt
>(S
);
5375 EvalStmtResult ESR
= EvaluateLoopBody(Result
, Info
, DS
->getBody(), Case
);
5376 if (ESR
!= ESR_Continue
)
5380 if (DS
->getCond()->isValueDependent()) {
5381 EvaluateDependentExpr(DS
->getCond(), Info
);
5382 // Bailout as we don't know whether to keep going or terminate the loop.
5385 FullExpressionRAII
CondScope(Info
);
5386 if (!EvaluateAsBooleanCondition(DS
->getCond(), Continue
, Info
) ||
5387 !CondScope
.destroy())
5390 return ESR_Succeeded
;
5393 case Stmt::ForStmtClass
: {
5394 const ForStmt
*FS
= cast
<ForStmt
>(S
);
5395 BlockScopeRAII
ForScope(Info
);
5396 if (FS
->getInit()) {
5397 EvalStmtResult ESR
= EvaluateStmt(Result
, Info
, FS
->getInit());
5398 if (ESR
!= ESR_Succeeded
) {
5399 if (ESR
!= ESR_Failed
&& !ForScope
.destroy())
5405 BlockScopeRAII
IterScope(Info
);
5406 bool Continue
= true;
5407 if (FS
->getCond() && !EvaluateCond(Info
, FS
->getConditionVariable(),
5408 FS
->getCond(), Continue
))
5413 EvalStmtResult ESR
= EvaluateLoopBody(Result
, Info
, FS
->getBody());
5414 if (ESR
!= ESR_Continue
) {
5415 if (ESR
!= ESR_Failed
&& (!IterScope
.destroy() || !ForScope
.destroy()))
5420 if (const auto *Inc
= FS
->getInc()) {
5421 if (Inc
->isValueDependent()) {
5422 if (!EvaluateDependentExpr(Inc
, Info
))
5425 FullExpressionRAII
IncScope(Info
);
5426 if (!EvaluateIgnoredValue(Info
, Inc
) || !IncScope
.destroy())
5431 if (!IterScope
.destroy())
5434 return ForScope
.destroy() ? ESR_Succeeded
: ESR_Failed
;
5437 case Stmt::CXXForRangeStmtClass
: {
5438 const CXXForRangeStmt
*FS
= cast
<CXXForRangeStmt
>(S
);
5439 BlockScopeRAII
Scope(Info
);
5441 // Evaluate the init-statement if present.
5442 if (FS
->getInit()) {
5443 EvalStmtResult ESR
= EvaluateStmt(Result
, Info
, FS
->getInit());
5444 if (ESR
!= ESR_Succeeded
) {
5445 if (ESR
!= ESR_Failed
&& !Scope
.destroy())
5451 // Initialize the __range variable.
5452 EvalStmtResult ESR
= EvaluateStmt(Result
, Info
, FS
->getRangeStmt());
5453 if (ESR
!= ESR_Succeeded
) {
5454 if (ESR
!= ESR_Failed
&& !Scope
.destroy())
5459 // In error-recovery cases it's possible to get here even if we failed to
5460 // synthesize the __begin and __end variables.
5461 if (!FS
->getBeginStmt() || !FS
->getEndStmt() || !FS
->getCond())
5464 // Create the __begin and __end iterators.
5465 ESR
= EvaluateStmt(Result
, Info
, FS
->getBeginStmt());
5466 if (ESR
!= ESR_Succeeded
) {
5467 if (ESR
!= ESR_Failed
&& !Scope
.destroy())
5471 ESR
= EvaluateStmt(Result
, Info
, FS
->getEndStmt());
5472 if (ESR
!= ESR_Succeeded
) {
5473 if (ESR
!= ESR_Failed
&& !Scope
.destroy())
5479 // Condition: __begin != __end.
5481 if (FS
->getCond()->isValueDependent()) {
5482 EvaluateDependentExpr(FS
->getCond(), Info
);
5483 // We don't know whether to keep going or terminate the loop.
5486 bool Continue
= true;
5487 FullExpressionRAII
CondExpr(Info
);
5488 if (!EvaluateAsBooleanCondition(FS
->getCond(), Continue
, Info
))
5494 // User's variable declaration, initialized by *__begin.
5495 BlockScopeRAII
InnerScope(Info
);
5496 ESR
= EvaluateStmt(Result
, Info
, FS
->getLoopVarStmt());
5497 if (ESR
!= ESR_Succeeded
) {
5498 if (ESR
!= ESR_Failed
&& (!InnerScope
.destroy() || !Scope
.destroy()))
5504 ESR
= EvaluateLoopBody(Result
, Info
, FS
->getBody());
5505 if (ESR
!= ESR_Continue
) {
5506 if (ESR
!= ESR_Failed
&& (!InnerScope
.destroy() || !Scope
.destroy()))
5510 if (FS
->getInc()->isValueDependent()) {
5511 if (!EvaluateDependentExpr(FS
->getInc(), Info
))
5514 // Increment: ++__begin
5515 if (!EvaluateIgnoredValue(Info
, FS
->getInc()))
5519 if (!InnerScope
.destroy())
5523 return Scope
.destroy() ? ESR_Succeeded
: ESR_Failed
;
5526 case Stmt::SwitchStmtClass
:
5527 return EvaluateSwitch(Result
, Info
, cast
<SwitchStmt
>(S
));
5529 case Stmt::ContinueStmtClass
:
5530 return ESR_Continue
;
5532 case Stmt::BreakStmtClass
:
5535 case Stmt::LabelStmtClass
:
5536 return EvaluateStmt(Result
, Info
, cast
<LabelStmt
>(S
)->getSubStmt(), Case
);
5538 case Stmt::AttributedStmtClass
:
5539 // As a general principle, C++11 attributes can be ignored without
5540 // any semantic impact.
5541 return EvaluateStmt(Result
, Info
, cast
<AttributedStmt
>(S
)->getSubStmt(),
5544 case Stmt::CaseStmtClass
:
5545 case Stmt::DefaultStmtClass
:
5546 return EvaluateStmt(Result
, Info
, cast
<SwitchCase
>(S
)->getSubStmt(), Case
);
5547 case Stmt::CXXTryStmtClass
:
5548 // Evaluate try blocks by evaluating all sub statements.
5549 return EvaluateStmt(Result
, Info
, cast
<CXXTryStmt
>(S
)->getTryBlock(), Case
);
5553 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5554 /// default constructor. If so, we'll fold it whether or not it's marked as
5555 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5556 /// so we need special handling.
5557 static bool CheckTrivialDefaultConstructor(EvalInfo
&Info
, SourceLocation Loc
,
5558 const CXXConstructorDecl
*CD
,
5559 bool IsValueInitialization
) {
5560 if (!CD
->isTrivial() || !CD
->isDefaultConstructor())
5563 // Value-initialization does not call a trivial default constructor, so such a
5564 // call is a core constant expression whether or not the constructor is
5566 if (!CD
->isConstexpr() && !IsValueInitialization
) {
5567 if (Info
.getLangOpts().CPlusPlus11
) {
5568 // FIXME: If DiagDecl is an implicitly-declared special member function,
5569 // we should be much more explicit about why it's not constexpr.
5570 Info
.CCEDiag(Loc
, diag::note_constexpr_invalid_function
, 1)
5571 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD
;
5572 Info
.Note(CD
->getLocation(), diag::note_declared_at
);
5574 Info
.CCEDiag(Loc
, diag::note_invalid_subexpr_in_const_expr
);
5580 /// CheckConstexprFunction - Check that a function can be called in a constant
5582 static bool CheckConstexprFunction(EvalInfo
&Info
, SourceLocation CallLoc
,
5583 const FunctionDecl
*Declaration
,
5584 const FunctionDecl
*Definition
,
5586 // Potential constant expressions can contain calls to declared, but not yet
5587 // defined, constexpr functions.
5588 if (Info
.checkingPotentialConstantExpression() && !Definition
&&
5589 Declaration
->isConstexpr())
5592 // Bail out if the function declaration itself is invalid. We will
5593 // have produced a relevant diagnostic while parsing it, so just
5594 // note the problematic sub-expression.
5595 if (Declaration
->isInvalidDecl()) {
5596 Info
.FFDiag(CallLoc
, diag::note_invalid_subexpr_in_const_expr
);
5600 // DR1872: An instantiated virtual constexpr function can't be called in a
5601 // constant expression (prior to C++20). We can still constant-fold such a
5603 if (!Info
.Ctx
.getLangOpts().CPlusPlus20
&& isa
<CXXMethodDecl
>(Declaration
) &&
5604 cast
<CXXMethodDecl
>(Declaration
)->isVirtual())
5605 Info
.CCEDiag(CallLoc
, diag::note_constexpr_virtual_call
);
5607 if (Definition
&& Definition
->isInvalidDecl()) {
5608 Info
.FFDiag(CallLoc
, diag::note_invalid_subexpr_in_const_expr
);
5612 // Can we evaluate this function call?
5613 if (Definition
&& Definition
->isConstexpr() && Body
)
5616 if (Info
.getLangOpts().CPlusPlus11
) {
5617 const FunctionDecl
*DiagDecl
= Definition
? Definition
: Declaration
;
5619 // If this function is not constexpr because it is an inherited
5620 // non-constexpr constructor, diagnose that directly.
5621 auto *CD
= dyn_cast
<CXXConstructorDecl
>(DiagDecl
);
5622 if (CD
&& CD
->isInheritingConstructor()) {
5623 auto *Inherited
= CD
->getInheritedConstructor().getConstructor();
5624 if (!Inherited
->isConstexpr())
5625 DiagDecl
= CD
= Inherited
;
5628 // FIXME: If DiagDecl is an implicitly-declared special member function
5629 // or an inheriting constructor, we should be much more explicit about why
5630 // it's not constexpr.
5631 if (CD
&& CD
->isInheritingConstructor())
5632 Info
.FFDiag(CallLoc
, diag::note_constexpr_invalid_inhctor
, 1)
5633 << CD
->getInheritedConstructor().getConstructor()->getParent();
5635 Info
.FFDiag(CallLoc
, diag::note_constexpr_invalid_function
, 1)
5636 << DiagDecl
->isConstexpr() << (bool)CD
<< DiagDecl
;
5637 Info
.Note(DiagDecl
->getLocation(), diag::note_declared_at
);
5639 Info
.FFDiag(CallLoc
, diag::note_invalid_subexpr_in_const_expr
);
5645 struct CheckDynamicTypeHandler
{
5646 AccessKinds AccessKind
;
5647 typedef bool result_type
;
5648 bool failed() { return false; }
5649 bool found(APValue
&Subobj
, QualType SubobjType
) { return true; }
5650 bool found(APSInt
&Value
, QualType SubobjType
) { return true; }
5651 bool found(APFloat
&Value
, QualType SubobjType
) { return true; }
5653 } // end anonymous namespace
5655 /// Check that we can access the notional vptr of an object / determine its
5657 static bool checkDynamicType(EvalInfo
&Info
, const Expr
*E
, const LValue
&This
,
5658 AccessKinds AK
, bool Polymorphic
) {
5659 if (This
.Designator
.Invalid
)
5662 CompleteObject Obj
= findCompleteObject(Info
, E
, AK
, This
, QualType());
5668 // The object is not usable in constant expressions, so we can't inspect
5669 // its value to see if it's in-lifetime or what the active union members
5670 // are. We can still check for a one-past-the-end lvalue.
5671 if (This
.Designator
.isOnePastTheEnd() ||
5672 This
.Designator
.isMostDerivedAnUnsizedArray()) {
5673 Info
.FFDiag(E
, This
.Designator
.isOnePastTheEnd()
5674 ? diag::note_constexpr_access_past_end
5675 : diag::note_constexpr_access_unsized_array
)
5678 } else if (Polymorphic
) {
5679 // Conservatively refuse to perform a polymorphic operation if we would
5680 // not be able to read a notional 'vptr' value.
5683 QualType StarThisType
=
5684 Info
.Ctx
.getLValueReferenceType(This
.Designator
.getType(Info
.Ctx
));
5685 Info
.FFDiag(E
, diag::note_constexpr_polymorphic_unknown_dynamic_type
)
5686 << AK
<< Val
.getAsString(Info
.Ctx
, StarThisType
);
5692 CheckDynamicTypeHandler Handler
{AK
};
5693 return Obj
&& findSubobject(Info
, E
, Obj
, This
.Designator
, Handler
);
5696 /// Check that the pointee of the 'this' pointer in a member function call is
5697 /// either within its lifetime or in its period of construction or destruction.
5699 checkNonVirtualMemberCallThisPointer(EvalInfo
&Info
, const Expr
*E
,
5701 const CXXMethodDecl
*NamedMember
) {
5702 return checkDynamicType(
5704 isa
<CXXDestructorDecl
>(NamedMember
) ? AK_Destroy
: AK_MemberCall
, false);
5707 struct DynamicType
{
5708 /// The dynamic class type of the object.
5709 const CXXRecordDecl
*Type
;
5710 /// The corresponding path length in the lvalue.
5711 unsigned PathLength
;
5714 static const CXXRecordDecl
*getBaseClassType(SubobjectDesignator
&Designator
,
5715 unsigned PathLength
) {
5716 assert(PathLength
>= Designator
.MostDerivedPathLength
&& PathLength
<=
5717 Designator
.Entries
.size() && "invalid path length");
5718 return (PathLength
== Designator
.MostDerivedPathLength
)
5719 ? Designator
.MostDerivedType
->getAsCXXRecordDecl()
5720 : getAsBaseClass(Designator
.Entries
[PathLength
- 1]);
5723 /// Determine the dynamic type of an object.
5724 static std::optional
<DynamicType
> ComputeDynamicType(EvalInfo
&Info
,
5728 // If we don't have an lvalue denoting an object of class type, there is no
5729 // meaningful dynamic type. (We consider objects of non-class type to have no
5731 if (!checkDynamicType(Info
, E
, This
, AK
, true))
5732 return std::nullopt
;
5734 // Refuse to compute a dynamic type in the presence of virtual bases. This
5735 // shouldn't happen other than in constant-folding situations, since literal
5736 // types can't have virtual bases.
5738 // Note that consumers of DynamicType assume that the type has no virtual
5739 // bases, and will need modifications if this restriction is relaxed.
5740 const CXXRecordDecl
*Class
=
5741 This
.Designator
.MostDerivedType
->getAsCXXRecordDecl();
5742 if (!Class
|| Class
->getNumVBases()) {
5744 return std::nullopt
;
5747 // FIXME: For very deep class hierarchies, it might be beneficial to use a
5748 // binary search here instead. But the overwhelmingly common case is that
5749 // we're not in the middle of a constructor, so it probably doesn't matter
5751 ArrayRef
<APValue::LValuePathEntry
> Path
= This
.Designator
.Entries
;
5752 for (unsigned PathLength
= This
.Designator
.MostDerivedPathLength
;
5753 PathLength
<= Path
.size(); ++PathLength
) {
5754 switch (Info
.isEvaluatingCtorDtor(This
.getLValueBase(),
5755 Path
.slice(0, PathLength
))) {
5756 case ConstructionPhase::Bases
:
5757 case ConstructionPhase::DestroyingBases
:
5758 // We're constructing or destroying a base class. This is not the dynamic
5762 case ConstructionPhase::None
:
5763 case ConstructionPhase::AfterBases
:
5764 case ConstructionPhase::AfterFields
:
5765 case ConstructionPhase::Destroying
:
5766 // We've finished constructing the base classes and not yet started
5767 // destroying them again, so this is the dynamic type.
5768 return DynamicType
{getBaseClassType(This
.Designator
, PathLength
),
5773 // CWG issue 1517: we're constructing a base class of the object described by
5774 // 'This', so that object has not yet begun its period of construction and
5775 // any polymorphic operation on it results in undefined behavior.
5777 return std::nullopt
;
5780 /// Perform virtual dispatch.
5781 static const CXXMethodDecl
*HandleVirtualDispatch(
5782 EvalInfo
&Info
, const Expr
*E
, LValue
&This
, const CXXMethodDecl
*Found
,
5783 llvm::SmallVectorImpl
<QualType
> &CovariantAdjustmentPath
) {
5784 std::optional
<DynamicType
> DynType
= ComputeDynamicType(
5786 isa
<CXXDestructorDecl
>(Found
) ? AK_Destroy
: AK_MemberCall
);
5790 // Find the final overrider. It must be declared in one of the classes on the
5791 // path from the dynamic type to the static type.
5792 // FIXME: If we ever allow literal types to have virtual base classes, that
5794 const CXXMethodDecl
*Callee
= Found
;
5795 unsigned PathLength
= DynType
->PathLength
;
5796 for (/**/; PathLength
<= This
.Designator
.Entries
.size(); ++PathLength
) {
5797 const CXXRecordDecl
*Class
= getBaseClassType(This
.Designator
, PathLength
);
5798 const CXXMethodDecl
*Overrider
=
5799 Found
->getCorrespondingMethodDeclaredInClass(Class
, false);
5806 // C++2a [class.abstract]p6:
5807 // the effect of making a virtual call to a pure virtual function [...] is
5809 if (Callee
->isPure()) {
5810 Info
.FFDiag(E
, diag::note_constexpr_pure_virtual_call
, 1) << Callee
;
5811 Info
.Note(Callee
->getLocation(), diag::note_declared_at
);
5815 // If necessary, walk the rest of the path to determine the sequence of
5816 // covariant adjustment steps to apply.
5817 if (!Info
.Ctx
.hasSameUnqualifiedType(Callee
->getReturnType(),
5818 Found
->getReturnType())) {
5819 CovariantAdjustmentPath
.push_back(Callee
->getReturnType());
5820 for (unsigned CovariantPathLength
= PathLength
+ 1;
5821 CovariantPathLength
!= This
.Designator
.Entries
.size();
5822 ++CovariantPathLength
) {
5823 const CXXRecordDecl
*NextClass
=
5824 getBaseClassType(This
.Designator
, CovariantPathLength
);
5825 const CXXMethodDecl
*Next
=
5826 Found
->getCorrespondingMethodDeclaredInClass(NextClass
, false);
5827 if (Next
&& !Info
.Ctx
.hasSameUnqualifiedType(
5828 Next
->getReturnType(), CovariantAdjustmentPath
.back()))
5829 CovariantAdjustmentPath
.push_back(Next
->getReturnType());
5831 if (!Info
.Ctx
.hasSameUnqualifiedType(Found
->getReturnType(),
5832 CovariantAdjustmentPath
.back()))
5833 CovariantAdjustmentPath
.push_back(Found
->getReturnType());
5836 // Perform 'this' adjustment.
5837 if (!CastToDerivedClass(Info
, E
, This
, Callee
->getParent(), PathLength
))
5843 /// Perform the adjustment from a value returned by a virtual function to
5844 /// a value of the statically expected type, which may be a pointer or
5845 /// reference to a base class of the returned type.
5846 static bool HandleCovariantReturnAdjustment(EvalInfo
&Info
, const Expr
*E
,
5848 ArrayRef
<QualType
> Path
) {
5849 assert(Result
.isLValue() &&
5850 "unexpected kind of APValue for covariant return");
5851 if (Result
.isNullPointer())
5855 LVal
.setFrom(Info
.Ctx
, Result
);
5857 const CXXRecordDecl
*OldClass
= Path
[0]->getPointeeCXXRecordDecl();
5858 for (unsigned I
= 1; I
!= Path
.size(); ++I
) {
5859 const CXXRecordDecl
*NewClass
= Path
[I
]->getPointeeCXXRecordDecl();
5860 assert(OldClass
&& NewClass
&& "unexpected kind of covariant return");
5861 if (OldClass
!= NewClass
&&
5862 !CastToBaseClass(Info
, E
, LVal
, OldClass
, NewClass
))
5864 OldClass
= NewClass
;
5867 LVal
.moveInto(Result
);
5871 /// Determine whether \p Base, which is known to be a direct base class of
5872 /// \p Derived, is a public base class.
5873 static bool isBaseClassPublic(const CXXRecordDecl
*Derived
,
5874 const CXXRecordDecl
*Base
) {
5875 for (const CXXBaseSpecifier
&BaseSpec
: Derived
->bases()) {
5876 auto *BaseClass
= BaseSpec
.getType()->getAsCXXRecordDecl();
5877 if (BaseClass
&& declaresSameEntity(BaseClass
, Base
))
5878 return BaseSpec
.getAccessSpecifier() == AS_public
;
5880 llvm_unreachable("Base is not a direct base of Derived");
5883 /// Apply the given dynamic cast operation on the provided lvalue.
5885 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5886 /// to find a suitable target subobject.
5887 static bool HandleDynamicCast(EvalInfo
&Info
, const ExplicitCastExpr
*E
,
5889 // We can't do anything with a non-symbolic pointer value.
5890 SubobjectDesignator
&D
= Ptr
.Designator
;
5894 // C++ [expr.dynamic.cast]p6:
5895 // If v is a null pointer value, the result is a null pointer value.
5896 if (Ptr
.isNullPointer() && !E
->isGLValue())
5899 // For all the other cases, we need the pointer to point to an object within
5900 // its lifetime / period of construction / destruction, and we need to know
5901 // its dynamic type.
5902 std::optional
<DynamicType
> DynType
=
5903 ComputeDynamicType(Info
, E
, Ptr
, AK_DynamicCast
);
5907 // C++ [expr.dynamic.cast]p7:
5908 // If T is "pointer to cv void", then the result is a pointer to the most
5910 if (E
->getType()->isVoidPointerType())
5911 return CastToDerivedClass(Info
, E
, Ptr
, DynType
->Type
, DynType
->PathLength
);
5913 const CXXRecordDecl
*C
= E
->getTypeAsWritten()->getPointeeCXXRecordDecl();
5914 assert(C
&& "dynamic_cast target is not void pointer nor class");
5915 CanQualType CQT
= Info
.Ctx
.getCanonicalType(Info
.Ctx
.getRecordType(C
));
5917 auto RuntimeCheckFailed
= [&] (CXXBasePaths
*Paths
) {
5918 // C++ [expr.dynamic.cast]p9:
5919 if (!E
->isGLValue()) {
5920 // The value of a failed cast to pointer type is the null pointer value
5921 // of the required result type.
5922 Ptr
.setNull(Info
.Ctx
, E
->getType());
5926 // A failed cast to reference type throws [...] std::bad_cast.
5928 if (!Paths
&& (declaresSameEntity(DynType
->Type
, C
) ||
5929 DynType
->Type
->isDerivedFrom(C
)))
5931 else if (!Paths
|| Paths
->begin() == Paths
->end())
5933 else if (Paths
->isAmbiguous(CQT
))
5936 assert(Paths
->front().Access
!= AS_public
&& "why did the cast fail?");
5939 Info
.FFDiag(E
, diag::note_constexpr_dynamic_cast_to_reference_failed
)
5940 << DiagKind
<< Ptr
.Designator
.getType(Info
.Ctx
)
5941 << Info
.Ctx
.getRecordType(DynType
->Type
)
5942 << E
->getType().getUnqualifiedType();
5946 // Runtime check, phase 1:
5947 // Walk from the base subobject towards the derived object looking for the
5949 for (int PathLength
= Ptr
.Designator
.Entries
.size();
5950 PathLength
>= (int)DynType
->PathLength
; --PathLength
) {
5951 const CXXRecordDecl
*Class
= getBaseClassType(Ptr
.Designator
, PathLength
);
5952 if (declaresSameEntity(Class
, C
))
5953 return CastToDerivedClass(Info
, E
, Ptr
, Class
, PathLength
);
5954 // We can only walk across public inheritance edges.
5955 if (PathLength
> (int)DynType
->PathLength
&&
5956 !isBaseClassPublic(getBaseClassType(Ptr
.Designator
, PathLength
- 1),
5958 return RuntimeCheckFailed(nullptr);
5961 // Runtime check, phase 2:
5962 // Search the dynamic type for an unambiguous public base of type C.
5963 CXXBasePaths
Paths(/*FindAmbiguities=*/true,
5964 /*RecordPaths=*/true, /*DetectVirtual=*/false);
5965 if (DynType
->Type
->isDerivedFrom(C
, Paths
) && !Paths
.isAmbiguous(CQT
) &&
5966 Paths
.front().Access
== AS_public
) {
5967 // Downcast to the dynamic type...
5968 if (!CastToDerivedClass(Info
, E
, Ptr
, DynType
->Type
, DynType
->PathLength
))
5970 // ... then upcast to the chosen base class subobject.
5971 for (CXXBasePathElement
&Elem
: Paths
.front())
5972 if (!HandleLValueBase(Info
, E
, Ptr
, Elem
.Class
, Elem
.Base
))
5977 // Otherwise, the runtime check fails.
5978 return RuntimeCheckFailed(&Paths
);
5982 struct StartLifetimeOfUnionMemberHandler
{
5984 const Expr
*LHSExpr
;
5985 const FieldDecl
*Field
;
5987 bool Failed
= false;
5988 static const AccessKinds AccessKind
= AK_Assign
;
5990 typedef bool result_type
;
5991 bool failed() { return Failed
; }
5992 bool found(APValue
&Subobj
, QualType SubobjType
) {
5993 // We are supposed to perform no initialization but begin the lifetime of
5994 // the object. We interpret that as meaning to do what default
5995 // initialization of the object would do if all constructors involved were
5997 // * All base, non-variant member, and array element subobjects' lifetimes
5999 // * No variant members' lifetimes begin
6000 // * All scalar subobjects whose lifetimes begin have indeterminate values
6001 assert(SubobjType
->isUnionType());
6002 if (declaresSameEntity(Subobj
.getUnionField(), Field
)) {
6003 // This union member is already active. If it's also in-lifetime, there's
6005 if (Subobj
.getUnionValue().hasValue())
6007 } else if (DuringInit
) {
6008 // We're currently in the process of initializing a different union
6009 // member. If we carried on, that initialization would attempt to
6010 // store to an inactive union member, resulting in undefined behavior.
6011 Info
.FFDiag(LHSExpr
,
6012 diag::note_constexpr_union_member_change_during_init
);
6016 Failed
= !handleDefaultInitValue(Field
->getType(), Result
);
6017 Subobj
.setUnion(Field
, Result
);
6020 bool found(APSInt
&Value
, QualType SubobjType
) {
6021 llvm_unreachable("wrong value kind for union object");
6023 bool found(APFloat
&Value
, QualType SubobjType
) {
6024 llvm_unreachable("wrong value kind for union object");
6027 } // end anonymous namespace
6029 const AccessKinds
StartLifetimeOfUnionMemberHandler::AccessKind
;
6031 /// Handle a builtin simple-assignment or a call to a trivial assignment
6032 /// operator whose left-hand side might involve a union member access. If it
6033 /// does, implicitly start the lifetime of any accessed union elements per
6034 /// C++20 [class.union]5.
6035 static bool MaybeHandleUnionActiveMemberChange(EvalInfo
&Info
,
6036 const Expr
*LHSExpr
,
6037 const LValue
&LHS
) {
6038 if (LHS
.InvalidBase
|| LHS
.Designator
.Invalid
)
6041 llvm::SmallVector
<std::pair
<unsigned, const FieldDecl
*>, 4> UnionPathLengths
;
6042 // C++ [class.union]p5:
6043 // define the set S(E) of subexpressions of E as follows:
6044 unsigned PathLength
= LHS
.Designator
.Entries
.size();
6045 for (const Expr
*E
= LHSExpr
; E
!= nullptr;) {
6046 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6047 if (auto *ME
= dyn_cast
<MemberExpr
>(E
)) {
6048 auto *FD
= dyn_cast
<FieldDecl
>(ME
->getMemberDecl());
6049 // Note that we can't implicitly start the lifetime of a reference,
6050 // so we don't need to proceed any further if we reach one.
6051 if (!FD
|| FD
->getType()->isReferenceType())
6054 // ... and also contains A.B if B names a union member ...
6055 if (FD
->getParent()->isUnion()) {
6056 // ... of a non-class, non-array type, or of a class type with a
6057 // trivial default constructor that is not deleted, or an array of
6060 FD
->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6061 if (!RD
|| RD
->hasTrivialDefaultConstructor())
6062 UnionPathLengths
.push_back({PathLength
- 1, FD
});
6067 assert(declaresSameEntity(FD
,
6068 LHS
.Designator
.Entries
[PathLength
]
6069 .getAsBaseOrMember().getPointer()));
6071 // -- If E is of the form A[B] and is interpreted as a built-in array
6072 // subscripting operator, S(E) is [S(the array operand, if any)].
6073 } else if (auto *ASE
= dyn_cast
<ArraySubscriptExpr
>(E
)) {
6074 // Step over an ArrayToPointerDecay implicit cast.
6075 auto *Base
= ASE
->getBase()->IgnoreImplicit();
6076 if (!Base
->getType()->isArrayType())
6082 } else if (auto *ICE
= dyn_cast
<ImplicitCastExpr
>(E
)) {
6083 // Step over a derived-to-base conversion.
6084 E
= ICE
->getSubExpr();
6085 if (ICE
->getCastKind() == CK_NoOp
)
6087 if (ICE
->getCastKind() != CK_DerivedToBase
&&
6088 ICE
->getCastKind() != CK_UncheckedDerivedToBase
)
6090 // Walk path backwards as we walk up from the base to the derived class.
6091 for (const CXXBaseSpecifier
*Elt
: llvm::reverse(ICE
->path())) {
6092 if (Elt
->isVirtual()) {
6093 // A class with virtual base classes never has a trivial default
6094 // constructor, so S(E) is empty in this case.
6100 assert(declaresSameEntity(Elt
->getType()->getAsCXXRecordDecl(),
6101 LHS
.Designator
.Entries
[PathLength
]
6102 .getAsBaseOrMember().getPointer()));
6105 // -- Otherwise, S(E) is empty.
6111 // Common case: no unions' lifetimes are started.
6112 if (UnionPathLengths
.empty())
6115 // if modification of X [would access an inactive union member], an object
6116 // of the type of X is implicitly created
6117 CompleteObject Obj
=
6118 findCompleteObject(Info
, LHSExpr
, AK_Assign
, LHS
, LHSExpr
->getType());
6121 for (std::pair
<unsigned, const FieldDecl
*> LengthAndField
:
6122 llvm::reverse(UnionPathLengths
)) {
6123 // Form a designator for the union object.
6124 SubobjectDesignator D
= LHS
.Designator
;
6125 D
.truncate(Info
.Ctx
, LHS
.Base
, LengthAndField
.first
);
6127 bool DuringInit
= Info
.isEvaluatingCtorDtor(LHS
.Base
, D
.Entries
) ==
6128 ConstructionPhase::AfterBases
;
6129 StartLifetimeOfUnionMemberHandler StartLifetime
{
6130 Info
, LHSExpr
, LengthAndField
.second
, DuringInit
};
6131 if (!findSubobject(Info
, LHSExpr
, Obj
, D
, StartLifetime
))
6138 static bool EvaluateCallArg(const ParmVarDecl
*PVD
, const Expr
*Arg
,
6139 CallRef Call
, EvalInfo
&Info
,
6140 bool NonNull
= false) {
6142 // Create the parameter slot and register its destruction. For a vararg
6143 // argument, create a temporary.
6144 // FIXME: For calling conventions that destroy parameters in the callee,
6145 // should we consider performing destruction when the function returns
6147 APValue
&V
= PVD
? Info
.CurrentCall
->createParam(Call
, PVD
, LV
)
6148 : Info
.CurrentCall
->createTemporary(Arg
, Arg
->getType(),
6149 ScopeKind::Call
, LV
);
6150 if (!EvaluateInPlace(V
, Info
, LV
, Arg
))
6153 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6154 // undefined behavior, so is non-constant.
6155 if (NonNull
&& V
.isLValue() && V
.isNullPointer()) {
6156 Info
.CCEDiag(Arg
, diag::note_non_null_attribute_failed
);
6163 /// Evaluate the arguments to a function call.
6164 static bool EvaluateArgs(ArrayRef
<const Expr
*> Args
, CallRef Call
,
6165 EvalInfo
&Info
, const FunctionDecl
*Callee
,
6166 bool RightToLeft
= false) {
6167 bool Success
= true;
6168 llvm::SmallBitVector ForbiddenNullArgs
;
6169 if (Callee
->hasAttr
<NonNullAttr
>()) {
6170 ForbiddenNullArgs
.resize(Args
.size());
6171 for (const auto *Attr
: Callee
->specific_attrs
<NonNullAttr
>()) {
6172 if (!Attr
->args_size()) {
6173 ForbiddenNullArgs
.set();
6176 for (auto Idx
: Attr
->args()) {
6177 unsigned ASTIdx
= Idx
.getASTIndex();
6178 if (ASTIdx
>= Args
.size())
6180 ForbiddenNullArgs
[ASTIdx
] = true;
6184 for (unsigned I
= 0; I
< Args
.size(); I
++) {
6185 unsigned Idx
= RightToLeft
? Args
.size() - I
- 1 : I
;
6186 const ParmVarDecl
*PVD
=
6187 Idx
< Callee
->getNumParams() ? Callee
->getParamDecl(Idx
) : nullptr;
6188 bool NonNull
= !ForbiddenNullArgs
.empty() && ForbiddenNullArgs
[Idx
];
6189 if (!EvaluateCallArg(PVD
, Args
[Idx
], Call
, Info
, NonNull
)) {
6190 // If we're checking for a potential constant expression, evaluate all
6191 // initializers even if some of them fail.
6192 if (!Info
.noteFailure())
6200 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6201 /// constructor or assignment operator.
6202 static bool handleTrivialCopy(EvalInfo
&Info
, const ParmVarDecl
*Param
,
6203 const Expr
*E
, APValue
&Result
,
6204 bool CopyObjectRepresentation
) {
6205 // Find the reference argument.
6206 CallStackFrame
*Frame
= Info
.CurrentCall
;
6207 APValue
*RefValue
= Info
.getParamSlot(Frame
->Arguments
, Param
);
6213 // Copy out the contents of the RHS object.
6215 RefLValue
.setFrom(Info
.Ctx
, *RefValue
);
6216 return handleLValueToRValueConversion(
6217 Info
, E
, Param
->getType().getNonReferenceType(), RefLValue
, Result
,
6218 CopyObjectRepresentation
);
6221 /// Evaluate a function call.
6222 static bool HandleFunctionCall(SourceLocation CallLoc
,
6223 const FunctionDecl
*Callee
, const LValue
*This
,
6224 const Expr
*E
, ArrayRef
<const Expr
*> Args
,
6225 CallRef Call
, const Stmt
*Body
, EvalInfo
&Info
,
6226 APValue
&Result
, const LValue
*ResultSlot
) {
6227 if (!Info
.CheckCallLimit(CallLoc
))
6230 CallStackFrame
Frame(Info
, E
->getSourceRange(), Callee
, This
, E
, Call
);
6232 // For a trivial copy or move assignment, perform an APValue copy. This is
6233 // essential for unions, where the operations performed by the assignment
6234 // operator cannot be represented as statements.
6236 // Skip this for non-union classes with no fields; in that case, the defaulted
6237 // copy/move does not actually read the object.
6238 const CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(Callee
);
6239 if (MD
&& MD
->isDefaulted() &&
6240 (MD
->getParent()->isUnion() ||
6242 isReadByLvalueToRvalueConversion(MD
->getParent())))) {
6244 (MD
->isCopyAssignmentOperator() || MD
->isMoveAssignmentOperator()));
6246 if (!handleTrivialCopy(Info
, MD
->getParamDecl(0), Args
[0], RHSValue
,
6247 MD
->getParent()->isUnion()))
6249 if (!handleAssignment(Info
, Args
[0], *This
, MD
->getThisType(),
6252 This
->moveInto(Result
);
6254 } else if (MD
&& isLambdaCallOperator(MD
)) {
6255 // We're in a lambda; determine the lambda capture field maps unless we're
6256 // just constexpr checking a lambda's call operator. constexpr checking is
6257 // done before the captures have been added to the closure object (unless
6258 // we're inferring constexpr-ness), so we don't have access to them in this
6259 // case. But since we don't need the captures to constexpr check, we can
6260 // just ignore them.
6261 if (!Info
.checkingPotentialConstantExpression())
6262 MD
->getParent()->getCaptureFields(Frame
.LambdaCaptureFields
,
6263 Frame
.LambdaThisCaptureField
);
6266 StmtResult Ret
= {Result
, ResultSlot
};
6267 EvalStmtResult ESR
= EvaluateStmt(Ret
, Info
, Body
);
6268 if (ESR
== ESR_Succeeded
) {
6269 if (Callee
->getReturnType()->isVoidType())
6271 Info
.FFDiag(Callee
->getEndLoc(), diag::note_constexpr_no_return
);
6273 return ESR
== ESR_Returned
;
6276 /// Evaluate a constructor call.
6277 static bool HandleConstructorCall(const Expr
*E
, const LValue
&This
,
6279 const CXXConstructorDecl
*Definition
,
6280 EvalInfo
&Info
, APValue
&Result
) {
6281 SourceLocation CallLoc
= E
->getExprLoc();
6282 if (!Info
.CheckCallLimit(CallLoc
))
6285 const CXXRecordDecl
*RD
= Definition
->getParent();
6286 if (RD
->getNumVBases()) {
6287 Info
.FFDiag(CallLoc
, diag::note_constexpr_virtual_base
) << RD
;
6291 EvalInfo::EvaluatingConstructorRAII
EvalObj(
6293 ObjectUnderConstruction
{This
.getLValueBase(), This
.Designator
.Entries
},
6295 CallStackFrame
Frame(Info
, E
->getSourceRange(), Definition
, &This
, E
, Call
);
6297 // FIXME: Creating an APValue just to hold a nonexistent return value is
6300 StmtResult Ret
= {RetVal
, nullptr};
6302 // If it's a delegating constructor, delegate.
6303 if (Definition
->isDelegatingConstructor()) {
6304 CXXConstructorDecl::init_const_iterator I
= Definition
->init_begin();
6305 if ((*I
)->getInit()->isValueDependent()) {
6306 if (!EvaluateDependentExpr((*I
)->getInit(), Info
))
6309 FullExpressionRAII
InitScope(Info
);
6310 if (!EvaluateInPlace(Result
, Info
, This
, (*I
)->getInit()) ||
6311 !InitScope
.destroy())
6314 return EvaluateStmt(Ret
, Info
, Definition
->getBody()) != ESR_Failed
;
6317 // For a trivial copy or move constructor, perform an APValue copy. This is
6318 // essential for unions (or classes with anonymous union members), where the
6319 // operations performed by the constructor cannot be represented by
6320 // ctor-initializers.
6322 // Skip this for empty non-union classes; we should not perform an
6323 // lvalue-to-rvalue conversion on them because their copy constructor does not
6324 // actually read them.
6325 if (Definition
->isDefaulted() && Definition
->isCopyOrMoveConstructor() &&
6326 (Definition
->getParent()->isUnion() ||
6327 (Definition
->isTrivial() &&
6328 isReadByLvalueToRvalueConversion(Definition
->getParent())))) {
6329 return handleTrivialCopy(Info
, Definition
->getParamDecl(0), E
, Result
,
6330 Definition
->getParent()->isUnion());
6333 // Reserve space for the struct members.
6334 if (!Result
.hasValue()) {
6336 Result
= APValue(APValue::UninitStruct(), RD
->getNumBases(),
6337 std::distance(RD
->field_begin(), RD
->field_end()));
6339 // A union starts with no active member.
6340 Result
= APValue((const FieldDecl
*)nullptr);
6343 if (RD
->isInvalidDecl()) return false;
6344 const ASTRecordLayout
&Layout
= Info
.Ctx
.getASTRecordLayout(RD
);
6346 // A scope for temporaries lifetime-extended by reference members.
6347 BlockScopeRAII
LifetimeExtendedScope(Info
);
6349 bool Success
= true;
6350 unsigned BasesSeen
= 0;
6352 CXXRecordDecl::base_class_const_iterator BaseIt
= RD
->bases_begin();
6354 CXXRecordDecl::field_iterator FieldIt
= RD
->field_begin();
6355 auto SkipToField
= [&](FieldDecl
*FD
, bool Indirect
) {
6356 // We might be initializing the same field again if this is an indirect
6357 // field initialization.
6358 if (FieldIt
== RD
->field_end() ||
6359 FieldIt
->getFieldIndex() > FD
->getFieldIndex()) {
6360 assert(Indirect
&& "fields out of order?");
6364 // Default-initialize any fields with no explicit initializer.
6365 for (; !declaresSameEntity(*FieldIt
, FD
); ++FieldIt
) {
6366 assert(FieldIt
!= RD
->field_end() && "missing field?");
6367 if (!FieldIt
->isUnnamedBitfield())
6368 Success
&= handleDefaultInitValue(
6370 Result
.getStructField(FieldIt
->getFieldIndex()));
6374 for (const auto *I
: Definition
->inits()) {
6375 LValue Subobject
= This
;
6376 LValue SubobjectParent
= This
;
6377 APValue
*Value
= &Result
;
6379 // Determine the subobject to initialize.
6380 FieldDecl
*FD
= nullptr;
6381 if (I
->isBaseInitializer()) {
6382 QualType
BaseType(I
->getBaseClass(), 0);
6384 // Non-virtual base classes are initialized in the order in the class
6385 // definition. We have already checked for virtual base classes.
6386 assert(!BaseIt
->isVirtual() && "virtual base for literal type");
6387 assert(Info
.Ctx
.hasSameType(BaseIt
->getType(), BaseType
) &&
6388 "base class initializers not in expected order");
6391 if (!HandleLValueDirectBase(Info
, I
->getInit(), Subobject
, RD
,
6392 BaseType
->getAsCXXRecordDecl(), &Layout
))
6394 Value
= &Result
.getStructBase(BasesSeen
++);
6395 } else if ((FD
= I
->getMember())) {
6396 if (!HandleLValueMember(Info
, I
->getInit(), Subobject
, FD
, &Layout
))
6398 if (RD
->isUnion()) {
6399 Result
= APValue(FD
);
6400 Value
= &Result
.getUnionValue();
6402 SkipToField(FD
, false);
6403 Value
= &Result
.getStructField(FD
->getFieldIndex());
6405 } else if (IndirectFieldDecl
*IFD
= I
->getIndirectMember()) {
6406 // Walk the indirect field decl's chain to find the object to initialize,
6407 // and make sure we've initialized every step along it.
6408 auto IndirectFieldChain
= IFD
->chain();
6409 for (auto *C
: IndirectFieldChain
) {
6410 FD
= cast
<FieldDecl
>(C
);
6411 CXXRecordDecl
*CD
= cast
<CXXRecordDecl
>(FD
->getParent());
6412 // Switch the union field if it differs. This happens if we had
6413 // preceding zero-initialization, and we're now initializing a union
6414 // subobject other than the first.
6415 // FIXME: In this case, the values of the other subobjects are
6416 // specified, since zero-initialization sets all padding bits to zero.
6417 if (!Value
->hasValue() ||
6418 (Value
->isUnion() && Value
->getUnionField() != FD
)) {
6420 *Value
= APValue(FD
);
6422 // FIXME: This immediately starts the lifetime of all members of
6423 // an anonymous struct. It would be preferable to strictly start
6424 // member lifetime in initialization order.
6426 handleDefaultInitValue(Info
.Ctx
.getRecordType(CD
), *Value
);
6428 // Store Subobject as its parent before updating it for the last element
6430 if (C
== IndirectFieldChain
.back())
6431 SubobjectParent
= Subobject
;
6432 if (!HandleLValueMember(Info
, I
->getInit(), Subobject
, FD
))
6435 Value
= &Value
->getUnionValue();
6437 if (C
== IndirectFieldChain
.front() && !RD
->isUnion())
6438 SkipToField(FD
, true);
6439 Value
= &Value
->getStructField(FD
->getFieldIndex());
6443 llvm_unreachable("unknown base initializer kind");
6446 // Need to override This for implicit field initializers as in this case
6447 // This refers to innermost anonymous struct/union containing initializer,
6448 // not to currently constructed class.
6449 const Expr
*Init
= I
->getInit();
6450 if (Init
->isValueDependent()) {
6451 if (!EvaluateDependentExpr(Init
, Info
))
6454 ThisOverrideRAII
ThisOverride(*Info
.CurrentCall
, &SubobjectParent
,
6455 isa
<CXXDefaultInitExpr
>(Init
));
6456 FullExpressionRAII
InitScope(Info
);
6457 if (!EvaluateInPlace(*Value
, Info
, Subobject
, Init
) ||
6458 (FD
&& FD
->isBitField() &&
6459 !truncateBitfieldValue(Info
, Init
, *Value
, FD
))) {
6460 // If we're checking for a potential constant expression, evaluate all
6461 // initializers even if some of them fail.
6462 if (!Info
.noteFailure())
6468 // This is the point at which the dynamic type of the object becomes this
6470 if (I
->isBaseInitializer() && BasesSeen
== RD
->getNumBases())
6471 EvalObj
.finishedConstructingBases();
6474 // Default-initialize any remaining fields.
6475 if (!RD
->isUnion()) {
6476 for (; FieldIt
!= RD
->field_end(); ++FieldIt
) {
6477 if (!FieldIt
->isUnnamedBitfield())
6478 Success
&= handleDefaultInitValue(
6480 Result
.getStructField(FieldIt
->getFieldIndex()));
6484 EvalObj
.finishedConstructingFields();
6487 EvaluateStmt(Ret
, Info
, Definition
->getBody()) != ESR_Failed
&&
6488 LifetimeExtendedScope
.destroy();
6491 static bool HandleConstructorCall(const Expr
*E
, const LValue
&This
,
6492 ArrayRef
<const Expr
*> Args
,
6493 const CXXConstructorDecl
*Definition
,
6494 EvalInfo
&Info
, APValue
&Result
) {
6495 CallScopeRAII
CallScope(Info
);
6496 CallRef Call
= Info
.CurrentCall
->createCall(Definition
);
6497 if (!EvaluateArgs(Args
, Call
, Info
, Definition
))
6500 return HandleConstructorCall(E
, This
, Call
, Definition
, Info
, Result
) &&
6501 CallScope
.destroy();
6504 static bool HandleDestructionImpl(EvalInfo
&Info
, SourceRange CallRange
,
6505 const LValue
&This
, APValue
&Value
,
6507 // Objects can only be destroyed while they're within their lifetimes.
6508 // FIXME: We have no representation for whether an object of type nullptr_t
6509 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6510 // as indeterminate instead?
6511 if (Value
.isAbsent() && !T
->isNullPtrType()) {
6513 This
.moveInto(Printable
);
6514 Info
.FFDiag(CallRange
.getBegin(),
6515 diag::note_constexpr_destroy_out_of_lifetime
)
6516 << Printable
.getAsString(Info
.Ctx
, Info
.Ctx
.getLValueReferenceType(T
));
6520 // Invent an expression for location purposes.
6521 // FIXME: We shouldn't need to do this.
6522 OpaqueValueExpr
LocE(CallRange
.getBegin(), Info
.Ctx
.IntTy
, VK_PRValue
);
6524 // For arrays, destroy elements right-to-left.
6525 if (const ConstantArrayType
*CAT
= Info
.Ctx
.getAsConstantArrayType(T
)) {
6526 uint64_t Size
= CAT
->getSize().getZExtValue();
6527 QualType ElemT
= CAT
->getElementType();
6529 if (!CheckArraySize(Info
, CAT
, CallRange
.getBegin()))
6532 LValue ElemLV
= This
;
6533 ElemLV
.addArray(Info
, &LocE
, CAT
);
6534 if (!HandleLValueArrayAdjustment(Info
, &LocE
, ElemLV
, ElemT
, Size
))
6537 // Ensure that we have actual array elements available to destroy; the
6538 // destructors might mutate the value, so we can't run them on the array
6540 if (Size
&& Size
> Value
.getArrayInitializedElts())
6541 expandArray(Value
, Value
.getArraySize() - 1);
6543 for (; Size
!= 0; --Size
) {
6544 APValue
&Elem
= Value
.getArrayInitializedElt(Size
- 1);
6545 if (!HandleLValueArrayAdjustment(Info
, &LocE
, ElemLV
, ElemT
, -1) ||
6546 !HandleDestructionImpl(Info
, CallRange
, ElemLV
, Elem
, ElemT
))
6550 // End the lifetime of this array now.
6555 const CXXRecordDecl
*RD
= T
->getAsCXXRecordDecl();
6557 if (T
.isDestructedType()) {
6558 Info
.FFDiag(CallRange
.getBegin(),
6559 diag::note_constexpr_unsupported_destruction
)
6568 if (RD
->getNumVBases()) {
6569 Info
.FFDiag(CallRange
.getBegin(), diag::note_constexpr_virtual_base
) << RD
;
6573 const CXXDestructorDecl
*DD
= RD
->getDestructor();
6574 if (!DD
&& !RD
->hasTrivialDestructor()) {
6575 Info
.FFDiag(CallRange
.getBegin());
6579 if (!DD
|| DD
->isTrivial() ||
6580 (RD
->isAnonymousStructOrUnion() && RD
->isUnion())) {
6581 // A trivial destructor just ends the lifetime of the object. Check for
6582 // this case before checking for a body, because we might not bother
6583 // building a body for a trivial destructor. Note that it doesn't matter
6584 // whether the destructor is constexpr in this case; all trivial
6585 // destructors are constexpr.
6587 // If an anonymous union would be destroyed, some enclosing destructor must
6588 // have been explicitly defined, and the anonymous union destruction should
6594 if (!Info
.CheckCallLimit(CallRange
.getBegin()))
6597 const FunctionDecl
*Definition
= nullptr;
6598 const Stmt
*Body
= DD
->getBody(Definition
);
6600 if (!CheckConstexprFunction(Info
, CallRange
.getBegin(), DD
, Definition
, Body
))
6603 CallStackFrame
Frame(Info
, CallRange
, Definition
, &This
, /*CallExpr=*/nullptr,
6606 // We're now in the period of destruction of this object.
6607 unsigned BasesLeft
= RD
->getNumBases();
6608 EvalInfo::EvaluatingDestructorRAII
EvalObj(
6610 ObjectUnderConstruction
{This
.getLValueBase(), This
.Designator
.Entries
});
6611 if (!EvalObj
.DidInsert
) {
6612 // C++2a [class.dtor]p19:
6613 // the behavior is undefined if the destructor is invoked for an object
6614 // whose lifetime has ended
6615 // (Note that formally the lifetime ends when the period of destruction
6616 // begins, even though certain uses of the object remain valid until the
6617 // period of destruction ends.)
6618 Info
.FFDiag(CallRange
.getBegin(), diag::note_constexpr_double_destroy
);
6622 // FIXME: Creating an APValue just to hold a nonexistent return value is
6625 StmtResult Ret
= {RetVal
, nullptr};
6626 if (EvaluateStmt(Ret
, Info
, Definition
->getBody()) == ESR_Failed
)
6629 // A union destructor does not implicitly destroy its members.
6633 const ASTRecordLayout
&Layout
= Info
.Ctx
.getASTRecordLayout(RD
);
6635 // We don't have a good way to iterate fields in reverse, so collect all the
6636 // fields first and then walk them backwards.
6637 SmallVector
<FieldDecl
*, 16> Fields(RD
->fields());
6638 for (const FieldDecl
*FD
: llvm::reverse(Fields
)) {
6639 if (FD
->isUnnamedBitfield())
6642 LValue Subobject
= This
;
6643 if (!HandleLValueMember(Info
, &LocE
, Subobject
, FD
, &Layout
))
6646 APValue
*SubobjectValue
= &Value
.getStructField(FD
->getFieldIndex());
6647 if (!HandleDestructionImpl(Info
, CallRange
, Subobject
, *SubobjectValue
,
6653 EvalObj
.startedDestroyingBases();
6655 // Destroy base classes in reverse order.
6656 for (const CXXBaseSpecifier
&Base
: llvm::reverse(RD
->bases())) {
6659 QualType BaseType
= Base
.getType();
6660 LValue Subobject
= This
;
6661 if (!HandleLValueDirectBase(Info
, &LocE
, Subobject
, RD
,
6662 BaseType
->getAsCXXRecordDecl(), &Layout
))
6665 APValue
*SubobjectValue
= &Value
.getStructBase(BasesLeft
);
6666 if (!HandleDestructionImpl(Info
, CallRange
, Subobject
, *SubobjectValue
,
6670 assert(BasesLeft
== 0 && "NumBases was wrong?");
6672 // The period of destruction ends now. The object is gone.
6678 struct DestroyObjectHandler
{
6682 const AccessKinds AccessKind
;
6684 typedef bool result_type
;
6685 bool failed() { return false; }
6686 bool found(APValue
&Subobj
, QualType SubobjType
) {
6687 return HandleDestructionImpl(Info
, E
->getSourceRange(), This
, Subobj
,
6690 bool found(APSInt
&Value
, QualType SubobjType
) {
6691 Info
.FFDiag(E
, diag::note_constexpr_destroy_complex_elem
);
6694 bool found(APFloat
&Value
, QualType SubobjType
) {
6695 Info
.FFDiag(E
, diag::note_constexpr_destroy_complex_elem
);
6701 /// Perform a destructor or pseudo-destructor call on the given object, which
6702 /// might in general not be a complete object.
6703 static bool HandleDestruction(EvalInfo
&Info
, const Expr
*E
,
6704 const LValue
&This
, QualType ThisType
) {
6705 CompleteObject Obj
= findCompleteObject(Info
, E
, AK_Destroy
, This
, ThisType
);
6706 DestroyObjectHandler Handler
= {Info
, E
, This
, AK_Destroy
};
6707 return Obj
&& findSubobject(Info
, E
, Obj
, This
.Designator
, Handler
);
6710 /// Destroy and end the lifetime of the given complete object.
6711 static bool HandleDestruction(EvalInfo
&Info
, SourceLocation Loc
,
6712 APValue::LValueBase LVBase
, APValue
&Value
,
6714 // If we've had an unmodeled side-effect, we can't rely on mutable state
6715 // (such as the object we're about to destroy) being correct.
6716 if (Info
.EvalStatus
.HasSideEffects
)
6721 return HandleDestructionImpl(Info
, Loc
, LV
, Value
, T
);
6724 /// Perform a call to 'operator new' or to `__builtin_operator_new'.
6725 static bool HandleOperatorNewCall(EvalInfo
&Info
, const CallExpr
*E
,
6727 if (Info
.checkingPotentialConstantExpression() ||
6728 Info
.SpeculativeEvaluationDepth
)
6731 // This is permitted only within a call to std::allocator<T>::allocate.
6732 auto Caller
= Info
.getStdAllocatorCaller("allocate");
6734 Info
.FFDiag(E
->getExprLoc(), Info
.getLangOpts().CPlusPlus20
6735 ? diag::note_constexpr_new_untyped
6736 : diag::note_constexpr_new
);
6740 QualType ElemType
= Caller
.ElemType
;
6741 if (ElemType
->isIncompleteType() || ElemType
->isFunctionType()) {
6742 Info
.FFDiag(E
->getExprLoc(),
6743 diag::note_constexpr_new_not_complete_object_type
)
6744 << (ElemType
->isIncompleteType() ? 0 : 1) << ElemType
;
6749 if (!EvaluateInteger(E
->getArg(0), ByteSize
, Info
))
6751 bool IsNothrow
= false;
6752 for (unsigned I
= 1, N
= E
->getNumArgs(); I
!= N
; ++I
) {
6753 EvaluateIgnoredValue(Info
, E
->getArg(I
));
6754 IsNothrow
|= E
->getType()->isNothrowT();
6758 if (!HandleSizeof(Info
, E
->getExprLoc(), ElemType
, ElemSize
))
6760 APInt Size
, Remainder
;
6761 APInt
ElemSizeAP(ByteSize
.getBitWidth(), ElemSize
.getQuantity());
6762 APInt::udivrem(ByteSize
, ElemSizeAP
, Size
, Remainder
);
6763 if (Remainder
!= 0) {
6764 // This likely indicates a bug in the implementation of 'std::allocator'.
6765 Info
.FFDiag(E
->getExprLoc(), diag::note_constexpr_operator_new_bad_size
)
6766 << ByteSize
<< APSInt(ElemSizeAP
, true) << ElemType
;
6770 if (!Info
.CheckArraySize(E
->getBeginLoc(), ByteSize
.getActiveBits(),
6771 Size
.getZExtValue(), /*Diag=*/!IsNothrow
)) {
6773 Result
.setNull(Info
.Ctx
, E
->getType());
6779 QualType AllocType
= Info
.Ctx
.getConstantArrayType(
6780 ElemType
, Size
, nullptr, ArraySizeModifier::Normal
, 0);
6781 APValue
*Val
= Info
.createHeapAlloc(E
, AllocType
, Result
);
6782 *Val
= APValue(APValue::UninitArray(), 0, Size
.getZExtValue());
6783 Result
.addArray(Info
, E
, cast
<ConstantArrayType
>(AllocType
));
6787 static bool hasVirtualDestructor(QualType T
) {
6788 if (CXXRecordDecl
*RD
= T
->getAsCXXRecordDecl())
6789 if (CXXDestructorDecl
*DD
= RD
->getDestructor())
6790 return DD
->isVirtual();
6794 static const FunctionDecl
*getVirtualOperatorDelete(QualType T
) {
6795 if (CXXRecordDecl
*RD
= T
->getAsCXXRecordDecl())
6796 if (CXXDestructorDecl
*DD
= RD
->getDestructor())
6797 return DD
->isVirtual() ? DD
->getOperatorDelete() : nullptr;
6801 /// Check that the given object is a suitable pointer to a heap allocation that
6802 /// still exists and is of the right kind for the purpose of a deletion.
6804 /// On success, returns the heap allocation to deallocate. On failure, produces
6805 /// a diagnostic and returns std::nullopt.
6806 static std::optional
<DynAlloc
*> CheckDeleteKind(EvalInfo
&Info
, const Expr
*E
,
6807 const LValue
&Pointer
,
6808 DynAlloc::Kind DeallocKind
) {
6809 auto PointerAsString
= [&] {
6810 return Pointer
.toString(Info
.Ctx
, Info
.Ctx
.VoidPtrTy
);
6813 DynamicAllocLValue DA
= Pointer
.Base
.dyn_cast
<DynamicAllocLValue
>();
6815 Info
.FFDiag(E
, diag::note_constexpr_delete_not_heap_alloc
)
6816 << PointerAsString();
6818 NoteLValueLocation(Info
, Pointer
.Base
);
6819 return std::nullopt
;
6822 std::optional
<DynAlloc
*> Alloc
= Info
.lookupDynamicAlloc(DA
);
6824 Info
.FFDiag(E
, diag::note_constexpr_double_delete
);
6825 return std::nullopt
;
6828 if (DeallocKind
!= (*Alloc
)->getKind()) {
6829 QualType AllocType
= Pointer
.Base
.getDynamicAllocType();
6830 Info
.FFDiag(E
, diag::note_constexpr_new_delete_mismatch
)
6831 << DeallocKind
<< (*Alloc
)->getKind() << AllocType
;
6832 NoteLValueLocation(Info
, Pointer
.Base
);
6833 return std::nullopt
;
6836 bool Subobject
= false;
6837 if (DeallocKind
== DynAlloc::New
) {
6838 Subobject
= Pointer
.Designator
.MostDerivedPathLength
!= 0 ||
6839 Pointer
.Designator
.isOnePastTheEnd();
6841 Subobject
= Pointer
.Designator
.Entries
.size() != 1 ||
6842 Pointer
.Designator
.Entries
[0].getAsArrayIndex() != 0;
6845 Info
.FFDiag(E
, diag::note_constexpr_delete_subobject
)
6846 << PointerAsString() << Pointer
.Designator
.isOnePastTheEnd();
6847 return std::nullopt
;
6853 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6854 bool HandleOperatorDeleteCall(EvalInfo
&Info
, const CallExpr
*E
) {
6855 if (Info
.checkingPotentialConstantExpression() ||
6856 Info
.SpeculativeEvaluationDepth
)
6859 // This is permitted only within a call to std::allocator<T>::deallocate.
6860 if (!Info
.getStdAllocatorCaller("deallocate")) {
6861 Info
.FFDiag(E
->getExprLoc());
6866 if (!EvaluatePointer(E
->getArg(0), Pointer
, Info
))
6868 for (unsigned I
= 1, N
= E
->getNumArgs(); I
!= N
; ++I
)
6869 EvaluateIgnoredValue(Info
, E
->getArg(I
));
6871 if (Pointer
.Designator
.Invalid
)
6874 // Deleting a null pointer would have no effect, but it's not permitted by
6875 // std::allocator<T>::deallocate's contract.
6876 if (Pointer
.isNullPointer()) {
6877 Info
.CCEDiag(E
->getExprLoc(), diag::note_constexpr_deallocate_null
);
6881 if (!CheckDeleteKind(Info
, E
, Pointer
, DynAlloc::StdAllocator
))
6884 Info
.HeapAllocs
.erase(Pointer
.Base
.get
<DynamicAllocLValue
>());
6888 //===----------------------------------------------------------------------===//
6889 // Generic Evaluation
6890 //===----------------------------------------------------------------------===//
6893 class BitCastBuffer
{
6894 // FIXME: We're going to need bit-level granularity when we support
6896 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6897 // we don't support a host or target where that is the case. Still, we should
6898 // use a more generic type in case we ever do.
6899 SmallVector
<std::optional
<unsigned char>, 32> Bytes
;
6901 static_assert(std::numeric_limits
<unsigned char>::digits
>= 8,
6902 "Need at least 8 bit unsigned char");
6904 bool TargetIsLittleEndian
;
6907 BitCastBuffer(CharUnits Width
, bool TargetIsLittleEndian
)
6908 : Bytes(Width
.getQuantity()),
6909 TargetIsLittleEndian(TargetIsLittleEndian
) {}
6911 [[nodiscard
]] bool readObject(CharUnits Offset
, CharUnits Width
,
6912 SmallVectorImpl
<unsigned char> &Output
) const {
6913 for (CharUnits I
= Offset
, E
= Offset
+ Width
; I
!= E
; ++I
) {
6914 // If a byte of an integer is uninitialized, then the whole integer is
6916 if (!Bytes
[I
.getQuantity()])
6918 Output
.push_back(*Bytes
[I
.getQuantity()]);
6920 if (llvm::sys::IsLittleEndianHost
!= TargetIsLittleEndian
)
6921 std::reverse(Output
.begin(), Output
.end());
6925 void writeObject(CharUnits Offset
, SmallVectorImpl
<unsigned char> &Input
) {
6926 if (llvm::sys::IsLittleEndianHost
!= TargetIsLittleEndian
)
6927 std::reverse(Input
.begin(), Input
.end());
6930 for (unsigned char Byte
: Input
) {
6931 assert(!Bytes
[Offset
.getQuantity() + Index
] && "overwriting a byte?");
6932 Bytes
[Offset
.getQuantity() + Index
] = Byte
;
6937 size_t size() { return Bytes
.size(); }
6940 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6941 /// target would represent the value at runtime.
6942 class APValueToBufferConverter
{
6944 BitCastBuffer Buffer
;
6945 const CastExpr
*BCE
;
6947 APValueToBufferConverter(EvalInfo
&Info
, CharUnits ObjectWidth
,
6948 const CastExpr
*BCE
)
6950 Buffer(ObjectWidth
, Info
.Ctx
.getTargetInfo().isLittleEndian()),
6953 bool visit(const APValue
&Val
, QualType Ty
) {
6954 return visit(Val
, Ty
, CharUnits::fromQuantity(0));
6957 // Write out Val with type Ty into Buffer starting at Offset.
6958 bool visit(const APValue
&Val
, QualType Ty
, CharUnits Offset
) {
6959 assert((size_t)Offset
.getQuantity() <= Buffer
.size());
6961 // As a special case, nullptr_t has an indeterminate value.
6962 if (Ty
->isNullPtrType())
6965 // Dig through Src to find the byte at SrcOffset.
6966 switch (Val
.getKind()) {
6967 case APValue::Indeterminate
:
6972 return visitInt(Val
.getInt(), Ty
, Offset
);
6973 case APValue::Float
:
6974 return visitFloat(Val
.getFloat(), Ty
, Offset
);
6975 case APValue::Array
:
6976 return visitArray(Val
, Ty
, Offset
);
6977 case APValue::Struct
:
6978 return visitRecord(Val
, Ty
, Offset
);
6979 case APValue::Vector
:
6980 return visitVector(Val
, Ty
, Offset
);
6982 case APValue::ComplexInt
:
6983 case APValue::ComplexFloat
:
6984 case APValue::FixedPoint
:
6985 // FIXME: We should support these.
6987 case APValue::Union
:
6988 case APValue::MemberPointer
:
6989 case APValue::AddrLabelDiff
: {
6990 Info
.FFDiag(BCE
->getBeginLoc(),
6991 diag::note_constexpr_bit_cast_unsupported_type
)
6996 case APValue::LValue
:
6997 llvm_unreachable("LValue subobject in bit_cast?");
6999 llvm_unreachable("Unhandled APValue::ValueKind");
7002 bool visitRecord(const APValue
&Val
, QualType Ty
, CharUnits Offset
) {
7003 const RecordDecl
*RD
= Ty
->getAsRecordDecl();
7004 const ASTRecordLayout
&Layout
= Info
.Ctx
.getASTRecordLayout(RD
);
7006 // Visit the base classes.
7007 if (auto *CXXRD
= dyn_cast
<CXXRecordDecl
>(RD
)) {
7008 for (size_t I
= 0, E
= CXXRD
->getNumBases(); I
!= E
; ++I
) {
7009 const CXXBaseSpecifier
&BS
= CXXRD
->bases_begin()[I
];
7010 CXXRecordDecl
*BaseDecl
= BS
.getType()->getAsCXXRecordDecl();
7012 if (!visitRecord(Val
.getStructBase(I
), BS
.getType(),
7013 Layout
.getBaseClassOffset(BaseDecl
) + Offset
))
7018 // Visit the fields.
7019 unsigned FieldIdx
= 0;
7020 for (FieldDecl
*FD
: RD
->fields()) {
7021 if (FD
->isBitField()) {
7022 Info
.FFDiag(BCE
->getBeginLoc(),
7023 diag::note_constexpr_bit_cast_unsupported_bitfield
);
7027 uint64_t FieldOffsetBits
= Layout
.getFieldOffset(FieldIdx
);
7029 assert(FieldOffsetBits
% Info
.Ctx
.getCharWidth() == 0 &&
7030 "only bit-fields can have sub-char alignment");
7031 CharUnits FieldOffset
=
7032 Info
.Ctx
.toCharUnitsFromBits(FieldOffsetBits
) + Offset
;
7033 QualType FieldTy
= FD
->getType();
7034 if (!visit(Val
.getStructField(FieldIdx
), FieldTy
, FieldOffset
))
7042 bool visitArray(const APValue
&Val
, QualType Ty
, CharUnits Offset
) {
7044 dyn_cast_or_null
<ConstantArrayType
>(Ty
->getAsArrayTypeUnsafe());
7048 CharUnits ElemWidth
= Info
.Ctx
.getTypeSizeInChars(CAT
->getElementType());
7049 unsigned NumInitializedElts
= Val
.getArrayInitializedElts();
7050 unsigned ArraySize
= Val
.getArraySize();
7051 // First, initialize the initialized elements.
7052 for (unsigned I
= 0; I
!= NumInitializedElts
; ++I
) {
7053 const APValue
&SubObj
= Val
.getArrayInitializedElt(I
);
7054 if (!visit(SubObj
, CAT
->getElementType(), Offset
+ I
* ElemWidth
))
7058 // Next, initialize the rest of the array using the filler.
7059 if (Val
.hasArrayFiller()) {
7060 const APValue
&Filler
= Val
.getArrayFiller();
7061 for (unsigned I
= NumInitializedElts
; I
!= ArraySize
; ++I
) {
7062 if (!visit(Filler
, CAT
->getElementType(), Offset
+ I
* ElemWidth
))
7070 bool visitVector(const APValue
&Val
, QualType Ty
, CharUnits Offset
) {
7071 const VectorType
*VTy
= Ty
->castAs
<VectorType
>();
7072 QualType EltTy
= VTy
->getElementType();
7073 unsigned NElts
= VTy
->getNumElements();
7075 VTy
->isExtVectorBoolType() ? 1 : Info
.Ctx
.getTypeSize(EltTy
);
7077 if ((NElts
* EltSize
) % Info
.Ctx
.getCharWidth() != 0) {
7078 // The vector's size in bits is not a multiple of the target's byte size,
7079 // so its layout is unspecified. For now, we'll simply treat these cases
7080 // as unsupported (this should only be possible with OpenCL bool vectors
7081 // whose element count isn't a multiple of the byte size).
7082 Info
.FFDiag(BCE
->getBeginLoc(),
7083 diag::note_constexpr_bit_cast_invalid_vector
)
7084 << Ty
.getCanonicalType() << EltSize
<< NElts
7085 << Info
.Ctx
.getCharWidth();
7089 if (EltTy
->isRealFloatingType() && &Info
.Ctx
.getFloatTypeSemantics(EltTy
) ==
7090 &APFloat::x87DoubleExtended()) {
7091 // The layout for x86_fp80 vectors seems to be handled very inconsistently
7092 // by both clang and LLVM, so for now we won't allow bit_casts involving
7093 // it in a constexpr context.
7094 Info
.FFDiag(BCE
->getBeginLoc(),
7095 diag::note_constexpr_bit_cast_unsupported_type
)
7100 if (VTy
->isExtVectorBoolType()) {
7101 // Special handling for OpenCL bool vectors:
7102 // Since these vectors are stored as packed bits, but we can't write
7103 // individual bits to the BitCastBuffer, we'll buffer all of the elements
7104 // together into an appropriately sized APInt and write them all out at
7105 // once. Because we don't accept vectors where NElts * EltSize isn't a
7106 // multiple of the char size, there will be no padding space, so we don't
7107 // have to worry about writing data which should have been left
7109 bool BigEndian
= Info
.Ctx
.getTargetInfo().isBigEndian();
7111 llvm::APInt Res
= llvm::APInt::getZero(NElts
);
7112 for (unsigned I
= 0; I
< NElts
; ++I
) {
7113 const llvm::APSInt
&EltAsInt
= Val
.getVectorElt(I
).getInt();
7114 assert(EltAsInt
.isUnsigned() && EltAsInt
.getBitWidth() == 1 &&
7115 "bool vector element must be 1-bit unsigned integer!");
7117 Res
.insertBits(EltAsInt
, BigEndian
? (NElts
- I
- 1) : I
);
7120 SmallVector
<uint8_t, 8> Bytes(NElts
/ 8);
7121 llvm::StoreIntToMemory(Res
, &*Bytes
.begin(), NElts
/ 8);
7122 Buffer
.writeObject(Offset
, Bytes
);
7124 // Iterate over each of the elements and write them out to the buffer at
7125 // the appropriate offset.
7126 CharUnits EltSizeChars
= Info
.Ctx
.getTypeSizeInChars(EltTy
);
7127 for (unsigned I
= 0; I
< NElts
; ++I
) {
7128 if (!visit(Val
.getVectorElt(I
), EltTy
, Offset
+ I
* EltSizeChars
))
7136 bool visitInt(const APSInt
&Val
, QualType Ty
, CharUnits Offset
) {
7137 APSInt AdjustedVal
= Val
;
7138 unsigned Width
= AdjustedVal
.getBitWidth();
7139 if (Ty
->isBooleanType()) {
7140 Width
= Info
.Ctx
.getTypeSize(Ty
);
7141 AdjustedVal
= AdjustedVal
.extend(Width
);
7144 SmallVector
<uint8_t, 8> Bytes(Width
/ 8);
7145 llvm::StoreIntToMemory(AdjustedVal
, &*Bytes
.begin(), Width
/ 8);
7146 Buffer
.writeObject(Offset
, Bytes
);
7150 bool visitFloat(const APFloat
&Val
, QualType Ty
, CharUnits Offset
) {
7151 APSInt
AsInt(Val
.bitcastToAPInt());
7152 return visitInt(AsInt
, Ty
, Offset
);
7156 static std::optional
<BitCastBuffer
>
7157 convert(EvalInfo
&Info
, const APValue
&Src
, const CastExpr
*BCE
) {
7158 CharUnits DstSize
= Info
.Ctx
.getTypeSizeInChars(BCE
->getType());
7159 APValueToBufferConverter
Converter(Info
, DstSize
, BCE
);
7160 if (!Converter
.visit(Src
, BCE
->getSubExpr()->getType()))
7161 return std::nullopt
;
7162 return Converter
.Buffer
;
7166 /// Write an BitCastBuffer into an APValue.
7167 class BufferToAPValueConverter
{
7169 const BitCastBuffer
&Buffer
;
7170 const CastExpr
*BCE
;
7172 BufferToAPValueConverter(EvalInfo
&Info
, const BitCastBuffer
&Buffer
,
7173 const CastExpr
*BCE
)
7174 : Info(Info
), Buffer(Buffer
), BCE(BCE
) {}
7176 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7177 // with an invalid type, so anything left is a deficiency on our part (FIXME).
7178 // Ideally this will be unreachable.
7179 std::nullopt_t
unsupportedType(QualType Ty
) {
7180 Info
.FFDiag(BCE
->getBeginLoc(),
7181 diag::note_constexpr_bit_cast_unsupported_type
)
7183 return std::nullopt
;
7186 std::nullopt_t
unrepresentableValue(QualType Ty
, const APSInt
&Val
) {
7187 Info
.FFDiag(BCE
->getBeginLoc(),
7188 diag::note_constexpr_bit_cast_unrepresentable_value
)
7189 << Ty
<< toString(Val
, /*Radix=*/10);
7190 return std::nullopt
;
7193 std::optional
<APValue
> visit(const BuiltinType
*T
, CharUnits Offset
,
7194 const EnumType
*EnumSugar
= nullptr) {
7195 if (T
->isNullPtrType()) {
7196 uint64_t NullValue
= Info
.Ctx
.getTargetNullPointerValue(QualType(T
, 0));
7197 return APValue((Expr
*)nullptr,
7198 /*Offset=*/CharUnits::fromQuantity(NullValue
),
7199 APValue::NoLValuePath
{}, /*IsNullPtr=*/true);
7202 CharUnits SizeOf
= Info
.Ctx
.getTypeSizeInChars(T
);
7204 // Work around floating point types that contain unused padding bytes. This
7205 // is really just `long double` on x86, which is the only fundamental type
7206 // with padding bytes.
7207 if (T
->isRealFloatingType()) {
7208 const llvm::fltSemantics
&Semantics
=
7209 Info
.Ctx
.getFloatTypeSemantics(QualType(T
, 0));
7210 unsigned NumBits
= llvm::APFloatBase::getSizeInBits(Semantics
);
7211 assert(NumBits
% 8 == 0);
7212 CharUnits NumBytes
= CharUnits::fromQuantity(NumBits
/ 8);
7213 if (NumBytes
!= SizeOf
)
7217 SmallVector
<uint8_t, 8> Bytes
;
7218 if (!Buffer
.readObject(Offset
, SizeOf
, Bytes
)) {
7219 // If this is std::byte or unsigned char, then its okay to store an
7220 // indeterminate value.
7221 bool IsStdByte
= EnumSugar
&& EnumSugar
->isStdByteType();
7223 !EnumSugar
&& (T
->isSpecificBuiltinType(BuiltinType::UChar
) ||
7224 T
->isSpecificBuiltinType(BuiltinType::Char_U
));
7225 if (!IsStdByte
&& !IsUChar
) {
7226 QualType
DisplayType(EnumSugar
? (const Type
*)EnumSugar
: T
, 0);
7227 Info
.FFDiag(BCE
->getExprLoc(),
7228 diag::note_constexpr_bit_cast_indet_dest
)
7229 << DisplayType
<< Info
.Ctx
.getLangOpts().CharIsSigned
;
7230 return std::nullopt
;
7233 return APValue::IndeterminateValue();
7236 APSInt
Val(SizeOf
.getQuantity() * Info
.Ctx
.getCharWidth(), true);
7237 llvm::LoadIntFromMemory(Val
, &*Bytes
.begin(), Bytes
.size());
7239 if (T
->isIntegralOrEnumerationType()) {
7240 Val
.setIsSigned(T
->isSignedIntegerOrEnumerationType());
7242 unsigned IntWidth
= Info
.Ctx
.getIntWidth(QualType(T
, 0));
7243 if (IntWidth
!= Val
.getBitWidth()) {
7244 APSInt Truncated
= Val
.trunc(IntWidth
);
7245 if (Truncated
.extend(Val
.getBitWidth()) != Val
)
7246 return unrepresentableValue(QualType(T
, 0), Val
);
7250 return APValue(Val
);
7253 if (T
->isRealFloatingType()) {
7254 const llvm::fltSemantics
&Semantics
=
7255 Info
.Ctx
.getFloatTypeSemantics(QualType(T
, 0));
7256 return APValue(APFloat(Semantics
, Val
));
7259 return unsupportedType(QualType(T
, 0));
7262 std::optional
<APValue
> visit(const RecordType
*RTy
, CharUnits Offset
) {
7263 const RecordDecl
*RD
= RTy
->getAsRecordDecl();
7264 const ASTRecordLayout
&Layout
= Info
.Ctx
.getASTRecordLayout(RD
);
7266 unsigned NumBases
= 0;
7267 if (auto *CXXRD
= dyn_cast
<CXXRecordDecl
>(RD
))
7268 NumBases
= CXXRD
->getNumBases();
7270 APValue
ResultVal(APValue::UninitStruct(), NumBases
,
7271 std::distance(RD
->field_begin(), RD
->field_end()));
7273 // Visit the base classes.
7274 if (auto *CXXRD
= dyn_cast
<CXXRecordDecl
>(RD
)) {
7275 for (size_t I
= 0, E
= CXXRD
->getNumBases(); I
!= E
; ++I
) {
7276 const CXXBaseSpecifier
&BS
= CXXRD
->bases_begin()[I
];
7277 CXXRecordDecl
*BaseDecl
= BS
.getType()->getAsCXXRecordDecl();
7278 if (BaseDecl
->isEmpty() ||
7279 Info
.Ctx
.getASTRecordLayout(BaseDecl
).getNonVirtualSize().isZero())
7282 std::optional
<APValue
> SubObj
= visitType(
7283 BS
.getType(), Layout
.getBaseClassOffset(BaseDecl
) + Offset
);
7285 return std::nullopt
;
7286 ResultVal
.getStructBase(I
) = *SubObj
;
7290 // Visit the fields.
7291 unsigned FieldIdx
= 0;
7292 for (FieldDecl
*FD
: RD
->fields()) {
7293 // FIXME: We don't currently support bit-fields. A lot of the logic for
7294 // this is in CodeGen, so we need to factor it around.
7295 if (FD
->isBitField()) {
7296 Info
.FFDiag(BCE
->getBeginLoc(),
7297 diag::note_constexpr_bit_cast_unsupported_bitfield
);
7298 return std::nullopt
;
7301 uint64_t FieldOffsetBits
= Layout
.getFieldOffset(FieldIdx
);
7302 assert(FieldOffsetBits
% Info
.Ctx
.getCharWidth() == 0);
7304 CharUnits FieldOffset
=
7305 CharUnits::fromQuantity(FieldOffsetBits
/ Info
.Ctx
.getCharWidth()) +
7307 QualType FieldTy
= FD
->getType();
7308 std::optional
<APValue
> SubObj
= visitType(FieldTy
, FieldOffset
);
7310 return std::nullopt
;
7311 ResultVal
.getStructField(FieldIdx
) = *SubObj
;
7318 std::optional
<APValue
> visit(const EnumType
*Ty
, CharUnits Offset
) {
7319 QualType RepresentationType
= Ty
->getDecl()->getIntegerType();
7320 assert(!RepresentationType
.isNull() &&
7321 "enum forward decl should be caught by Sema");
7322 const auto *AsBuiltin
=
7323 RepresentationType
.getCanonicalType()->castAs
<BuiltinType
>();
7324 // Recurse into the underlying type. Treat std::byte transparently as
7326 return visit(AsBuiltin
, Offset
, /*EnumTy=*/Ty
);
7329 std::optional
<APValue
> visit(const ConstantArrayType
*Ty
, CharUnits Offset
) {
7330 size_t Size
= Ty
->getSize().getLimitedValue();
7331 CharUnits ElementWidth
= Info
.Ctx
.getTypeSizeInChars(Ty
->getElementType());
7333 APValue
ArrayValue(APValue::UninitArray(), Size
, Size
);
7334 for (size_t I
= 0; I
!= Size
; ++I
) {
7335 std::optional
<APValue
> ElementValue
=
7336 visitType(Ty
->getElementType(), Offset
+ I
* ElementWidth
);
7338 return std::nullopt
;
7339 ArrayValue
.getArrayInitializedElt(I
) = std::move(*ElementValue
);
7345 std::optional
<APValue
> visit(const VectorType
*VTy
, CharUnits Offset
) {
7346 QualType EltTy
= VTy
->getElementType();
7347 unsigned NElts
= VTy
->getNumElements();
7349 VTy
->isExtVectorBoolType() ? 1 : Info
.Ctx
.getTypeSize(EltTy
);
7351 if ((NElts
* EltSize
) % Info
.Ctx
.getCharWidth() != 0) {
7352 // The vector's size in bits is not a multiple of the target's byte size,
7353 // so its layout is unspecified. For now, we'll simply treat these cases
7354 // as unsupported (this should only be possible with OpenCL bool vectors
7355 // whose element count isn't a multiple of the byte size).
7356 Info
.FFDiag(BCE
->getBeginLoc(),
7357 diag::note_constexpr_bit_cast_invalid_vector
)
7358 << QualType(VTy
, 0) << EltSize
<< NElts
<< Info
.Ctx
.getCharWidth();
7359 return std::nullopt
;
7362 if (EltTy
->isRealFloatingType() && &Info
.Ctx
.getFloatTypeSemantics(EltTy
) ==
7363 &APFloat::x87DoubleExtended()) {
7364 // The layout for x86_fp80 vectors seems to be handled very inconsistently
7365 // by both clang and LLVM, so for now we won't allow bit_casts involving
7366 // it in a constexpr context.
7367 Info
.FFDiag(BCE
->getBeginLoc(),
7368 diag::note_constexpr_bit_cast_unsupported_type
)
7370 return std::nullopt
;
7373 SmallVector
<APValue
, 4> Elts
;
7374 Elts
.reserve(NElts
);
7375 if (VTy
->isExtVectorBoolType()) {
7376 // Special handling for OpenCL bool vectors:
7377 // Since these vectors are stored as packed bits, but we can't read
7378 // individual bits from the BitCastBuffer, we'll buffer all of the
7379 // elements together into an appropriately sized APInt and write them all
7380 // out at once. Because we don't accept vectors where NElts * EltSize
7381 // isn't a multiple of the char size, there will be no padding space, so
7382 // we don't have to worry about reading any padding data which didn't
7383 // actually need to be accessed.
7384 bool BigEndian
= Info
.Ctx
.getTargetInfo().isBigEndian();
7386 SmallVector
<uint8_t, 8> Bytes
;
7387 Bytes
.reserve(NElts
/ 8);
7388 if (!Buffer
.readObject(Offset
, CharUnits::fromQuantity(NElts
/ 8), Bytes
))
7389 return std::nullopt
;
7391 APSInt
SValInt(NElts
, true);
7392 llvm::LoadIntFromMemory(SValInt
, &*Bytes
.begin(), Bytes
.size());
7394 for (unsigned I
= 0; I
< NElts
; ++I
) {
7396 SValInt
.extractBits(1, (BigEndian
? NElts
- I
- 1 : I
) * EltSize
);
7398 APSInt(std::move(Elt
), !EltTy
->isSignedIntegerType()));
7401 // Iterate over each of the elements and read them from the buffer at
7402 // the appropriate offset.
7403 CharUnits EltSizeChars
= Info
.Ctx
.getTypeSizeInChars(EltTy
);
7404 for (unsigned I
= 0; I
< NElts
; ++I
) {
7405 std::optional
<APValue
> EltValue
=
7406 visitType(EltTy
, Offset
+ I
* EltSizeChars
);
7408 return std::nullopt
;
7409 Elts
.push_back(std::move(*EltValue
));
7413 return APValue(Elts
.data(), Elts
.size());
7416 std::optional
<APValue
> visit(const Type
*Ty
, CharUnits Offset
) {
7417 return unsupportedType(QualType(Ty
, 0));
7420 std::optional
<APValue
> visitType(QualType Ty
, CharUnits Offset
) {
7421 QualType Can
= Ty
.getCanonicalType();
7423 switch (Can
->getTypeClass()) {
7424 #define TYPE(Class, Base) \
7426 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7427 #define ABSTRACT_TYPE(Class, Base)
7428 #define NON_CANONICAL_TYPE(Class, Base) \
7430 llvm_unreachable("non-canonical type should be impossible!");
7431 #define DEPENDENT_TYPE(Class, Base) \
7434 "dependent types aren't supported in the constant evaluator!");
7435 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
7437 llvm_unreachable("either dependent or not canonical!");
7438 #include "clang/AST/TypeNodes.inc"
7440 llvm_unreachable("Unhandled Type::TypeClass");
7444 // Pull out a full value of type DstType.
7445 static std::optional
<APValue
> convert(EvalInfo
&Info
, BitCastBuffer
&Buffer
,
7446 const CastExpr
*BCE
) {
7447 BufferToAPValueConverter
Converter(Info
, Buffer
, BCE
);
7448 return Converter
.visitType(BCE
->getType(), CharUnits::fromQuantity(0));
7452 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc
,
7453 QualType Ty
, EvalInfo
*Info
,
7454 const ASTContext
&Ctx
,
7455 bool CheckingDest
) {
7456 Ty
= Ty
.getCanonicalType();
7458 auto diag
= [&](int Reason
) {
7460 Info
->FFDiag(Loc
, diag::note_constexpr_bit_cast_invalid_type
)
7461 << CheckingDest
<< (Reason
== 4) << Reason
;
7464 auto note
= [&](int Construct
, QualType NoteTy
, SourceLocation NoteLoc
) {
7466 Info
->Note(NoteLoc
, diag::note_constexpr_bit_cast_invalid_subtype
)
7467 << NoteTy
<< Construct
<< Ty
;
7471 if (Ty
->isUnionType())
7473 if (Ty
->isPointerType())
7475 if (Ty
->isMemberPointerType())
7477 if (Ty
.isVolatileQualified())
7480 if (RecordDecl
*Record
= Ty
->getAsRecordDecl()) {
7481 if (auto *CXXRD
= dyn_cast
<CXXRecordDecl
>(Record
)) {
7482 for (CXXBaseSpecifier
&BS
: CXXRD
->bases())
7483 if (!checkBitCastConstexprEligibilityType(Loc
, BS
.getType(), Info
, Ctx
,
7485 return note(1, BS
.getType(), BS
.getBeginLoc());
7487 for (FieldDecl
*FD
: Record
->fields()) {
7488 if (FD
->getType()->isReferenceType())
7490 if (!checkBitCastConstexprEligibilityType(Loc
, FD
->getType(), Info
, Ctx
,
7492 return note(0, FD
->getType(), FD
->getBeginLoc());
7496 if (Ty
->isArrayType() &&
7497 !checkBitCastConstexprEligibilityType(Loc
, Ctx
.getBaseElementType(Ty
),
7498 Info
, Ctx
, CheckingDest
))
7504 static bool checkBitCastConstexprEligibility(EvalInfo
*Info
,
7505 const ASTContext
&Ctx
,
7506 const CastExpr
*BCE
) {
7507 bool DestOK
= checkBitCastConstexprEligibilityType(
7508 BCE
->getBeginLoc(), BCE
->getType(), Info
, Ctx
, true);
7509 bool SourceOK
= DestOK
&& checkBitCastConstexprEligibilityType(
7511 BCE
->getSubExpr()->getType(), Info
, Ctx
, false);
7515 static bool handleRValueToRValueBitCast(EvalInfo
&Info
, APValue
&DestValue
,
7516 const APValue
&SourceRValue
,
7517 const CastExpr
*BCE
) {
7518 assert(CHAR_BIT
== 8 && Info
.Ctx
.getTargetInfo().getCharWidth() == 8 &&
7519 "no host or target supports non 8-bit chars");
7521 if (!checkBitCastConstexprEligibility(&Info
, Info
.Ctx
, BCE
))
7524 // Read out SourceValue into a char buffer.
7525 std::optional
<BitCastBuffer
> Buffer
=
7526 APValueToBufferConverter::convert(Info
, SourceRValue
, BCE
);
7530 // Write out the buffer into a new APValue.
7531 std::optional
<APValue
> MaybeDestValue
=
7532 BufferToAPValueConverter::convert(Info
, *Buffer
, BCE
);
7533 if (!MaybeDestValue
)
7536 DestValue
= std::move(*MaybeDestValue
);
7540 static bool handleLValueToRValueBitCast(EvalInfo
&Info
, APValue
&DestValue
,
7541 APValue
&SourceValue
,
7542 const CastExpr
*BCE
) {
7543 assert(CHAR_BIT
== 8 && Info
.Ctx
.getTargetInfo().getCharWidth() == 8 &&
7544 "no host or target supports non 8-bit chars");
7545 assert(SourceValue
.isLValue() &&
7546 "LValueToRValueBitcast requires an lvalue operand!");
7548 LValue SourceLValue
;
7549 APValue SourceRValue
;
7550 SourceLValue
.setFrom(Info
.Ctx
, SourceValue
);
7551 if (!handleLValueToRValueConversion(
7552 Info
, BCE
, BCE
->getSubExpr()->getType().withConst(), SourceLValue
,
7553 SourceRValue
, /*WantObjectRepresentation=*/true))
7556 return handleRValueToRValueBitCast(Info
, DestValue
, SourceRValue
, BCE
);
7559 template <class Derived
>
7560 class ExprEvaluatorBase
7561 : public ConstStmtVisitor
<Derived
, bool> {
7563 Derived
&getDerived() { return static_cast<Derived
&>(*this); }
7564 bool DerivedSuccess(const APValue
&V
, const Expr
*E
) {
7565 return getDerived().Success(V
, E
);
7567 bool DerivedZeroInitialization(const Expr
*E
) {
7568 return getDerived().ZeroInitialization(E
);
7571 // Check whether a conditional operator with a non-constant condition is a
7572 // potential constant expression. If neither arm is a potential constant
7573 // expression, then the conditional operator is not either.
7574 template<typename ConditionalOperator
>
7575 void CheckPotentialConstantConditional(const ConditionalOperator
*E
) {
7576 assert(Info
.checkingPotentialConstantExpression());
7578 // Speculatively evaluate both arms.
7579 SmallVector
<PartialDiagnosticAt
, 8> Diag
;
7581 SpeculativeEvaluationRAII
Speculate(Info
, &Diag
);
7582 StmtVisitorTy::Visit(E
->getFalseExpr());
7588 SpeculativeEvaluationRAII
Speculate(Info
, &Diag
);
7590 StmtVisitorTy::Visit(E
->getTrueExpr());
7595 Error(E
, diag::note_constexpr_conditional_never_const
);
7599 template<typename ConditionalOperator
>
7600 bool HandleConditionalOperator(const ConditionalOperator
*E
) {
7602 if (!EvaluateAsBooleanCondition(E
->getCond(), BoolResult
, Info
)) {
7603 if (Info
.checkingPotentialConstantExpression() && Info
.noteFailure()) {
7604 CheckPotentialConstantConditional(E
);
7607 if (Info
.noteFailure()) {
7608 StmtVisitorTy::Visit(E
->getTrueExpr());
7609 StmtVisitorTy::Visit(E
->getFalseExpr());
7614 Expr
*EvalExpr
= BoolResult
? E
->getTrueExpr() : E
->getFalseExpr();
7615 return StmtVisitorTy::Visit(EvalExpr
);
7620 typedef ConstStmtVisitor
<Derived
, bool> StmtVisitorTy
;
7621 typedef ExprEvaluatorBase ExprEvaluatorBaseTy
;
7623 OptionalDiagnostic
CCEDiag(const Expr
*E
, diag::kind D
) {
7624 return Info
.CCEDiag(E
, D
);
7627 bool ZeroInitialization(const Expr
*E
) { return Error(E
); }
7629 bool IsConstantEvaluatedBuiltinCall(const CallExpr
*E
) {
7630 unsigned BuiltinOp
= E
->getBuiltinCallee();
7631 return BuiltinOp
!= 0 &&
7632 Info
.Ctx
.BuiltinInfo
.isConstantEvaluated(BuiltinOp
);
7636 ExprEvaluatorBase(EvalInfo
&Info
) : Info(Info
) {}
7638 EvalInfo
&getEvalInfo() { return Info
; }
7640 /// Report an evaluation error. This should only be called when an error is
7641 /// first discovered. When propagating an error, just return false.
7642 bool Error(const Expr
*E
, diag::kind D
) {
7643 Info
.FFDiag(E
, D
) << E
->getSourceRange();
7646 bool Error(const Expr
*E
) {
7647 return Error(E
, diag::note_invalid_subexpr_in_const_expr
);
7650 bool VisitStmt(const Stmt
*) {
7651 llvm_unreachable("Expression evaluator should not be called on stmts");
7653 bool VisitExpr(const Expr
*E
) {
7657 bool VisitPredefinedExpr(const PredefinedExpr
*E
) {
7658 return StmtVisitorTy::Visit(E
->getFunctionName());
7660 bool VisitConstantExpr(const ConstantExpr
*E
) {
7661 if (E
->hasAPValueResult())
7662 return DerivedSuccess(E
->getAPValueResult(), E
);
7664 return StmtVisitorTy::Visit(E
->getSubExpr());
7667 bool VisitParenExpr(const ParenExpr
*E
)
7668 { return StmtVisitorTy::Visit(E
->getSubExpr()); }
7669 bool VisitUnaryExtension(const UnaryOperator
*E
)
7670 { return StmtVisitorTy::Visit(E
->getSubExpr()); }
7671 bool VisitUnaryPlus(const UnaryOperator
*E
)
7672 { return StmtVisitorTy::Visit(E
->getSubExpr()); }
7673 bool VisitChooseExpr(const ChooseExpr
*E
)
7674 { return StmtVisitorTy::Visit(E
->getChosenSubExpr()); }
7675 bool VisitGenericSelectionExpr(const GenericSelectionExpr
*E
)
7676 { return StmtVisitorTy::Visit(E
->getResultExpr()); }
7677 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr
*E
)
7678 { return StmtVisitorTy::Visit(E
->getReplacement()); }
7679 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr
*E
) {
7680 TempVersionRAII
RAII(*Info
.CurrentCall
);
7681 SourceLocExprScopeGuard
Guard(E
, Info
.CurrentCall
->CurSourceLocExprScope
);
7682 return StmtVisitorTy::Visit(E
->getExpr());
7684 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr
*E
) {
7685 TempVersionRAII
RAII(*Info
.CurrentCall
);
7686 // The initializer may not have been parsed yet, or might be erroneous.
7689 SourceLocExprScopeGuard
Guard(E
, Info
.CurrentCall
->CurSourceLocExprScope
);
7690 return StmtVisitorTy::Visit(E
->getExpr());
7693 bool VisitExprWithCleanups(const ExprWithCleanups
*E
) {
7694 FullExpressionRAII
Scope(Info
);
7695 return StmtVisitorTy::Visit(E
->getSubExpr()) && Scope
.destroy();
7698 // Temporaries are registered when created, so we don't care about
7699 // CXXBindTemporaryExpr.
7700 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr
*E
) {
7701 return StmtVisitorTy::Visit(E
->getSubExpr());
7704 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr
*E
) {
7705 CCEDiag(E
, diag::note_constexpr_invalid_cast
) << 0;
7706 return static_cast<Derived
*>(this)->VisitCastExpr(E
);
7708 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr
*E
) {
7709 if (!Info
.Ctx
.getLangOpts().CPlusPlus20
)
7710 CCEDiag(E
, diag::note_constexpr_invalid_cast
) << 1;
7711 return static_cast<Derived
*>(this)->VisitCastExpr(E
);
7713 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr
*E
) {
7714 return static_cast<Derived
*>(this)->VisitCastExpr(E
);
7717 bool VisitBinaryOperator(const BinaryOperator
*E
) {
7718 switch (E
->getOpcode()) {
7723 VisitIgnoredValue(E
->getLHS());
7724 return StmtVisitorTy::Visit(E
->getRHS());
7729 if (!HandleMemberPointerAccess(Info
, E
, Obj
))
7732 if (!handleLValueToRValueConversion(Info
, E
, E
->getType(), Obj
, Result
))
7734 return DerivedSuccess(Result
, E
);
7739 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator
*E
) {
7740 return StmtVisitorTy::Visit(E
->getSemanticForm());
7743 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator
*E
) {
7744 // Evaluate and cache the common expression. We treat it as a temporary,
7745 // even though it's not quite the same thing.
7747 if (!Evaluate(Info
.CurrentCall
->createTemporary(
7748 E
->getOpaqueValue(),
7749 getStorageType(Info
.Ctx
, E
->getOpaqueValue()),
7750 ScopeKind::FullExpression
, CommonLV
),
7751 Info
, E
->getCommon()))
7754 return HandleConditionalOperator(E
);
7757 bool VisitConditionalOperator(const ConditionalOperator
*E
) {
7758 bool IsBcpCall
= false;
7759 // If the condition (ignoring parens) is a __builtin_constant_p call,
7760 // the result is a constant expression if it can be folded without
7761 // side-effects. This is an important GNU extension. See GCC PR38377
7763 if (const CallExpr
*CallCE
=
7764 dyn_cast
<CallExpr
>(E
->getCond()->IgnoreParenCasts()))
7765 if (CallCE
->getBuiltinCallee() == Builtin::BI__builtin_constant_p
)
7768 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7769 // constant expression; we can't check whether it's potentially foldable.
7770 // FIXME: We should instead treat __builtin_constant_p as non-constant if
7771 // it would return 'false' in this mode.
7772 if (Info
.checkingPotentialConstantExpression() && IsBcpCall
)
7775 FoldConstant
Fold(Info
, IsBcpCall
);
7776 if (!HandleConditionalOperator(E
)) {
7777 Fold
.keepDiagnostics();
7784 bool VisitOpaqueValueExpr(const OpaqueValueExpr
*E
) {
7785 if (APValue
*Value
= Info
.CurrentCall
->getCurrentTemporary(E
);
7786 Value
&& !Value
->isAbsent())
7787 return DerivedSuccess(*Value
, E
);
7789 const Expr
*Source
= E
->getSourceExpr();
7793 assert(0 && "OpaqueValueExpr recursively refers to itself");
7796 return StmtVisitorTy::Visit(Source
);
7799 bool VisitPseudoObjectExpr(const PseudoObjectExpr
*E
) {
7800 for (const Expr
*SemE
: E
->semantics()) {
7801 if (auto *OVE
= dyn_cast
<OpaqueValueExpr
>(SemE
)) {
7802 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7803 // result expression: there could be two different LValues that would
7804 // refer to the same object in that case, and we can't model that.
7805 if (SemE
== E
->getResultExpr())
7808 // Unique OVEs get evaluated if and when we encounter them when
7809 // emitting the rest of the semantic form, rather than eagerly.
7810 if (OVE
->isUnique())
7814 if (!Evaluate(Info
.CurrentCall
->createTemporary(
7815 OVE
, getStorageType(Info
.Ctx
, OVE
),
7816 ScopeKind::FullExpression
, LV
),
7817 Info
, OVE
->getSourceExpr()))
7819 } else if (SemE
== E
->getResultExpr()) {
7820 if (!StmtVisitorTy::Visit(SemE
))
7823 if (!EvaluateIgnoredValue(Info
, SemE
))
7830 bool VisitCallExpr(const CallExpr
*E
) {
7832 if (!handleCallExpr(E
, Result
, nullptr))
7834 return DerivedSuccess(Result
, E
);
7837 bool handleCallExpr(const CallExpr
*E
, APValue
&Result
,
7838 const LValue
*ResultSlot
) {
7839 CallScopeRAII
CallScope(Info
);
7841 const Expr
*Callee
= E
->getCallee()->IgnoreParens();
7842 QualType CalleeType
= Callee
->getType();
7844 const FunctionDecl
*FD
= nullptr;
7845 LValue
*This
= nullptr, ThisVal
;
7846 auto Args
= llvm::ArrayRef(E
->getArgs(), E
->getNumArgs());
7847 bool HasQualifier
= false;
7851 // Extract function decl and 'this' pointer from the callee.
7852 if (CalleeType
->isSpecificBuiltinType(BuiltinType::BoundMember
)) {
7853 const CXXMethodDecl
*Member
= nullptr;
7854 if (const MemberExpr
*ME
= dyn_cast
<MemberExpr
>(Callee
)) {
7855 // Explicit bound member calls, such as x.f() or p->g();
7856 if (!EvaluateObjectArgument(Info
, ME
->getBase(), ThisVal
))
7858 Member
= dyn_cast
<CXXMethodDecl
>(ME
->getMemberDecl());
7860 return Error(Callee
);
7862 HasQualifier
= ME
->hasQualifier();
7863 } else if (const BinaryOperator
*BE
= dyn_cast
<BinaryOperator
>(Callee
)) {
7864 // Indirect bound member calls ('.*' or '->*').
7865 const ValueDecl
*D
=
7866 HandleMemberPointerAccess(Info
, BE
, ThisVal
, false);
7869 Member
= dyn_cast
<CXXMethodDecl
>(D
);
7871 return Error(Callee
);
7873 } else if (const auto *PDE
= dyn_cast
<CXXPseudoDestructorExpr
>(Callee
)) {
7874 if (!Info
.getLangOpts().CPlusPlus20
)
7875 Info
.CCEDiag(PDE
, diag::note_constexpr_pseudo_destructor
);
7876 return EvaluateObjectArgument(Info
, PDE
->getBase(), ThisVal
) &&
7877 HandleDestruction(Info
, PDE
, ThisVal
, PDE
->getDestroyedType());
7879 return Error(Callee
);
7881 } else if (CalleeType
->isFunctionPointerType()) {
7883 if (!EvaluatePointer(Callee
, CalleeLV
, Info
))
7886 if (!CalleeLV
.getLValueOffset().isZero())
7887 return Error(Callee
);
7888 if (CalleeLV
.isNullPointer()) {
7889 Info
.FFDiag(Callee
, diag::note_constexpr_null_callee
)
7890 << const_cast<Expr
*>(Callee
);
7893 FD
= dyn_cast_or_null
<FunctionDecl
>(
7894 CalleeLV
.getLValueBase().dyn_cast
<const ValueDecl
*>());
7896 return Error(Callee
);
7897 // Don't call function pointers which have been cast to some other type.
7898 // Per DR (no number yet), the caller and callee can differ in noexcept.
7899 if (!Info
.Ctx
.hasSameFunctionTypeIgnoringExceptionSpec(
7900 CalleeType
->getPointeeType(), FD
->getType())) {
7904 // For an (overloaded) assignment expression, evaluate the RHS before the
7906 auto *OCE
= dyn_cast
<CXXOperatorCallExpr
>(E
);
7907 if (OCE
&& OCE
->isAssignmentOp()) {
7908 assert(Args
.size() == 2 && "wrong number of arguments in assignment");
7909 Call
= Info
.CurrentCall
->createCall(FD
);
7910 bool HasThis
= false;
7911 if (const auto *MD
= dyn_cast
<CXXMethodDecl
>(FD
))
7912 HasThis
= MD
->isImplicitObjectMemberFunction();
7913 if (!EvaluateArgs(HasThis
? Args
.slice(1) : Args
, Call
, Info
, FD
,
7914 /*RightToLeft=*/true))
7918 // Overloaded operator calls to member functions are represented as normal
7919 // calls with '*this' as the first argument.
7920 const CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(FD
);
7921 if (MD
&& MD
->isImplicitObjectMemberFunction()) {
7922 // FIXME: When selecting an implicit conversion for an overloaded
7923 // operator delete, we sometimes try to evaluate calls to conversion
7924 // operators without a 'this' parameter!
7928 if (!EvaluateObjectArgument(Info
, Args
[0], ThisVal
))
7932 // If this is syntactically a simple assignment using a trivial
7933 // assignment operator, start the lifetimes of union members as needed,
7934 // per C++20 [class.union]5.
7935 if (Info
.getLangOpts().CPlusPlus20
&& OCE
&&
7936 OCE
->getOperator() == OO_Equal
&& MD
->isTrivial() &&
7937 !MaybeHandleUnionActiveMemberChange(Info
, Args
[0], ThisVal
))
7940 Args
= Args
.slice(1);
7941 } else if (MD
&& MD
->isLambdaStaticInvoker()) {
7942 // Map the static invoker for the lambda back to the call operator.
7943 // Conveniently, we don't have to slice out the 'this' argument (as is
7944 // being done for the non-static case), since a static member function
7945 // doesn't have an implicit argument passed in.
7946 const CXXRecordDecl
*ClosureClass
= MD
->getParent();
7948 ClosureClass
->captures_begin() == ClosureClass
->captures_end() &&
7949 "Number of captures must be zero for conversion to function-ptr");
7951 const CXXMethodDecl
*LambdaCallOp
=
7952 ClosureClass
->getLambdaCallOperator();
7954 // Set 'FD', the function that will be called below, to the call
7955 // operator. If the closure object represents a generic lambda, find
7956 // the corresponding specialization of the call operator.
7958 if (ClosureClass
->isGenericLambda()) {
7959 assert(MD
->isFunctionTemplateSpecialization() &&
7960 "A generic lambda's static-invoker function must be a "
7961 "template specialization");
7962 const TemplateArgumentList
*TAL
= MD
->getTemplateSpecializationArgs();
7963 FunctionTemplateDecl
*CallOpTemplate
=
7964 LambdaCallOp
->getDescribedFunctionTemplate();
7965 void *InsertPos
= nullptr;
7966 FunctionDecl
*CorrespondingCallOpSpecialization
=
7967 CallOpTemplate
->findSpecialization(TAL
->asArray(), InsertPos
);
7968 assert(CorrespondingCallOpSpecialization
&&
7969 "We must always have a function call operator specialization "
7970 "that corresponds to our static invoker specialization");
7971 FD
= cast
<CXXMethodDecl
>(CorrespondingCallOpSpecialization
);
7974 } else if (FD
->isReplaceableGlobalAllocationFunction()) {
7975 if (FD
->getDeclName().getCXXOverloadedOperator() == OO_New
||
7976 FD
->getDeclName().getCXXOverloadedOperator() == OO_Array_New
) {
7978 if (!HandleOperatorNewCall(Info
, E
, Ptr
))
7980 Ptr
.moveInto(Result
);
7981 return CallScope
.destroy();
7983 return HandleOperatorDeleteCall(Info
, E
) && CallScope
.destroy();
7989 // Evaluate the arguments now if we've not already done so.
7991 Call
= Info
.CurrentCall
->createCall(FD
);
7992 if (!EvaluateArgs(Args
, Call
, Info
, FD
))
7996 SmallVector
<QualType
, 4> CovariantAdjustmentPath
;
7998 auto *NamedMember
= dyn_cast
<CXXMethodDecl
>(FD
);
7999 if (NamedMember
&& NamedMember
->isVirtual() && !HasQualifier
) {
8000 // Perform virtual dispatch, if necessary.
8001 FD
= HandleVirtualDispatch(Info
, E
, *This
, NamedMember
,
8002 CovariantAdjustmentPath
);
8005 } else if (NamedMember
&& NamedMember
->isImplicitObjectMemberFunction()) {
8006 // Check that the 'this' pointer points to an object of the right type.
8007 // FIXME: If this is an assignment operator call, we may need to change
8008 // the active union member before we check this.
8009 if (!checkNonVirtualMemberCallThisPointer(Info
, E
, *This
, NamedMember
))
8014 // Destructor calls are different enough that they have their own codepath.
8015 if (auto *DD
= dyn_cast
<CXXDestructorDecl
>(FD
)) {
8016 assert(This
&& "no 'this' pointer for destructor call");
8017 return HandleDestruction(Info
, E
, *This
,
8018 Info
.Ctx
.getRecordType(DD
->getParent())) &&
8019 CallScope
.destroy();
8022 const FunctionDecl
*Definition
= nullptr;
8023 Stmt
*Body
= FD
->getBody(Definition
);
8025 if (!CheckConstexprFunction(Info
, E
->getExprLoc(), FD
, Definition
, Body
) ||
8026 !HandleFunctionCall(E
->getExprLoc(), Definition
, This
, E
, Args
, Call
,
8027 Body
, Info
, Result
, ResultSlot
))
8030 if (!CovariantAdjustmentPath
.empty() &&
8031 !HandleCovariantReturnAdjustment(Info
, E
, Result
,
8032 CovariantAdjustmentPath
))
8035 return CallScope
.destroy();
8038 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr
*E
) {
8039 return StmtVisitorTy::Visit(E
->getInitializer());
8041 bool VisitInitListExpr(const InitListExpr
*E
) {
8042 if (E
->getNumInits() == 0)
8043 return DerivedZeroInitialization(E
);
8044 if (E
->getNumInits() == 1)
8045 return StmtVisitorTy::Visit(E
->getInit(0));
8048 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr
*E
) {
8049 return DerivedZeroInitialization(E
);
8051 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr
*E
) {
8052 return DerivedZeroInitialization(E
);
8054 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr
*E
) {
8055 return DerivedZeroInitialization(E
);
8058 /// A member expression where the object is a prvalue is itself a prvalue.
8059 bool VisitMemberExpr(const MemberExpr
*E
) {
8060 assert(!Info
.Ctx
.getLangOpts().CPlusPlus11
&&
8061 "missing temporary materialization conversion");
8062 assert(!E
->isArrow() && "missing call to bound member function?");
8065 if (!Evaluate(Val
, Info
, E
->getBase()))
8068 QualType BaseTy
= E
->getBase()->getType();
8070 const FieldDecl
*FD
= dyn_cast
<FieldDecl
>(E
->getMemberDecl());
8071 if (!FD
) return Error(E
);
8072 assert(!FD
->getType()->isReferenceType() && "prvalue reference?");
8073 assert(BaseTy
->castAs
<RecordType
>()->getDecl()->getCanonicalDecl() ==
8074 FD
->getParent()->getCanonicalDecl() && "record / field mismatch");
8076 // Note: there is no lvalue base here. But this case should only ever
8077 // happen in C or in C++98, where we cannot be evaluating a constexpr
8078 // constructor, which is the only case the base matters.
8079 CompleteObject
Obj(APValue::LValueBase(), &Val
, BaseTy
);
8080 SubobjectDesignator
Designator(BaseTy
);
8081 Designator
.addDeclUnchecked(FD
);
8084 return extractSubobject(Info
, E
, Obj
, Designator
, Result
) &&
8085 DerivedSuccess(Result
, E
);
8088 bool VisitExtVectorElementExpr(const ExtVectorElementExpr
*E
) {
8090 if (!Evaluate(Val
, Info
, E
->getBase()))
8093 if (Val
.isVector()) {
8094 SmallVector
<uint32_t, 4> Indices
;
8095 E
->getEncodedElementAccess(Indices
);
8096 if (Indices
.size() == 1) {
8098 return DerivedSuccess(Val
.getVectorElt(Indices
[0]), E
);
8100 // Construct new APValue vector.
8101 SmallVector
<APValue
, 4> Elts
;
8102 for (unsigned I
= 0; I
< Indices
.size(); ++I
) {
8103 Elts
.push_back(Val
.getVectorElt(Indices
[I
]));
8105 APValue
VecResult(Elts
.data(), Indices
.size());
8106 return DerivedSuccess(VecResult
, E
);
8113 bool VisitCastExpr(const CastExpr
*E
) {
8114 switch (E
->getCastKind()) {
8118 case CK_AtomicToNonAtomic
: {
8120 // This does not need to be done in place even for class/array types:
8121 // atomic-to-non-atomic conversion implies copying the object
8123 if (!Evaluate(AtomicVal
, Info
, E
->getSubExpr()))
8125 return DerivedSuccess(AtomicVal
, E
);
8129 case CK_UserDefinedConversion
:
8130 return StmtVisitorTy::Visit(E
->getSubExpr());
8132 case CK_LValueToRValue
: {
8134 if (!EvaluateLValue(E
->getSubExpr(), LVal
, Info
))
8137 // Note, we use the subexpression's type in order to retain cv-qualifiers.
8138 if (!handleLValueToRValueConversion(Info
, E
, E
->getSubExpr()->getType(),
8141 return DerivedSuccess(RVal
, E
);
8143 case CK_LValueToRValueBitCast
: {
8144 APValue DestValue
, SourceValue
;
8145 if (!Evaluate(SourceValue
, Info
, E
->getSubExpr()))
8147 if (!handleLValueToRValueBitCast(Info
, DestValue
, SourceValue
, E
))
8149 return DerivedSuccess(DestValue
, E
);
8152 case CK_AddressSpaceConversion
: {
8154 if (!Evaluate(Value
, Info
, E
->getSubExpr()))
8156 return DerivedSuccess(Value
, E
);
8163 bool VisitUnaryPostInc(const UnaryOperator
*UO
) {
8164 return VisitUnaryPostIncDec(UO
);
8166 bool VisitUnaryPostDec(const UnaryOperator
*UO
) {
8167 return VisitUnaryPostIncDec(UO
);
8169 bool VisitUnaryPostIncDec(const UnaryOperator
*UO
) {
8170 if (!Info
.getLangOpts().CPlusPlus14
&& !Info
.keepEvaluatingAfterFailure())
8174 if (!EvaluateLValue(UO
->getSubExpr(), LVal
, Info
))
8177 if (!handleIncDec(this->Info
, UO
, LVal
, UO
->getSubExpr()->getType(),
8178 UO
->isIncrementOp(), &RVal
))
8180 return DerivedSuccess(RVal
, UO
);
8183 bool VisitStmtExpr(const StmtExpr
*E
) {
8184 // We will have checked the full-expressions inside the statement expression
8185 // when they were completed, and don't need to check them again now.
8186 llvm::SaveAndRestore
NotCheckingForUB(Info
.CheckingForUndefinedBehavior
,
8189 const CompoundStmt
*CS
= E
->getSubStmt();
8190 if (CS
->body_empty())
8193 BlockScopeRAII
Scope(Info
);
8194 for (CompoundStmt::const_body_iterator BI
= CS
->body_begin(),
8195 BE
= CS
->body_end();
8198 const Expr
*FinalExpr
= dyn_cast
<Expr
>(*BI
);
8200 Info
.FFDiag((*BI
)->getBeginLoc(),
8201 diag::note_constexpr_stmt_expr_unsupported
);
8204 return this->Visit(FinalExpr
) && Scope
.destroy();
8207 APValue ReturnValue
;
8208 StmtResult Result
= { ReturnValue
, nullptr };
8209 EvalStmtResult ESR
= EvaluateStmt(Result
, Info
, *BI
);
8210 if (ESR
!= ESR_Succeeded
) {
8211 // FIXME: If the statement-expression terminated due to 'return',
8212 // 'break', or 'continue', it would be nice to propagate that to
8213 // the outer statement evaluation rather than bailing out.
8214 if (ESR
!= ESR_Failed
)
8215 Info
.FFDiag((*BI
)->getBeginLoc(),
8216 diag::note_constexpr_stmt_expr_unsupported
);
8221 llvm_unreachable("Return from function from the loop above.");
8224 /// Visit a value which is evaluated, but whose value is ignored.
8225 void VisitIgnoredValue(const Expr
*E
) {
8226 EvaluateIgnoredValue(Info
, E
);
8229 /// Potentially visit a MemberExpr's base expression.
8230 void VisitIgnoredBaseExpression(const Expr
*E
) {
8231 // While MSVC doesn't evaluate the base expression, it does diagnose the
8232 // presence of side-effecting behavior.
8233 if (Info
.getLangOpts().MSVCCompat
&& !E
->HasSideEffects(Info
.Ctx
))
8235 VisitIgnoredValue(E
);
8241 //===----------------------------------------------------------------------===//
8242 // Common base class for lvalue and temporary evaluation.
8243 //===----------------------------------------------------------------------===//
8245 template<class Derived
>
8246 class LValueExprEvaluatorBase
8247 : public ExprEvaluatorBase
<Derived
> {
8251 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy
;
8252 typedef ExprEvaluatorBase
<Derived
> ExprEvaluatorBaseTy
;
8254 bool Success(APValue::LValueBase B
) {
8259 bool evaluatePointer(const Expr
*E
, LValue
&Result
) {
8260 return EvaluatePointer(E
, Result
, this->Info
, InvalidBaseOK
);
8264 LValueExprEvaluatorBase(EvalInfo
&Info
, LValue
&Result
, bool InvalidBaseOK
)
8265 : ExprEvaluatorBaseTy(Info
), Result(Result
),
8266 InvalidBaseOK(InvalidBaseOK
) {}
8268 bool Success(const APValue
&V
, const Expr
*E
) {
8269 Result
.setFrom(this->Info
.Ctx
, V
);
8273 bool VisitMemberExpr(const MemberExpr
*E
) {
8274 // Handle non-static data members.
8278 EvalOK
= evaluatePointer(E
->getBase(), Result
);
8279 BaseTy
= E
->getBase()->getType()->castAs
<PointerType
>()->getPointeeType();
8280 } else if (E
->getBase()->isPRValue()) {
8281 assert(E
->getBase()->getType()->isRecordType());
8282 EvalOK
= EvaluateTemporary(E
->getBase(), Result
, this->Info
);
8283 BaseTy
= E
->getBase()->getType();
8285 EvalOK
= this->Visit(E
->getBase());
8286 BaseTy
= E
->getBase()->getType();
8291 Result
.setInvalid(E
);
8295 const ValueDecl
*MD
= E
->getMemberDecl();
8296 if (const FieldDecl
*FD
= dyn_cast
<FieldDecl
>(E
->getMemberDecl())) {
8297 assert(BaseTy
->castAs
<RecordType
>()->getDecl()->getCanonicalDecl() ==
8298 FD
->getParent()->getCanonicalDecl() && "record / field mismatch");
8300 if (!HandleLValueMember(this->Info
, E
, Result
, FD
))
8302 } else if (const IndirectFieldDecl
*IFD
= dyn_cast
<IndirectFieldDecl
>(MD
)) {
8303 if (!HandleLValueIndirectMember(this->Info
, E
, Result
, IFD
))
8306 return this->Error(E
);
8308 if (MD
->getType()->isReferenceType()) {
8310 if (!handleLValueToRValueConversion(this->Info
, E
, MD
->getType(), Result
,
8313 return Success(RefValue
, E
);
8318 bool VisitBinaryOperator(const BinaryOperator
*E
) {
8319 switch (E
->getOpcode()) {
8321 return ExprEvaluatorBaseTy::VisitBinaryOperator(E
);
8325 return HandleMemberPointerAccess(this->Info
, E
, Result
);
8329 bool VisitCastExpr(const CastExpr
*E
) {
8330 switch (E
->getCastKind()) {
8332 return ExprEvaluatorBaseTy::VisitCastExpr(E
);
8334 case CK_DerivedToBase
:
8335 case CK_UncheckedDerivedToBase
:
8336 if (!this->Visit(E
->getSubExpr()))
8339 // Now figure out the necessary offset to add to the base LV to get from
8340 // the derived class to the base class.
8341 return HandleLValueBasePath(this->Info
, E
, E
->getSubExpr()->getType(),
8348 //===----------------------------------------------------------------------===//
8349 // LValue Evaluation
8351 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8352 // function designators (in C), decl references to void objects (in C), and
8353 // temporaries (if building with -Wno-address-of-temporary).
8355 // LValue evaluation produces values comprising a base expression of one of the
8361 // * CompoundLiteralExpr in C (and in global scope in C++)
8364 // * ObjCStringLiteralExpr
8368 // * CallExpr for a MakeStringConstant builtin
8369 // - typeid(T) expressions, as TypeInfoLValues
8370 // - Locals and temporaries
8371 // * MaterializeTemporaryExpr
8372 // * Any Expr, with a CallIndex indicating the function in which the temporary
8373 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
8374 // from the AST (FIXME).
8375 // * A MaterializeTemporaryExpr that has static storage duration, with no
8376 // CallIndex, for a lifetime-extended temporary.
8377 // * The ConstantExpr that is currently being evaluated during evaluation of an
8378 // immediate invocation.
8379 // plus an offset in bytes.
8380 //===----------------------------------------------------------------------===//
8382 class LValueExprEvaluator
8383 : public LValueExprEvaluatorBase
<LValueExprEvaluator
> {
8385 LValueExprEvaluator(EvalInfo
&Info
, LValue
&Result
, bool InvalidBaseOK
) :
8386 LValueExprEvaluatorBaseTy(Info
, Result
, InvalidBaseOK
) {}
8388 bool VisitVarDecl(const Expr
*E
, const VarDecl
*VD
);
8389 bool VisitUnaryPreIncDec(const UnaryOperator
*UO
);
8391 bool VisitCallExpr(const CallExpr
*E
);
8392 bool VisitDeclRefExpr(const DeclRefExpr
*E
);
8393 bool VisitPredefinedExpr(const PredefinedExpr
*E
) { return Success(E
); }
8394 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr
*E
);
8395 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr
*E
);
8396 bool VisitMemberExpr(const MemberExpr
*E
);
8397 bool VisitStringLiteral(const StringLiteral
*E
) { return Success(E
); }
8398 bool VisitObjCEncodeExpr(const ObjCEncodeExpr
*E
) { return Success(E
); }
8399 bool VisitCXXTypeidExpr(const CXXTypeidExpr
*E
);
8400 bool VisitCXXUuidofExpr(const CXXUuidofExpr
*E
);
8401 bool VisitArraySubscriptExpr(const ArraySubscriptExpr
*E
);
8402 bool VisitUnaryDeref(const UnaryOperator
*E
);
8403 bool VisitUnaryReal(const UnaryOperator
*E
);
8404 bool VisitUnaryImag(const UnaryOperator
*E
);
8405 bool VisitUnaryPreInc(const UnaryOperator
*UO
) {
8406 return VisitUnaryPreIncDec(UO
);
8408 bool VisitUnaryPreDec(const UnaryOperator
*UO
) {
8409 return VisitUnaryPreIncDec(UO
);
8411 bool VisitBinAssign(const BinaryOperator
*BO
);
8412 bool VisitCompoundAssignOperator(const CompoundAssignOperator
*CAO
);
8414 bool VisitCastExpr(const CastExpr
*E
) {
8415 switch (E
->getCastKind()) {
8417 return LValueExprEvaluatorBaseTy::VisitCastExpr(E
);
8419 case CK_LValueBitCast
:
8420 this->CCEDiag(E
, diag::note_constexpr_invalid_cast
)
8421 << 2 << Info
.Ctx
.getLangOpts().CPlusPlus
;
8422 if (!Visit(E
->getSubExpr()))
8424 Result
.Designator
.setInvalid();
8427 case CK_BaseToDerived
:
8428 if (!Visit(E
->getSubExpr()))
8430 return HandleBaseToDerivedCast(Info
, E
, Result
);
8433 if (!Visit(E
->getSubExpr()))
8435 return HandleDynamicCast(Info
, cast
<ExplicitCastExpr
>(E
), Result
);
8439 } // end anonymous namespace
8441 /// Evaluate an expression as an lvalue. This can be legitimately called on
8442 /// expressions which are not glvalues, in three cases:
8443 /// * function designators in C, and
8444 /// * "extern void" objects
8445 /// * @selector() expressions in Objective-C
8446 static bool EvaluateLValue(const Expr
*E
, LValue
&Result
, EvalInfo
&Info
,
8447 bool InvalidBaseOK
) {
8448 assert(!E
->isValueDependent());
8449 assert(E
->isGLValue() || E
->getType()->isFunctionType() ||
8450 E
->getType()->isVoidType() || isa
<ObjCSelectorExpr
>(E
->IgnoreParens()));
8451 return LValueExprEvaluator(Info
, Result
, InvalidBaseOK
).Visit(E
);
8454 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr
*E
) {
8455 const NamedDecl
*D
= E
->getDecl();
8456 if (isa
<FunctionDecl
, MSGuidDecl
, TemplateParamObjectDecl
,
8457 UnnamedGlobalConstantDecl
>(D
))
8458 return Success(cast
<ValueDecl
>(D
));
8459 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(D
))
8460 return VisitVarDecl(E
, VD
);
8461 if (const BindingDecl
*BD
= dyn_cast
<BindingDecl
>(D
))
8462 return Visit(BD
->getBinding());
8467 bool LValueExprEvaluator::VisitVarDecl(const Expr
*E
, const VarDecl
*VD
) {
8469 // If we are within a lambda's call operator, check whether the 'VD' referred
8470 // to within 'E' actually represents a lambda-capture that maps to a
8471 // data-member/field within the closure object, and if so, evaluate to the
8472 // field or what the field refers to.
8473 if (Info
.CurrentCall
&& isLambdaCallOperator(Info
.CurrentCall
->Callee
) &&
8474 isa
<DeclRefExpr
>(E
) &&
8475 cast
<DeclRefExpr
>(E
)->refersToEnclosingVariableOrCapture()) {
8476 // We don't always have a complete capture-map when checking or inferring if
8477 // the function call operator meets the requirements of a constexpr function
8478 // - but we don't need to evaluate the captures to determine constexprness
8479 // (dcl.constexpr C++17).
8480 if (Info
.checkingPotentialConstantExpression())
8483 if (auto *FD
= Info
.CurrentCall
->LambdaCaptureFields
.lookup(VD
)) {
8484 // Start with 'Result' referring to the complete closure object...
8485 if (auto *MD
= cast
<CXXMethodDecl
>(Info
.CurrentCall
->Callee
);
8486 MD
->isExplicitObjectMemberFunction()) {
8488 Info
.getParamSlot(Info
.CurrentCall
->Arguments
, MD
->getParamDecl(0));
8489 Result
.setFrom(Info
.Ctx
, *RefValue
);
8491 Result
= *Info
.CurrentCall
->This
;
8492 // ... then update it to refer to the field of the closure object
8493 // that represents the capture.
8494 if (!HandleLValueMember(Info
, E
, Result
, FD
))
8496 // And if the field is of reference type, update 'Result' to refer to what
8497 // the field refers to.
8498 if (FD
->getType()->isReferenceType()) {
8500 if (!handleLValueToRValueConversion(Info
, E
, FD
->getType(), Result
,
8503 Result
.setFrom(Info
.Ctx
, RVal
);
8509 CallStackFrame
*Frame
= nullptr;
8510 unsigned Version
= 0;
8511 if (VD
->hasLocalStorage()) {
8512 // Only if a local variable was declared in the function currently being
8513 // evaluated, do we expect to be able to find its value in the current
8514 // frame. (Otherwise it was likely declared in an enclosing context and
8515 // could either have a valid evaluatable value (for e.g. a constexpr
8516 // variable) or be ill-formed (and trigger an appropriate evaluation
8518 CallStackFrame
*CurrFrame
= Info
.CurrentCall
;
8519 if (CurrFrame
->Callee
&& CurrFrame
->Callee
->Equals(VD
->getDeclContext())) {
8520 // Function parameters are stored in some caller's frame. (Usually the
8521 // immediate caller, but for an inherited constructor they may be more
8523 if (auto *PVD
= dyn_cast
<ParmVarDecl
>(VD
)) {
8524 if (CurrFrame
->Arguments
) {
8525 VD
= CurrFrame
->Arguments
.getOrigParam(PVD
);
8527 Info
.getCallFrameAndDepth(CurrFrame
->Arguments
.CallIndex
).first
;
8528 Version
= CurrFrame
->Arguments
.Version
;
8532 Version
= CurrFrame
->getCurrentTemporaryVersion(VD
);
8537 if (!VD
->getType()->isReferenceType()) {
8539 Result
.set({VD
, Frame
->Index
, Version
});
8545 if (!Info
.getLangOpts().CPlusPlus11
) {
8546 Info
.CCEDiag(E
, diag::note_constexpr_ltor_non_integral
, 1)
8547 << VD
<< VD
->getType();
8548 Info
.Note(VD
->getLocation(), diag::note_declared_at
);
8552 if (!evaluateVarDeclInit(Info
, E
, VD
, Frame
, Version
, V
))
8554 if (!V
->hasValue()) {
8555 // FIXME: Is it possible for V to be indeterminate here? If so, we should
8556 // adjust the diagnostic to say that.
8557 if (!Info
.checkingPotentialConstantExpression())
8558 Info
.FFDiag(E
, diag::note_constexpr_use_uninit_reference
);
8561 return Success(*V
, E
);
8564 bool LValueExprEvaluator::VisitCallExpr(const CallExpr
*E
) {
8565 if (!IsConstantEvaluatedBuiltinCall(E
))
8566 return ExprEvaluatorBaseTy::VisitCallExpr(E
);
8568 switch (E
->getBuiltinCallee()) {
8571 case Builtin::BIas_const
:
8572 case Builtin::BIforward
:
8573 case Builtin::BIforward_like
:
8574 case Builtin::BImove
:
8575 case Builtin::BImove_if_noexcept
:
8576 if (cast
<FunctionDecl
>(E
->getCalleeDecl())->isConstexpr())
8577 return Visit(E
->getArg(0));
8581 return ExprEvaluatorBaseTy::VisitCallExpr(E
);
8584 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8585 const MaterializeTemporaryExpr
*E
) {
8586 // Walk through the expression to find the materialized temporary itself.
8587 SmallVector
<const Expr
*, 2> CommaLHSs
;
8588 SmallVector
<SubobjectAdjustment
, 2> Adjustments
;
8590 E
->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs
, Adjustments
);
8592 // If we passed any comma operators, evaluate their LHSs.
8593 for (const Expr
*E
: CommaLHSs
)
8594 if (!EvaluateIgnoredValue(Info
, E
))
8597 // A materialized temporary with static storage duration can appear within the
8598 // result of a constant expression evaluation, so we need to preserve its
8599 // value for use outside this evaluation.
8601 if (E
->getStorageDuration() == SD_Static
) {
8602 if (Info
.EvalMode
== EvalInfo::EM_ConstantFold
)
8604 // FIXME: What about SD_Thread?
8605 Value
= E
->getOrCreateValue(true);
8609 Value
= &Info
.CurrentCall
->createTemporary(
8611 E
->getStorageDuration() == SD_FullExpression
? ScopeKind::FullExpression
8616 QualType Type
= Inner
->getType();
8618 // Materialize the temporary itself.
8619 if (!EvaluateInPlace(*Value
, Info
, Result
, Inner
)) {
8624 // Adjust our lvalue to refer to the desired subobject.
8625 for (unsigned I
= Adjustments
.size(); I
!= 0; /**/) {
8627 switch (Adjustments
[I
].Kind
) {
8628 case SubobjectAdjustment::DerivedToBaseAdjustment
:
8629 if (!HandleLValueBasePath(Info
, Adjustments
[I
].DerivedToBase
.BasePath
,
8632 Type
= Adjustments
[I
].DerivedToBase
.BasePath
->getType();
8635 case SubobjectAdjustment::FieldAdjustment
:
8636 if (!HandleLValueMember(Info
, E
, Result
, Adjustments
[I
].Field
))
8638 Type
= Adjustments
[I
].Field
->getType();
8641 case SubobjectAdjustment::MemberPointerAdjustment
:
8642 if (!HandleMemberPointerAccess(this->Info
, Type
, Result
,
8643 Adjustments
[I
].Ptr
.RHS
))
8645 Type
= Adjustments
[I
].Ptr
.MPT
->getPointeeType();
8654 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr
*E
) {
8655 assert((!Info
.getLangOpts().CPlusPlus
|| E
->isFileScope()) &&
8656 "lvalue compound literal in c++?");
8657 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8658 // only see this when folding in C, so there's no standard to follow here.
8662 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr
*E
) {
8663 TypeInfoLValue TypeInfo
;
8665 if (!E
->isPotentiallyEvaluated()) {
8666 if (E
->isTypeOperand())
8667 TypeInfo
= TypeInfoLValue(E
->getTypeOperand(Info
.Ctx
).getTypePtr());
8669 TypeInfo
= TypeInfoLValue(E
->getExprOperand()->getType().getTypePtr());
8671 if (!Info
.Ctx
.getLangOpts().CPlusPlus20
) {
8672 Info
.CCEDiag(E
, diag::note_constexpr_typeid_polymorphic
)
8673 << E
->getExprOperand()->getType()
8674 << E
->getExprOperand()->getSourceRange();
8677 if (!Visit(E
->getExprOperand()))
8680 std::optional
<DynamicType
> DynType
=
8681 ComputeDynamicType(Info
, E
, Result
, AK_TypeId
);
8686 TypeInfoLValue(Info
.Ctx
.getRecordType(DynType
->Type
).getTypePtr());
8689 return Success(APValue::LValueBase::getTypeInfo(TypeInfo
, E
->getType()));
8692 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr
*E
) {
8693 return Success(E
->getGuidDecl());
8696 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr
*E
) {
8697 // Handle static data members.
8698 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(E
->getMemberDecl())) {
8699 VisitIgnoredBaseExpression(E
->getBase());
8700 return VisitVarDecl(E
, VD
);
8703 // Handle static member functions.
8704 if (const CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(E
->getMemberDecl())) {
8705 if (MD
->isStatic()) {
8706 VisitIgnoredBaseExpression(E
->getBase());
8711 // Handle non-static data members.
8712 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E
);
8715 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr
*E
) {
8716 // FIXME: Deal with vectors as array subscript bases.
8717 if (E
->getBase()->getType()->isVectorType() ||
8718 E
->getBase()->getType()->isSveVLSBuiltinType())
8722 bool Success
= true;
8724 // C++17's rules require us to evaluate the LHS first, regardless of which
8725 // side is the base.
8726 for (const Expr
*SubExpr
: {E
->getLHS(), E
->getRHS()}) {
8727 if (SubExpr
== E
->getBase() ? !evaluatePointer(SubExpr
, Result
)
8728 : !EvaluateInteger(SubExpr
, Index
, Info
)) {
8729 if (!Info
.noteFailure())
8736 HandleLValueArrayAdjustment(Info
, E
, Result
, E
->getType(), Index
);
8739 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator
*E
) {
8740 return evaluatePointer(E
->getSubExpr(), Result
);
8743 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator
*E
) {
8744 if (!Visit(E
->getSubExpr()))
8746 // __real is a no-op on scalar lvalues.
8747 if (E
->getSubExpr()->getType()->isAnyComplexType())
8748 HandleLValueComplexElement(Info
, E
, Result
, E
->getType(), false);
8752 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator
*E
) {
8753 assert(E
->getSubExpr()->getType()->isAnyComplexType() &&
8754 "lvalue __imag__ on scalar?");
8755 if (!Visit(E
->getSubExpr()))
8757 HandleLValueComplexElement(Info
, E
, Result
, E
->getType(), true);
8761 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator
*UO
) {
8762 if (!Info
.getLangOpts().CPlusPlus14
&& !Info
.keepEvaluatingAfterFailure())
8765 if (!this->Visit(UO
->getSubExpr()))
8768 return handleIncDec(
8769 this->Info
, UO
, Result
, UO
->getSubExpr()->getType(),
8770 UO
->isIncrementOp(), nullptr);
8773 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8774 const CompoundAssignOperator
*CAO
) {
8775 if (!Info
.getLangOpts().CPlusPlus14
&& !Info
.keepEvaluatingAfterFailure())
8778 bool Success
= true;
8780 // C++17 onwards require that we evaluate the RHS first.
8782 if (!Evaluate(RHS
, this->Info
, CAO
->getRHS())) {
8783 if (!Info
.noteFailure())
8788 // The overall lvalue result is the result of evaluating the LHS.
8789 if (!this->Visit(CAO
->getLHS()) || !Success
)
8792 return handleCompoundAssignment(
8794 Result
, CAO
->getLHS()->getType(), CAO
->getComputationLHSType(),
8795 CAO
->getOpForCompoundAssignment(CAO
->getOpcode()), RHS
);
8798 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator
*E
) {
8799 if (!Info
.getLangOpts().CPlusPlus14
&& !Info
.keepEvaluatingAfterFailure())
8802 bool Success
= true;
8804 // C++17 onwards require that we evaluate the RHS first.
8806 if (!Evaluate(NewVal
, this->Info
, E
->getRHS())) {
8807 if (!Info
.noteFailure())
8812 if (!this->Visit(E
->getLHS()) || !Success
)
8815 if (Info
.getLangOpts().CPlusPlus20
&&
8816 !MaybeHandleUnionActiveMemberChange(Info
, E
->getLHS(), Result
))
8819 return handleAssignment(this->Info
, E
, Result
, E
->getLHS()->getType(),
8823 //===----------------------------------------------------------------------===//
8824 // Pointer Evaluation
8825 //===----------------------------------------------------------------------===//
8827 /// Attempts to compute the number of bytes available at the pointer
8828 /// returned by a function with the alloc_size attribute. Returns true if we
8829 /// were successful. Places an unsigned number into `Result`.
8831 /// This expects the given CallExpr to be a call to a function with an
8832 /// alloc_size attribute.
8833 static bool getBytesReturnedByAllocSizeCall(const ASTContext
&Ctx
,
8834 const CallExpr
*Call
,
8835 llvm::APInt
&Result
) {
8836 const AllocSizeAttr
*AllocSize
= getAllocSizeAttr(Call
);
8838 assert(AllocSize
&& AllocSize
->getElemSizeParam().isValid());
8839 unsigned SizeArgNo
= AllocSize
->getElemSizeParam().getASTIndex();
8840 unsigned BitsInSizeT
= Ctx
.getTypeSize(Ctx
.getSizeType());
8841 if (Call
->getNumArgs() <= SizeArgNo
)
8844 auto EvaluateAsSizeT
= [&](const Expr
*E
, APSInt
&Into
) {
8845 Expr::EvalResult ExprResult
;
8846 if (!E
->EvaluateAsInt(ExprResult
, Ctx
, Expr::SE_AllowSideEffects
))
8848 Into
= ExprResult
.Val
.getInt();
8849 if (Into
.isNegative() || !Into
.isIntN(BitsInSizeT
))
8851 Into
= Into
.zext(BitsInSizeT
);
8856 if (!EvaluateAsSizeT(Call
->getArg(SizeArgNo
), SizeOfElem
))
8859 if (!AllocSize
->getNumElemsParam().isValid()) {
8860 Result
= std::move(SizeOfElem
);
8864 APSInt NumberOfElems
;
8865 unsigned NumArgNo
= AllocSize
->getNumElemsParam().getASTIndex();
8866 if (!EvaluateAsSizeT(Call
->getArg(NumArgNo
), NumberOfElems
))
8870 llvm::APInt BytesAvailable
= SizeOfElem
.umul_ov(NumberOfElems
, Overflow
);
8874 Result
= std::move(BytesAvailable
);
8878 /// Convenience function. LVal's base must be a call to an alloc_size
8880 static bool getBytesReturnedByAllocSizeCall(const ASTContext
&Ctx
,
8882 llvm::APInt
&Result
) {
8883 assert(isBaseAnAllocSizeCall(LVal
.getLValueBase()) &&
8884 "Can't get the size of a non alloc_size function");
8885 const auto *Base
= LVal
.getLValueBase().get
<const Expr
*>();
8886 const CallExpr
*CE
= tryUnwrapAllocSizeCall(Base
);
8887 return getBytesReturnedByAllocSizeCall(Ctx
, CE
, Result
);
8890 /// Attempts to evaluate the given LValueBase as the result of a call to
8891 /// a function with the alloc_size attribute. If it was possible to do so, this
8892 /// function will return true, make Result's Base point to said function call,
8893 /// and mark Result's Base as invalid.
8894 static bool evaluateLValueAsAllocSize(EvalInfo
&Info
, APValue::LValueBase Base
,
8899 // Because we do no form of static analysis, we only support const variables.
8901 // Additionally, we can't support parameters, nor can we support static
8902 // variables (in the latter case, use-before-assign isn't UB; in the former,
8903 // we have no clue what they'll be assigned to).
8905 dyn_cast_or_null
<VarDecl
>(Base
.dyn_cast
<const ValueDecl
*>());
8906 if (!VD
|| !VD
->isLocalVarDecl() || !VD
->getType().isConstQualified())
8909 const Expr
*Init
= VD
->getAnyInitializer();
8910 if (!Init
|| Init
->getType().isNull())
8913 const Expr
*E
= Init
->IgnoreParens();
8914 if (!tryUnwrapAllocSizeCall(E
))
8917 // Store E instead of E unwrapped so that the type of the LValue's base is
8918 // what the user wanted.
8919 Result
.setInvalid(E
);
8921 QualType Pointee
= E
->getType()->castAs
<PointerType
>()->getPointeeType();
8922 Result
.addUnsizedArray(Info
, E
, Pointee
);
8927 class PointerExprEvaluator
8928 : public ExprEvaluatorBase
<PointerExprEvaluator
> {
8932 bool Success(const Expr
*E
) {
8937 bool evaluateLValue(const Expr
*E
, LValue
&Result
) {
8938 return EvaluateLValue(E
, Result
, Info
, InvalidBaseOK
);
8941 bool evaluatePointer(const Expr
*E
, LValue
&Result
) {
8942 return EvaluatePointer(E
, Result
, Info
, InvalidBaseOK
);
8945 bool visitNonBuiltinCallExpr(const CallExpr
*E
);
8948 PointerExprEvaluator(EvalInfo
&info
, LValue
&Result
, bool InvalidBaseOK
)
8949 : ExprEvaluatorBaseTy(info
), Result(Result
),
8950 InvalidBaseOK(InvalidBaseOK
) {}
8952 bool Success(const APValue
&V
, const Expr
*E
) {
8953 Result
.setFrom(Info
.Ctx
, V
);
8956 bool ZeroInitialization(const Expr
*E
) {
8957 Result
.setNull(Info
.Ctx
, E
->getType());
8961 bool VisitBinaryOperator(const BinaryOperator
*E
);
8962 bool VisitCastExpr(const CastExpr
* E
);
8963 bool VisitUnaryAddrOf(const UnaryOperator
*E
);
8964 bool VisitObjCStringLiteral(const ObjCStringLiteral
*E
)
8965 { return Success(E
); }
8966 bool VisitObjCBoxedExpr(const ObjCBoxedExpr
*E
) {
8967 if (E
->isExpressibleAsConstantInitializer())
8969 if (Info
.noteFailure())
8970 EvaluateIgnoredValue(Info
, E
->getSubExpr());
8973 bool VisitAddrLabelExpr(const AddrLabelExpr
*E
)
8974 { return Success(E
); }
8975 bool VisitCallExpr(const CallExpr
*E
);
8976 bool VisitBuiltinCallExpr(const CallExpr
*E
, unsigned BuiltinOp
);
8977 bool VisitBlockExpr(const BlockExpr
*E
) {
8978 if (!E
->getBlockDecl()->hasCaptures())
8982 bool VisitCXXThisExpr(const CXXThisExpr
*E
) {
8983 // Can't look at 'this' when checking a potential constant expression.
8984 if (Info
.checkingPotentialConstantExpression())
8986 if (!Info
.CurrentCall
->This
) {
8987 if (Info
.getLangOpts().CPlusPlus11
)
8988 Info
.FFDiag(E
, diag::note_constexpr_this
) << E
->isImplicit();
8993 Result
= *Info
.CurrentCall
->This
;
8995 if (isLambdaCallOperator(Info
.CurrentCall
->Callee
)) {
8996 // Ensure we actually have captured 'this'. If something was wrong with
8997 // 'this' capture, the error would have been previously reported.
8998 // Otherwise we can be inside of a default initialization of an object
8999 // declared by lambda's body, so no need to return false.
9000 if (!Info
.CurrentCall
->LambdaThisCaptureField
)
9003 // If we have captured 'this', the 'this' expression refers
9004 // to the enclosing '*this' object (either by value or reference) which is
9005 // either copied into the closure object's field that represents the
9006 // '*this' or refers to '*this'.
9007 // Update 'Result' to refer to the data member/field of the closure object
9008 // that represents the '*this' capture.
9009 if (!HandleLValueMember(Info
, E
, Result
,
9010 Info
.CurrentCall
->LambdaThisCaptureField
))
9012 // If we captured '*this' by reference, replace the field with its referent.
9013 if (Info
.CurrentCall
->LambdaThisCaptureField
->getType()
9014 ->isPointerType()) {
9016 if (!handleLValueToRValueConversion(Info
, E
, E
->getType(), Result
,
9020 Result
.setFrom(Info
.Ctx
, RVal
);
9026 bool VisitCXXNewExpr(const CXXNewExpr
*E
);
9028 bool VisitSourceLocExpr(const SourceLocExpr
*E
) {
9029 assert(!E
->isIntType() && "SourceLocExpr isn't a pointer type?");
9030 APValue LValResult
= E
->EvaluateInContext(
9031 Info
.Ctx
, Info
.CurrentCall
->CurSourceLocExprScope
.getDefaultExpr());
9032 Result
.setFrom(Info
.Ctx
, LValResult
);
9036 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr
*E
) {
9037 std::string ResultStr
= E
->ComputeName(Info
.Ctx
);
9039 QualType CharTy
= Info
.Ctx
.CharTy
.withConst();
9040 APInt
Size(Info
.Ctx
.getTypeSize(Info
.Ctx
.getSizeType()),
9041 ResultStr
.size() + 1);
9042 QualType ArrayTy
= Info
.Ctx
.getConstantArrayType(
9043 CharTy
, Size
, nullptr, ArraySizeModifier::Normal
, 0);
9046 StringLiteral::Create(Info
.Ctx
, ResultStr
, StringLiteral::Ordinary
,
9047 /*Pascal*/ false, ArrayTy
, E
->getLocation());
9049 evaluateLValue(SL
, Result
);
9050 Result
.addArray(Info
, E
, cast
<ConstantArrayType
>(ArrayTy
));
9054 // FIXME: Missing: @protocol, @selector
9056 } // end anonymous namespace
9058 static bool EvaluatePointer(const Expr
* E
, LValue
& Result
, EvalInfo
&Info
,
9059 bool InvalidBaseOK
) {
9060 assert(!E
->isValueDependent());
9061 assert(E
->isPRValue() && E
->getType()->hasPointerRepresentation());
9062 return PointerExprEvaluator(Info
, Result
, InvalidBaseOK
).Visit(E
);
9065 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator
*E
) {
9066 if (E
->getOpcode() != BO_Add
&&
9067 E
->getOpcode() != BO_Sub
)
9068 return ExprEvaluatorBaseTy::VisitBinaryOperator(E
);
9070 const Expr
*PExp
= E
->getLHS();
9071 const Expr
*IExp
= E
->getRHS();
9072 if (IExp
->getType()->isPointerType())
9073 std::swap(PExp
, IExp
);
9075 bool EvalPtrOK
= evaluatePointer(PExp
, Result
);
9076 if (!EvalPtrOK
&& !Info
.noteFailure())
9079 llvm::APSInt Offset
;
9080 if (!EvaluateInteger(IExp
, Offset
, Info
) || !EvalPtrOK
)
9083 if (E
->getOpcode() == BO_Sub
)
9084 negateAsSigned(Offset
);
9086 QualType Pointee
= PExp
->getType()->castAs
<PointerType
>()->getPointeeType();
9087 return HandleLValueArrayAdjustment(Info
, E
, Result
, Pointee
, Offset
);
9090 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator
*E
) {
9091 return evaluateLValue(E
->getSubExpr(), Result
);
9094 // Is the provided decl 'std::source_location::current'?
9095 static bool IsDeclSourceLocationCurrent(const FunctionDecl
*FD
) {
9098 const IdentifierInfo
*FnII
= FD
->getIdentifier();
9099 if (!FnII
|| !FnII
->isStr("current"))
9102 const auto *RD
= dyn_cast
<RecordDecl
>(FD
->getParent());
9106 const IdentifierInfo
*ClassII
= RD
->getIdentifier();
9107 return RD
->isInStdNamespace() && ClassII
&& ClassII
->isStr("source_location");
9110 bool PointerExprEvaluator::VisitCastExpr(const CastExpr
*E
) {
9111 const Expr
*SubExpr
= E
->getSubExpr();
9113 switch (E
->getCastKind()) {
9117 case CK_CPointerToObjCPointerCast
:
9118 case CK_BlockPointerToObjCPointerCast
:
9119 case CK_AnyPointerToBlockPointerCast
:
9120 case CK_AddressSpaceConversion
:
9121 if (!Visit(SubExpr
))
9123 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
9124 // permitted in constant expressions in C++11. Bitcasts from cv void* are
9125 // also static_casts, but we disallow them as a resolution to DR1312.
9126 if (!E
->getType()->isVoidPointerType()) {
9127 // In some circumstances, we permit casting from void* to cv1 T*, when the
9128 // actual pointee object is actually a cv2 T.
9129 bool HasValidResult
= !Result
.InvalidBase
&& !Result
.Designator
.Invalid
&&
9131 bool VoidPtrCastMaybeOK
=
9133 Info
.Ctx
.hasSameUnqualifiedType(Result
.Designator
.getType(Info
.Ctx
),
9134 E
->getType()->getPointeeType());
9135 // 1. We'll allow it in std::allocator::allocate, and anything which that
9137 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
9138 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
9139 // We'll allow it in the body of std::source_location::current. GCC's
9140 // implementation had a parameter of type `void*`, and casts from
9141 // that back to `const __impl*` in its body.
9142 if (VoidPtrCastMaybeOK
&&
9143 (Info
.getStdAllocatorCaller("allocate") ||
9144 IsDeclSourceLocationCurrent(Info
.CurrentCall
->Callee
) ||
9145 Info
.getLangOpts().CPlusPlus26
)) {
9148 if (SubExpr
->getType()->isVoidPointerType()) {
9150 CCEDiag(E
, diag::note_constexpr_invalid_void_star_cast
)
9151 << SubExpr
->getType() << Info
.getLangOpts().CPlusPlus26
9152 << Result
.Designator
.getType(Info
.Ctx
).getCanonicalType()
9153 << E
->getType()->getPointeeType();
9155 CCEDiag(E
, diag::note_constexpr_invalid_cast
)
9156 << 3 << SubExpr
->getType();
9158 CCEDiag(E
, diag::note_constexpr_invalid_cast
)
9159 << 2 << Info
.Ctx
.getLangOpts().CPlusPlus
;
9160 Result
.Designator
.setInvalid();
9163 if (E
->getCastKind() == CK_AddressSpaceConversion
&& Result
.IsNullPtr
)
9164 ZeroInitialization(E
);
9167 case CK_DerivedToBase
:
9168 case CK_UncheckedDerivedToBase
:
9169 if (!evaluatePointer(E
->getSubExpr(), Result
))
9171 if (!Result
.Base
&& Result
.Offset
.isZero())
9174 // Now figure out the necessary offset to add to the base LV to get from
9175 // the derived class to the base class.
9176 return HandleLValueBasePath(Info
, E
, E
->getSubExpr()->getType()->
9177 castAs
<PointerType
>()->getPointeeType(),
9180 case CK_BaseToDerived
:
9181 if (!Visit(E
->getSubExpr()))
9183 if (!Result
.Base
&& Result
.Offset
.isZero())
9185 return HandleBaseToDerivedCast(Info
, E
, Result
);
9188 if (!Visit(E
->getSubExpr()))
9190 return HandleDynamicCast(Info
, cast
<ExplicitCastExpr
>(E
), Result
);
9192 case CK_NullToPointer
:
9193 VisitIgnoredValue(E
->getSubExpr());
9194 return ZeroInitialization(E
);
9196 case CK_IntegralToPointer
: {
9197 CCEDiag(E
, diag::note_constexpr_invalid_cast
)
9198 << 2 << Info
.Ctx
.getLangOpts().CPlusPlus
;
9201 if (!EvaluateIntegerOrLValue(SubExpr
, Value
, Info
))
9204 if (Value
.isInt()) {
9205 unsigned Size
= Info
.Ctx
.getTypeSize(E
->getType());
9206 uint64_t N
= Value
.getInt().extOrTrunc(Size
).getZExtValue();
9207 Result
.Base
= (Expr
*)nullptr;
9208 Result
.InvalidBase
= false;
9209 Result
.Offset
= CharUnits::fromQuantity(N
);
9210 Result
.Designator
.setInvalid();
9211 Result
.IsNullPtr
= false;
9214 // Cast is of an lvalue, no need to change value.
9215 Result
.setFrom(Info
.Ctx
, Value
);
9220 case CK_ArrayToPointerDecay
: {
9221 if (SubExpr
->isGLValue()) {
9222 if (!evaluateLValue(SubExpr
, Result
))
9225 APValue
&Value
= Info
.CurrentCall
->createTemporary(
9226 SubExpr
, SubExpr
->getType(), ScopeKind::FullExpression
, Result
);
9227 if (!EvaluateInPlace(Value
, Info
, Result
, SubExpr
))
9230 // The result is a pointer to the first element of the array.
9231 auto *AT
= Info
.Ctx
.getAsArrayType(SubExpr
->getType());
9232 if (auto *CAT
= dyn_cast
<ConstantArrayType
>(AT
))
9233 Result
.addArray(Info
, E
, CAT
);
9235 Result
.addUnsizedArray(Info
, E
, AT
->getElementType());
9239 case CK_FunctionToPointerDecay
:
9240 return evaluateLValue(SubExpr
, Result
);
9242 case CK_LValueToRValue
: {
9244 if (!evaluateLValue(E
->getSubExpr(), LVal
))
9248 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9249 if (!handleLValueToRValueConversion(Info
, E
, E
->getSubExpr()->getType(),
9251 return InvalidBaseOK
&&
9252 evaluateLValueAsAllocSize(Info
, LVal
.Base
, Result
);
9253 return Success(RVal
, E
);
9257 return ExprEvaluatorBaseTy::VisitCastExpr(E
);
9260 static CharUnits
GetAlignOfType(EvalInfo
&Info
, QualType T
,
9261 UnaryExprOrTypeTrait ExprKind
) {
9262 // C++ [expr.alignof]p3:
9263 // When alignof is applied to a reference type, the result is the
9264 // alignment of the referenced type.
9265 T
= T
.getNonReferenceType();
9267 if (T
.getQualifiers().hasUnaligned())
9268 return CharUnits::One();
9270 const bool AlignOfReturnsPreferred
=
9271 Info
.Ctx
.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7
;
9273 // __alignof is defined to return the preferred alignment.
9274 // Before 8, clang returned the preferred alignment for alignof and _Alignof
9276 if (ExprKind
== UETT_PreferredAlignOf
|| AlignOfReturnsPreferred
)
9277 return Info
.Ctx
.toCharUnitsFromBits(
9278 Info
.Ctx
.getPreferredTypeAlign(T
.getTypePtr()));
9279 // alignof and _Alignof are defined to return the ABI alignment.
9280 else if (ExprKind
== UETT_AlignOf
)
9281 return Info
.Ctx
.getTypeAlignInChars(T
.getTypePtr());
9283 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9286 static CharUnits
GetAlignOfExpr(EvalInfo
&Info
, const Expr
*E
,
9287 UnaryExprOrTypeTrait ExprKind
) {
9288 E
= E
->IgnoreParens();
9290 // The kinds of expressions that we have special-case logic here for
9291 // should be kept up to date with the special checks for those
9292 // expressions in Sema.
9294 // alignof decl is always accepted, even if it doesn't make sense: we default
9295 // to 1 in those cases.
9296 if (const DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(E
))
9297 return Info
.Ctx
.getDeclAlign(DRE
->getDecl(),
9298 /*RefAsPointee*/true);
9300 if (const MemberExpr
*ME
= dyn_cast
<MemberExpr
>(E
))
9301 return Info
.Ctx
.getDeclAlign(ME
->getMemberDecl(),
9302 /*RefAsPointee*/true);
9304 return GetAlignOfType(Info
, E
->getType(), ExprKind
);
9307 static CharUnits
getBaseAlignment(EvalInfo
&Info
, const LValue
&Value
) {
9308 if (const auto *VD
= Value
.Base
.dyn_cast
<const ValueDecl
*>())
9309 return Info
.Ctx
.getDeclAlign(VD
);
9310 if (const auto *E
= Value
.Base
.dyn_cast
<const Expr
*>())
9311 return GetAlignOfExpr(Info
, E
, UETT_AlignOf
);
9312 return GetAlignOfType(Info
, Value
.Base
.getTypeInfoType(), UETT_AlignOf
);
9315 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9316 /// __builtin_is_aligned and __builtin_assume_aligned.
9317 static bool getAlignmentArgument(const Expr
*E
, QualType ForType
,
9318 EvalInfo
&Info
, APSInt
&Alignment
) {
9319 if (!EvaluateInteger(E
, Alignment
, Info
))
9321 if (Alignment
< 0 || !Alignment
.isPowerOf2()) {
9322 Info
.FFDiag(E
, diag::note_constexpr_invalid_alignment
) << Alignment
;
9325 unsigned SrcWidth
= Info
.Ctx
.getIntWidth(ForType
);
9326 APSInt
MaxValue(APInt::getOneBitSet(SrcWidth
, SrcWidth
- 1));
9327 if (APSInt::compareValues(Alignment
, MaxValue
) > 0) {
9328 Info
.FFDiag(E
, diag::note_constexpr_alignment_too_big
)
9329 << MaxValue
<< ForType
<< Alignment
;
9332 // Ensure both alignment and source value have the same bit width so that we
9333 // don't assert when computing the resulting value.
9334 APSInt ExtAlignment
=
9335 APSInt(Alignment
.zextOrTrunc(SrcWidth
), /*isUnsigned=*/true);
9336 assert(APSInt::compareValues(Alignment
, ExtAlignment
) == 0 &&
9337 "Alignment should not be changed by ext/trunc");
9338 Alignment
= ExtAlignment
;
9339 assert(Alignment
.getBitWidth() == SrcWidth
);
9343 // To be clear: this happily visits unsupported builtins. Better name welcomed.
9344 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr
*E
) {
9345 if (ExprEvaluatorBaseTy::VisitCallExpr(E
))
9348 if (!(InvalidBaseOK
&& getAllocSizeAttr(E
)))
9351 Result
.setInvalid(E
);
9352 QualType PointeeTy
= E
->getType()->castAs
<PointerType
>()->getPointeeType();
9353 Result
.addUnsizedArray(Info
, E
, PointeeTy
);
9357 bool PointerExprEvaluator::VisitCallExpr(const CallExpr
*E
) {
9358 if (!IsConstantEvaluatedBuiltinCall(E
))
9359 return visitNonBuiltinCallExpr(E
);
9360 return VisitBuiltinCallExpr(E
, E
->getBuiltinCallee());
9363 // Determine if T is a character type for which we guarantee that
9365 static bool isOneByteCharacterType(QualType T
) {
9366 return T
->isCharType() || T
->isChar8Type();
9369 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr
*E
,
9370 unsigned BuiltinOp
) {
9374 switch (BuiltinOp
) {
9375 case Builtin::BIaddressof
:
9376 case Builtin::BI__addressof
:
9377 case Builtin::BI__builtin_addressof
:
9378 return evaluateLValue(E
->getArg(0), Result
);
9379 case Builtin::BI__builtin_assume_aligned
: {
9380 // We need to be very careful here because: if the pointer does not have the
9381 // asserted alignment, then the behavior is undefined, and undefined
9382 // behavior is non-constant.
9383 if (!evaluatePointer(E
->getArg(0), Result
))
9386 LValue
OffsetResult(Result
);
9388 if (!getAlignmentArgument(E
->getArg(1), E
->getArg(0)->getType(), Info
,
9391 CharUnits Align
= CharUnits::fromQuantity(Alignment
.getZExtValue());
9393 if (E
->getNumArgs() > 2) {
9395 if (!EvaluateInteger(E
->getArg(2), Offset
, Info
))
9398 int64_t AdditionalOffset
= -Offset
.getZExtValue();
9399 OffsetResult
.Offset
+= CharUnits::fromQuantity(AdditionalOffset
);
9402 // If there is a base object, then it must have the correct alignment.
9403 if (OffsetResult
.Base
) {
9404 CharUnits BaseAlignment
= getBaseAlignment(Info
, OffsetResult
);
9406 if (BaseAlignment
< Align
) {
9407 Result
.Designator
.setInvalid();
9408 // FIXME: Add support to Diagnostic for long / long long.
9409 CCEDiag(E
->getArg(0),
9410 diag::note_constexpr_baa_insufficient_alignment
) << 0
9411 << (unsigned)BaseAlignment
.getQuantity()
9412 << (unsigned)Align
.getQuantity();
9417 // The offset must also have the correct alignment.
9418 if (OffsetResult
.Offset
.alignTo(Align
) != OffsetResult
.Offset
) {
9419 Result
.Designator
.setInvalid();
9422 ? CCEDiag(E
->getArg(0),
9423 diag::note_constexpr_baa_insufficient_alignment
) << 1
9424 : CCEDiag(E
->getArg(0),
9425 diag::note_constexpr_baa_value_insufficient_alignment
))
9426 << (int)OffsetResult
.Offset
.getQuantity()
9427 << (unsigned)Align
.getQuantity();
9433 case Builtin::BI__builtin_align_up
:
9434 case Builtin::BI__builtin_align_down
: {
9435 if (!evaluatePointer(E
->getArg(0), Result
))
9438 if (!getAlignmentArgument(E
->getArg(1), E
->getArg(0)->getType(), Info
,
9441 CharUnits BaseAlignment
= getBaseAlignment(Info
, Result
);
9442 CharUnits PtrAlign
= BaseAlignment
.alignmentAtOffset(Result
.Offset
);
9443 // For align_up/align_down, we can return the same value if the alignment
9444 // is known to be greater or equal to the requested value.
9445 if (PtrAlign
.getQuantity() >= Alignment
)
9448 // The alignment could be greater than the minimum at run-time, so we cannot
9449 // infer much about the resulting pointer value. One case is possible:
9450 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9451 // can infer the correct index if the requested alignment is smaller than
9452 // the base alignment so we can perform the computation on the offset.
9453 if (BaseAlignment
.getQuantity() >= Alignment
) {
9454 assert(Alignment
.getBitWidth() <= 64 &&
9455 "Cannot handle > 64-bit address-space");
9456 uint64_t Alignment64
= Alignment
.getZExtValue();
9457 CharUnits NewOffset
= CharUnits::fromQuantity(
9458 BuiltinOp
== Builtin::BI__builtin_align_down
9459 ? llvm::alignDown(Result
.Offset
.getQuantity(), Alignment64
)
9460 : llvm::alignTo(Result
.Offset
.getQuantity(), Alignment64
));
9461 Result
.adjustOffset(NewOffset
- Result
.Offset
);
9462 // TODO: diagnose out-of-bounds values/only allow for arrays?
9465 // Otherwise, we cannot constant-evaluate the result.
9466 Info
.FFDiag(E
->getArg(0), diag::note_constexpr_alignment_adjust
)
9470 case Builtin::BI__builtin_operator_new
:
9471 return HandleOperatorNewCall(Info
, E
, Result
);
9472 case Builtin::BI__builtin_launder
:
9473 return evaluatePointer(E
->getArg(0), Result
);
9474 case Builtin::BIstrchr
:
9475 case Builtin::BIwcschr
:
9476 case Builtin::BImemchr
:
9477 case Builtin::BIwmemchr
:
9478 if (Info
.getLangOpts().CPlusPlus11
)
9479 Info
.CCEDiag(E
, diag::note_constexpr_invalid_function
)
9480 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9481 << ("'" + Info
.Ctx
.BuiltinInfo
.getName(BuiltinOp
) + "'").str();
9483 Info
.CCEDiag(E
, diag::note_invalid_subexpr_in_const_expr
);
9485 case Builtin::BI__builtin_strchr
:
9486 case Builtin::BI__builtin_wcschr
:
9487 case Builtin::BI__builtin_memchr
:
9488 case Builtin::BI__builtin_char_memchr
:
9489 case Builtin::BI__builtin_wmemchr
: {
9490 if (!Visit(E
->getArg(0)))
9493 if (!EvaluateInteger(E
->getArg(1), Desired
, Info
))
9495 uint64_t MaxLength
= uint64_t(-1);
9496 if (BuiltinOp
!= Builtin::BIstrchr
&&
9497 BuiltinOp
!= Builtin::BIwcschr
&&
9498 BuiltinOp
!= Builtin::BI__builtin_strchr
&&
9499 BuiltinOp
!= Builtin::BI__builtin_wcschr
) {
9501 if (!EvaluateInteger(E
->getArg(2), N
, Info
))
9503 MaxLength
= N
.getZExtValue();
9505 // We cannot find the value if there are no candidates to match against.
9506 if (MaxLength
== 0u)
9507 return ZeroInitialization(E
);
9508 if (!Result
.checkNullPointerForFoldAccess(Info
, E
, AK_Read
) ||
9509 Result
.Designator
.Invalid
)
9511 QualType CharTy
= Result
.Designator
.getType(Info
.Ctx
);
9512 bool IsRawByte
= BuiltinOp
== Builtin::BImemchr
||
9513 BuiltinOp
== Builtin::BI__builtin_memchr
;
9515 Info
.Ctx
.hasSameUnqualifiedType(
9516 CharTy
, E
->getArg(0)->getType()->getPointeeType()));
9517 // Pointers to const void may point to objects of incomplete type.
9518 if (IsRawByte
&& CharTy
->isIncompleteType()) {
9519 Info
.FFDiag(E
, diag::note_constexpr_ltor_incomplete_type
) << CharTy
;
9522 // Give up on byte-oriented matching against multibyte elements.
9523 // FIXME: We can compare the bytes in the correct order.
9524 if (IsRawByte
&& !isOneByteCharacterType(CharTy
)) {
9525 Info
.FFDiag(E
, diag::note_constexpr_memchr_unsupported
)
9526 << ("'" + Info
.Ctx
.BuiltinInfo
.getName(BuiltinOp
) + "'").str()
9530 // Figure out what value we're actually looking for (after converting to
9531 // the corresponding unsigned type if necessary).
9532 uint64_t DesiredVal
;
9533 bool StopAtNull
= false;
9534 switch (BuiltinOp
) {
9535 case Builtin::BIstrchr
:
9536 case Builtin::BI__builtin_strchr
:
9537 // strchr compares directly to the passed integer, and therefore
9538 // always fails if given an int that is not a char.
9539 if (!APSInt::isSameValue(HandleIntToIntCast(Info
, E
, CharTy
,
9540 E
->getArg(1)->getType(),
9543 return ZeroInitialization(E
);
9546 case Builtin::BImemchr
:
9547 case Builtin::BI__builtin_memchr
:
9548 case Builtin::BI__builtin_char_memchr
:
9549 // memchr compares by converting both sides to unsigned char. That's also
9550 // correct for strchr if we get this far (to cope with plain char being
9551 // unsigned in the strchr case).
9552 DesiredVal
= Desired
.trunc(Info
.Ctx
.getCharWidth()).getZExtValue();
9555 case Builtin::BIwcschr
:
9556 case Builtin::BI__builtin_wcschr
:
9559 case Builtin::BIwmemchr
:
9560 case Builtin::BI__builtin_wmemchr
:
9561 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9562 DesiredVal
= Desired
.getZExtValue();
9566 for (; MaxLength
; --MaxLength
) {
9568 if (!handleLValueToRValueConversion(Info
, E
, CharTy
, Result
, Char
) ||
9571 if (Char
.getInt().getZExtValue() == DesiredVal
)
9573 if (StopAtNull
&& !Char
.getInt())
9575 if (!HandleLValueArrayAdjustment(Info
, E
, Result
, CharTy
, 1))
9578 // Not found: return nullptr.
9579 return ZeroInitialization(E
);
9582 case Builtin::BImemcpy
:
9583 case Builtin::BImemmove
:
9584 case Builtin::BIwmemcpy
:
9585 case Builtin::BIwmemmove
:
9586 if (Info
.getLangOpts().CPlusPlus11
)
9587 Info
.CCEDiag(E
, diag::note_constexpr_invalid_function
)
9588 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9589 << ("'" + Info
.Ctx
.BuiltinInfo
.getName(BuiltinOp
) + "'").str();
9591 Info
.CCEDiag(E
, diag::note_invalid_subexpr_in_const_expr
);
9593 case Builtin::BI__builtin_memcpy
:
9594 case Builtin::BI__builtin_memmove
:
9595 case Builtin::BI__builtin_wmemcpy
:
9596 case Builtin::BI__builtin_wmemmove
: {
9597 bool WChar
= BuiltinOp
== Builtin::BIwmemcpy
||
9598 BuiltinOp
== Builtin::BIwmemmove
||
9599 BuiltinOp
== Builtin::BI__builtin_wmemcpy
||
9600 BuiltinOp
== Builtin::BI__builtin_wmemmove
;
9601 bool Move
= BuiltinOp
== Builtin::BImemmove
||
9602 BuiltinOp
== Builtin::BIwmemmove
||
9603 BuiltinOp
== Builtin::BI__builtin_memmove
||
9604 BuiltinOp
== Builtin::BI__builtin_wmemmove
;
9606 // The result of mem* is the first argument.
9607 if (!Visit(E
->getArg(0)))
9609 LValue Dest
= Result
;
9612 if (!EvaluatePointer(E
->getArg(1), Src
, Info
))
9616 if (!EvaluateInteger(E
->getArg(2), N
, Info
))
9618 assert(!N
.isSigned() && "memcpy and friends take an unsigned size");
9620 // If the size is zero, we treat this as always being a valid no-op.
9621 // (Even if one of the src and dest pointers is null.)
9625 // Otherwise, if either of the operands is null, we can't proceed. Don't
9626 // try to determine the type of the copied objects, because there aren't
9628 if (!Src
.Base
|| !Dest
.Base
) {
9630 (!Src
.Base
? Src
: Dest
).moveInto(Val
);
9631 Info
.FFDiag(E
, diag::note_constexpr_memcpy_null
)
9632 << Move
<< WChar
<< !!Src
.Base
9633 << Val
.getAsString(Info
.Ctx
, E
->getArg(0)->getType());
9636 if (Src
.Designator
.Invalid
|| Dest
.Designator
.Invalid
)
9639 // We require that Src and Dest are both pointers to arrays of
9640 // trivially-copyable type. (For the wide version, the designator will be
9641 // invalid if the designated object is not a wchar_t.)
9642 QualType T
= Dest
.Designator
.getType(Info
.Ctx
);
9643 QualType SrcT
= Src
.Designator
.getType(Info
.Ctx
);
9644 if (!Info
.Ctx
.hasSameUnqualifiedType(T
, SrcT
)) {
9645 // FIXME: Consider using our bit_cast implementation to support this.
9646 Info
.FFDiag(E
, diag::note_constexpr_memcpy_type_pun
) << Move
<< SrcT
<< T
;
9649 if (T
->isIncompleteType()) {
9650 Info
.FFDiag(E
, diag::note_constexpr_memcpy_incomplete_type
) << Move
<< T
;
9653 if (!T
.isTriviallyCopyableType(Info
.Ctx
)) {
9654 Info
.FFDiag(E
, diag::note_constexpr_memcpy_nontrivial
) << Move
<< T
;
9658 // Figure out how many T's we're copying.
9659 uint64_t TSize
= Info
.Ctx
.getTypeSizeInChars(T
).getQuantity();
9664 llvm::APInt OrigN
= N
;
9665 llvm::APInt::udivrem(OrigN
, TSize
, N
, Remainder
);
9667 Info
.FFDiag(E
, diag::note_constexpr_memcpy_unsupported
)
9668 << Move
<< WChar
<< 0 << T
<< toString(OrigN
, 10, /*Signed*/false)
9674 // Check that the copying will remain within the arrays, just so that we
9675 // can give a more meaningful diagnostic. This implicitly also checks that
9676 // N fits into 64 bits.
9677 uint64_t RemainingSrcSize
= Src
.Designator
.validIndexAdjustments().second
;
9678 uint64_t RemainingDestSize
= Dest
.Designator
.validIndexAdjustments().second
;
9679 if (N
.ugt(RemainingSrcSize
) || N
.ugt(RemainingDestSize
)) {
9680 Info
.FFDiag(E
, diag::note_constexpr_memcpy_unsupported
)
9681 << Move
<< WChar
<< (N
.ugt(RemainingSrcSize
) ? 1 : 2) << T
9682 << toString(N
, 10, /*Signed*/false);
9685 uint64_t NElems
= N
.getZExtValue();
9686 uint64_t NBytes
= NElems
* TSize
;
9688 // Check for overlap.
9690 if (HasSameBase(Src
, Dest
)) {
9691 uint64_t SrcOffset
= Src
.getLValueOffset().getQuantity();
9692 uint64_t DestOffset
= Dest
.getLValueOffset().getQuantity();
9693 if (DestOffset
>= SrcOffset
&& DestOffset
- SrcOffset
< NBytes
) {
9694 // Dest is inside the source region.
9696 Info
.FFDiag(E
, diag::note_constexpr_memcpy_overlap
) << WChar
;
9699 // For memmove and friends, copy backwards.
9700 if (!HandleLValueArrayAdjustment(Info
, E
, Src
, T
, NElems
- 1) ||
9701 !HandleLValueArrayAdjustment(Info
, E
, Dest
, T
, NElems
- 1))
9704 } else if (!Move
&& SrcOffset
>= DestOffset
&&
9705 SrcOffset
- DestOffset
< NBytes
) {
9706 // Src is inside the destination region for memcpy: invalid.
9707 Info
.FFDiag(E
, diag::note_constexpr_memcpy_overlap
) << WChar
;
9714 // FIXME: Set WantObjectRepresentation to true if we're copying a
9716 if (!handleLValueToRValueConversion(Info
, E
, T
, Src
, Val
) ||
9717 !handleAssignment(Info
, E
, Dest
, T
, Val
))
9719 // Do not iterate past the last element; if we're copying backwards, that
9720 // might take us off the start of the array.
9723 if (!HandleLValueArrayAdjustment(Info
, E
, Src
, T
, Direction
) ||
9724 !HandleLValueArrayAdjustment(Info
, E
, Dest
, T
, Direction
))
9734 static bool EvaluateArrayNewInitList(EvalInfo
&Info
, LValue
&This
,
9735 APValue
&Result
, const InitListExpr
*ILE
,
9736 QualType AllocType
);
9737 static bool EvaluateArrayNewConstructExpr(EvalInfo
&Info
, LValue
&This
,
9739 const CXXConstructExpr
*CCE
,
9740 QualType AllocType
);
9742 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr
*E
) {
9743 if (!Info
.getLangOpts().CPlusPlus20
)
9744 Info
.CCEDiag(E
, diag::note_constexpr_new
);
9746 // We cannot speculatively evaluate a delete expression.
9747 if (Info
.SpeculativeEvaluationDepth
)
9750 FunctionDecl
*OperatorNew
= E
->getOperatorNew();
9752 bool IsNothrow
= false;
9753 bool IsPlacement
= false;
9754 if (OperatorNew
->isReservedGlobalPlacementOperator() &&
9755 Info
.CurrentCall
->isStdFunction() && !E
->isArray()) {
9756 // FIXME Support array placement new.
9757 assert(E
->getNumPlacementArgs() == 1);
9758 if (!EvaluatePointer(E
->getPlacementArg(0), Result
, Info
))
9760 if (Result
.Designator
.Invalid
)
9763 } else if (!OperatorNew
->isReplaceableGlobalAllocationFunction()) {
9764 Info
.FFDiag(E
, diag::note_constexpr_new_non_replaceable
)
9765 << isa
<CXXMethodDecl
>(OperatorNew
) << OperatorNew
;
9767 } else if (E
->getNumPlacementArgs()) {
9768 // The only new-placement list we support is of the form (std::nothrow).
9770 // FIXME: There is no restriction on this, but it's not clear that any
9771 // other form makes any sense. We get here for cases such as:
9773 // new (std::align_val_t{N}) X(int)
9775 // (which should presumably be valid only if N is a multiple of
9776 // alignof(int), and in any case can't be deallocated unless N is
9777 // alignof(X) and X has new-extended alignment).
9778 if (E
->getNumPlacementArgs() != 1 ||
9779 !E
->getPlacementArg(0)->getType()->isNothrowT())
9780 return Error(E
, diag::note_constexpr_new_placement
);
9783 if (!EvaluateLValue(E
->getPlacementArg(0), Nothrow
, Info
))
9788 const Expr
*Init
= E
->getInitializer();
9789 const InitListExpr
*ResizedArrayILE
= nullptr;
9790 const CXXConstructExpr
*ResizedArrayCCE
= nullptr;
9791 bool ValueInit
= false;
9793 QualType AllocType
= E
->getAllocatedType();
9794 if (std::optional
<const Expr
*> ArraySize
= E
->getArraySize()) {
9795 const Expr
*Stripped
= *ArraySize
;
9796 for (; auto *ICE
= dyn_cast
<ImplicitCastExpr
>(Stripped
);
9797 Stripped
= ICE
->getSubExpr())
9798 if (ICE
->getCastKind() != CK_NoOp
&&
9799 ICE
->getCastKind() != CK_IntegralCast
)
9802 llvm::APSInt ArrayBound
;
9803 if (!EvaluateInteger(Stripped
, ArrayBound
, Info
))
9806 // C++ [expr.new]p9:
9807 // The expression is erroneous if:
9808 // -- [...] its value before converting to size_t [or] applying the
9809 // second standard conversion sequence is less than zero
9810 if (ArrayBound
.isSigned() && ArrayBound
.isNegative()) {
9812 return ZeroInitialization(E
);
9814 Info
.FFDiag(*ArraySize
, diag::note_constexpr_new_negative
)
9815 << ArrayBound
<< (*ArraySize
)->getSourceRange();
9819 // -- its value is such that the size of the allocated object would
9820 // exceed the implementation-defined limit
9821 if (!Info
.CheckArraySize(ArraySize
.value()->getExprLoc(),
9822 ConstantArrayType::getNumAddressingBits(
9823 Info
.Ctx
, AllocType
, ArrayBound
),
9824 ArrayBound
.getZExtValue(), /*Diag=*/!IsNothrow
)) {
9826 return ZeroInitialization(E
);
9830 // -- the new-initializer is a braced-init-list and the number of
9831 // array elements for which initializers are provided [...]
9832 // exceeds the number of elements to initialize
9834 // No initialization is performed.
9835 } else if (isa
<CXXScalarValueInitExpr
>(Init
) ||
9836 isa
<ImplicitValueInitExpr
>(Init
)) {
9838 } else if (auto *CCE
= dyn_cast
<CXXConstructExpr
>(Init
)) {
9839 ResizedArrayCCE
= CCE
;
9841 auto *CAT
= Info
.Ctx
.getAsConstantArrayType(Init
->getType());
9842 assert(CAT
&& "unexpected type for array initializer");
9845 std::max(CAT
->getSize().getBitWidth(), ArrayBound
.getBitWidth());
9846 llvm::APInt InitBound
= CAT
->getSize().zext(Bits
);
9847 llvm::APInt AllocBound
= ArrayBound
.zext(Bits
);
9848 if (InitBound
.ugt(AllocBound
)) {
9850 return ZeroInitialization(E
);
9852 Info
.FFDiag(*ArraySize
, diag::note_constexpr_new_too_small
)
9853 << toString(AllocBound
, 10, /*Signed=*/false)
9854 << toString(InitBound
, 10, /*Signed=*/false)
9855 << (*ArraySize
)->getSourceRange();
9859 // If the sizes differ, we must have an initializer list, and we need
9860 // special handling for this case when we initialize.
9861 if (InitBound
!= AllocBound
)
9862 ResizedArrayILE
= cast
<InitListExpr
>(Init
);
9865 AllocType
= Info
.Ctx
.getConstantArrayType(AllocType
, ArrayBound
, nullptr,
9866 ArraySizeModifier::Normal
, 0);
9868 assert(!AllocType
->isArrayType() &&
9869 "array allocation with non-array new");
9874 AccessKinds AK
= AK_Construct
;
9875 struct FindObjectHandler
{
9879 const AccessKinds AccessKind
;
9882 typedef bool result_type
;
9883 bool failed() { return false; }
9884 bool found(APValue
&Subobj
, QualType SubobjType
) {
9885 // FIXME: Reject the cases where [basic.life]p8 would not permit the
9886 // old name of the object to be used to name the new object.
9887 if (!Info
.Ctx
.hasSameUnqualifiedType(SubobjType
, AllocType
)) {
9888 Info
.FFDiag(E
, diag::note_constexpr_placement_new_wrong_type
) <<
9889 SubobjType
<< AllocType
;
9895 bool found(APSInt
&Value
, QualType SubobjType
) {
9896 Info
.FFDiag(E
, diag::note_constexpr_construct_complex_elem
);
9899 bool found(APFloat
&Value
, QualType SubobjType
) {
9900 Info
.FFDiag(E
, diag::note_constexpr_construct_complex_elem
);
9903 } Handler
= {Info
, E
, AllocType
, AK
, nullptr};
9905 CompleteObject Obj
= findCompleteObject(Info
, E
, AK
, Result
, AllocType
);
9906 if (!Obj
|| !findSubobject(Info
, E
, Obj
, Result
.Designator
, Handler
))
9909 Val
= Handler
.Value
;
9912 // The lifetime of an object o of type T ends when [...] the storage
9913 // which the object occupies is [...] reused by an object that is not
9914 // nested within o (6.6.2).
9917 // Perform the allocation and obtain a pointer to the resulting object.
9918 Val
= Info
.createHeapAlloc(E
, AllocType
, Result
);
9924 ImplicitValueInitExpr
VIE(AllocType
);
9925 if (!EvaluateInPlace(*Val
, Info
, Result
, &VIE
))
9927 } else if (ResizedArrayILE
) {
9928 if (!EvaluateArrayNewInitList(Info
, Result
, *Val
, ResizedArrayILE
,
9931 } else if (ResizedArrayCCE
) {
9932 if (!EvaluateArrayNewConstructExpr(Info
, Result
, *Val
, ResizedArrayCCE
,
9936 if (!EvaluateInPlace(*Val
, Info
, Result
, Init
))
9938 } else if (!handleDefaultInitValue(AllocType
, *Val
)) {
9942 // Array new returns a pointer to the first element, not a pointer to the
9944 if (auto *AT
= AllocType
->getAsArrayTypeUnsafe())
9945 Result
.addArray(Info
, E
, cast
<ConstantArrayType
>(AT
));
9949 //===----------------------------------------------------------------------===//
9950 // Member Pointer Evaluation
9951 //===----------------------------------------------------------------------===//
9954 class MemberPointerExprEvaluator
9955 : public ExprEvaluatorBase
<MemberPointerExprEvaluator
> {
9958 bool Success(const ValueDecl
*D
) {
9959 Result
= MemberPtr(D
);
9964 MemberPointerExprEvaluator(EvalInfo
&Info
, MemberPtr
&Result
)
9965 : ExprEvaluatorBaseTy(Info
), Result(Result
) {}
9967 bool Success(const APValue
&V
, const Expr
*E
) {
9971 bool ZeroInitialization(const Expr
*E
) {
9972 return Success((const ValueDecl
*)nullptr);
9975 bool VisitCastExpr(const CastExpr
*E
);
9976 bool VisitUnaryAddrOf(const UnaryOperator
*E
);
9978 } // end anonymous namespace
9980 static bool EvaluateMemberPointer(const Expr
*E
, MemberPtr
&Result
,
9982 assert(!E
->isValueDependent());
9983 assert(E
->isPRValue() && E
->getType()->isMemberPointerType());
9984 return MemberPointerExprEvaluator(Info
, Result
).Visit(E
);
9987 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr
*E
) {
9988 switch (E
->getCastKind()) {
9990 return ExprEvaluatorBaseTy::VisitCastExpr(E
);
9992 case CK_NullToMemberPointer
:
9993 VisitIgnoredValue(E
->getSubExpr());
9994 return ZeroInitialization(E
);
9996 case CK_BaseToDerivedMemberPointer
: {
9997 if (!Visit(E
->getSubExpr()))
9999 if (E
->path_empty())
10001 // Base-to-derived member pointer casts store the path in derived-to-base
10002 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
10003 // the wrong end of the derived->base arc, so stagger the path by one class.
10004 typedef std::reverse_iterator
<CastExpr::path_const_iterator
> ReverseIter
;
10005 for (ReverseIter
PathI(E
->path_end() - 1), PathE(E
->path_begin());
10006 PathI
!= PathE
; ++PathI
) {
10007 assert(!(*PathI
)->isVirtual() && "memptr cast through vbase");
10008 const CXXRecordDecl
*Derived
= (*PathI
)->getType()->getAsCXXRecordDecl();
10009 if (!Result
.castToDerived(Derived
))
10012 const Type
*FinalTy
= E
->getType()->castAs
<MemberPointerType
>()->getClass();
10013 if (!Result
.castToDerived(FinalTy
->getAsCXXRecordDecl()))
10018 case CK_DerivedToBaseMemberPointer
:
10019 if (!Visit(E
->getSubExpr()))
10021 for (CastExpr::path_const_iterator PathI
= E
->path_begin(),
10022 PathE
= E
->path_end(); PathI
!= PathE
; ++PathI
) {
10023 assert(!(*PathI
)->isVirtual() && "memptr cast through vbase");
10024 const CXXRecordDecl
*Base
= (*PathI
)->getType()->getAsCXXRecordDecl();
10025 if (!Result
.castToBase(Base
))
10032 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator
*E
) {
10033 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
10034 // member can be formed.
10035 return Success(cast
<DeclRefExpr
>(E
->getSubExpr())->getDecl());
10038 //===----------------------------------------------------------------------===//
10039 // Record Evaluation
10040 //===----------------------------------------------------------------------===//
10043 class RecordExprEvaluator
10044 : public ExprEvaluatorBase
<RecordExprEvaluator
> {
10045 const LValue
&This
;
10049 RecordExprEvaluator(EvalInfo
&info
, const LValue
&This
, APValue
&Result
)
10050 : ExprEvaluatorBaseTy(info
), This(This
), Result(Result
) {}
10052 bool Success(const APValue
&V
, const Expr
*E
) {
10056 bool ZeroInitialization(const Expr
*E
) {
10057 return ZeroInitialization(E
, E
->getType());
10059 bool ZeroInitialization(const Expr
*E
, QualType T
);
10061 bool VisitCallExpr(const CallExpr
*E
) {
10062 return handleCallExpr(E
, Result
, &This
);
10064 bool VisitCastExpr(const CastExpr
*E
);
10065 bool VisitInitListExpr(const InitListExpr
*E
);
10066 bool VisitCXXConstructExpr(const CXXConstructExpr
*E
) {
10067 return VisitCXXConstructExpr(E
, E
->getType());
10069 bool VisitLambdaExpr(const LambdaExpr
*E
);
10070 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr
*E
);
10071 bool VisitCXXConstructExpr(const CXXConstructExpr
*E
, QualType T
);
10072 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr
*E
);
10073 bool VisitBinCmp(const BinaryOperator
*E
);
10074 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr
*E
);
10075 bool VisitCXXParenListOrInitListExpr(const Expr
*ExprToVisit
,
10076 ArrayRef
<Expr
*> Args
);
10080 /// Perform zero-initialization on an object of non-union class type.
10081 /// C++11 [dcl.init]p5:
10082 /// To zero-initialize an object or reference of type T means:
10084 /// -- if T is a (possibly cv-qualified) non-union class type,
10085 /// each non-static data member and each base-class subobject is
10086 /// zero-initialized
10087 static bool HandleClassZeroInitialization(EvalInfo
&Info
, const Expr
*E
,
10088 const RecordDecl
*RD
,
10089 const LValue
&This
, APValue
&Result
) {
10090 assert(!RD
->isUnion() && "Expected non-union class type");
10091 const CXXRecordDecl
*CD
= dyn_cast
<CXXRecordDecl
>(RD
);
10092 Result
= APValue(APValue::UninitStruct(), CD
? CD
->getNumBases() : 0,
10093 std::distance(RD
->field_begin(), RD
->field_end()));
10095 if (RD
->isInvalidDecl()) return false;
10096 const ASTRecordLayout
&Layout
= Info
.Ctx
.getASTRecordLayout(RD
);
10099 unsigned Index
= 0;
10100 for (CXXRecordDecl::base_class_const_iterator I
= CD
->bases_begin(),
10101 End
= CD
->bases_end(); I
!= End
; ++I
, ++Index
) {
10102 const CXXRecordDecl
*Base
= I
->getType()->getAsCXXRecordDecl();
10103 LValue Subobject
= This
;
10104 if (!HandleLValueDirectBase(Info
, E
, Subobject
, CD
, Base
, &Layout
))
10106 if (!HandleClassZeroInitialization(Info
, E
, Base
, Subobject
,
10107 Result
.getStructBase(Index
)))
10112 for (const auto *I
: RD
->fields()) {
10113 // -- if T is a reference type, no initialization is performed.
10114 if (I
->isUnnamedBitfield() || I
->getType()->isReferenceType())
10117 LValue Subobject
= This
;
10118 if (!HandleLValueMember(Info
, E
, Subobject
, I
, &Layout
))
10121 ImplicitValueInitExpr
VIE(I
->getType());
10122 if (!EvaluateInPlace(
10123 Result
.getStructField(I
->getFieldIndex()), Info
, Subobject
, &VIE
))
10130 bool RecordExprEvaluator::ZeroInitialization(const Expr
*E
, QualType T
) {
10131 const RecordDecl
*RD
= T
->castAs
<RecordType
>()->getDecl();
10132 if (RD
->isInvalidDecl()) return false;
10133 if (RD
->isUnion()) {
10134 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
10135 // object's first non-static named data member is zero-initialized
10136 RecordDecl::field_iterator I
= RD
->field_begin();
10137 while (I
!= RD
->field_end() && (*I
)->isUnnamedBitfield())
10139 if (I
== RD
->field_end()) {
10140 Result
= APValue((const FieldDecl
*)nullptr);
10144 LValue Subobject
= This
;
10145 if (!HandleLValueMember(Info
, E
, Subobject
, *I
))
10147 Result
= APValue(*I
);
10148 ImplicitValueInitExpr
VIE(I
->getType());
10149 return EvaluateInPlace(Result
.getUnionValue(), Info
, Subobject
, &VIE
);
10152 if (isa
<CXXRecordDecl
>(RD
) && cast
<CXXRecordDecl
>(RD
)->getNumVBases()) {
10153 Info
.FFDiag(E
, diag::note_constexpr_virtual_base
) << RD
;
10157 return HandleClassZeroInitialization(Info
, E
, RD
, This
, Result
);
10160 bool RecordExprEvaluator::VisitCastExpr(const CastExpr
*E
) {
10161 switch (E
->getCastKind()) {
10163 return ExprEvaluatorBaseTy::VisitCastExpr(E
);
10165 case CK_ConstructorConversion
:
10166 return Visit(E
->getSubExpr());
10168 case CK_DerivedToBase
:
10169 case CK_UncheckedDerivedToBase
: {
10170 APValue DerivedObject
;
10171 if (!Evaluate(DerivedObject
, Info
, E
->getSubExpr()))
10173 if (!DerivedObject
.isStruct())
10174 return Error(E
->getSubExpr());
10176 // Derived-to-base rvalue conversion: just slice off the derived part.
10177 APValue
*Value
= &DerivedObject
;
10178 const CXXRecordDecl
*RD
= E
->getSubExpr()->getType()->getAsCXXRecordDecl();
10179 for (CastExpr::path_const_iterator PathI
= E
->path_begin(),
10180 PathE
= E
->path_end(); PathI
!= PathE
; ++PathI
) {
10181 assert(!(*PathI
)->isVirtual() && "record rvalue with virtual base");
10182 const CXXRecordDecl
*Base
= (*PathI
)->getType()->getAsCXXRecordDecl();
10183 Value
= &Value
->getStructBase(getBaseIndex(RD
, Base
));
10192 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr
*E
) {
10193 if (E
->isTransparent())
10194 return Visit(E
->getInit(0));
10195 return VisitCXXParenListOrInitListExpr(E
, E
->inits());
10198 bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
10199 const Expr
*ExprToVisit
, ArrayRef
<Expr
*> Args
) {
10200 const RecordDecl
*RD
=
10201 ExprToVisit
->getType()->castAs
<RecordType
>()->getDecl();
10202 if (RD
->isInvalidDecl()) return false;
10203 const ASTRecordLayout
&Layout
= Info
.Ctx
.getASTRecordLayout(RD
);
10204 auto *CXXRD
= dyn_cast
<CXXRecordDecl
>(RD
);
10206 EvalInfo::EvaluatingConstructorRAII
EvalObj(
10208 ObjectUnderConstruction
{This
.getLValueBase(), This
.Designator
.Entries
},
10209 CXXRD
&& CXXRD
->getNumBases());
10211 if (RD
->isUnion()) {
10212 const FieldDecl
*Field
;
10213 if (auto *ILE
= dyn_cast
<InitListExpr
>(ExprToVisit
)) {
10214 Field
= ILE
->getInitializedFieldInUnion();
10215 } else if (auto *PLIE
= dyn_cast
<CXXParenListInitExpr
>(ExprToVisit
)) {
10216 Field
= PLIE
->getInitializedFieldInUnion();
10219 "Expression is neither an init list nor a C++ paren list");
10222 Result
= APValue(Field
);
10226 // If the initializer list for a union does not contain any elements, the
10227 // first element of the union is value-initialized.
10228 // FIXME: The element should be initialized from an initializer list.
10229 // Is this difference ever observable for initializer lists which
10231 ImplicitValueInitExpr
VIE(Field
->getType());
10232 const Expr
*InitExpr
= Args
.empty() ? &VIE
: Args
[0];
10234 LValue Subobject
= This
;
10235 if (!HandleLValueMember(Info
, InitExpr
, Subobject
, Field
, &Layout
))
10238 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10239 ThisOverrideRAII
ThisOverride(*Info
.CurrentCall
, &This
,
10240 isa
<CXXDefaultInitExpr
>(InitExpr
));
10242 if (EvaluateInPlace(Result
.getUnionValue(), Info
, Subobject
, InitExpr
)) {
10243 if (Field
->isBitField())
10244 return truncateBitfieldValue(Info
, InitExpr
, Result
.getUnionValue(),
10252 if (!Result
.hasValue())
10253 Result
= APValue(APValue::UninitStruct(), CXXRD
? CXXRD
->getNumBases() : 0,
10254 std::distance(RD
->field_begin(), RD
->field_end()));
10255 unsigned ElementNo
= 0;
10256 bool Success
= true;
10258 // Initialize base classes.
10259 if (CXXRD
&& CXXRD
->getNumBases()) {
10260 for (const auto &Base
: CXXRD
->bases()) {
10261 assert(ElementNo
< Args
.size() && "missing init for base class");
10262 const Expr
*Init
= Args
[ElementNo
];
10264 LValue Subobject
= This
;
10265 if (!HandleLValueBase(Info
, Init
, Subobject
, CXXRD
, &Base
))
10268 APValue
&FieldVal
= Result
.getStructBase(ElementNo
);
10269 if (!EvaluateInPlace(FieldVal
, Info
, Subobject
, Init
)) {
10270 if (!Info
.noteFailure())
10277 EvalObj
.finishedConstructingBases();
10280 // Initialize members.
10281 for (const auto *Field
: RD
->fields()) {
10282 // Anonymous bit-fields are not considered members of the class for
10283 // purposes of aggregate initialization.
10284 if (Field
->isUnnamedBitfield())
10287 LValue Subobject
= This
;
10289 bool HaveInit
= ElementNo
< Args
.size();
10291 // FIXME: Diagnostics here should point to the end of the initializer
10292 // list, not the start.
10293 if (!HandleLValueMember(Info
, HaveInit
? Args
[ElementNo
] : ExprToVisit
,
10294 Subobject
, Field
, &Layout
))
10297 // Perform an implicit value-initialization for members beyond the end of
10298 // the initializer list.
10299 ImplicitValueInitExpr
VIE(HaveInit
? Info
.Ctx
.IntTy
: Field
->getType());
10300 const Expr
*Init
= HaveInit
? Args
[ElementNo
++] : &VIE
;
10302 if (Field
->getType()->isIncompleteArrayType()) {
10303 if (auto *CAT
= Info
.Ctx
.getAsConstantArrayType(Init
->getType())) {
10304 if (!CAT
->getSize().isZero()) {
10305 // Bail out for now. This might sort of "work", but the rest of the
10306 // code isn't really prepared to handle it.
10307 Info
.FFDiag(Init
, diag::note_constexpr_unsupported_flexible_array
);
10313 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10314 ThisOverrideRAII
ThisOverride(*Info
.CurrentCall
, &This
,
10315 isa
<CXXDefaultInitExpr
>(Init
));
10317 APValue
&FieldVal
= Result
.getStructField(Field
->getFieldIndex());
10318 if (!EvaluateInPlace(FieldVal
, Info
, Subobject
, Init
) ||
10319 (Field
->isBitField() && !truncateBitfieldValue(Info
, Init
,
10320 FieldVal
, Field
))) {
10321 if (!Info
.noteFailure())
10327 EvalObj
.finishedConstructingFields();
10332 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr
*E
,
10334 // Note that E's type is not necessarily the type of our class here; we might
10335 // be initializing an array element instead.
10336 const CXXConstructorDecl
*FD
= E
->getConstructor();
10337 if (FD
->isInvalidDecl() || FD
->getParent()->isInvalidDecl()) return false;
10339 bool ZeroInit
= E
->requiresZeroInitialization();
10340 if (CheckTrivialDefaultConstructor(Info
, E
->getExprLoc(), FD
, ZeroInit
)) {
10341 // If we've already performed zero-initialization, we're already done.
10342 if (Result
.hasValue())
10346 return ZeroInitialization(E
, T
);
10348 return handleDefaultInitValue(T
, Result
);
10351 const FunctionDecl
*Definition
= nullptr;
10352 auto Body
= FD
->getBody(Definition
);
10354 if (!CheckConstexprFunction(Info
, E
->getExprLoc(), FD
, Definition
, Body
))
10357 // Avoid materializing a temporary for an elidable copy/move constructor.
10358 if (E
->isElidable() && !ZeroInit
) {
10359 // FIXME: This only handles the simplest case, where the source object
10360 // is passed directly as the first argument to the constructor.
10361 // This should also handle stepping though implicit casts and
10362 // and conversion sequences which involve two steps, with a
10363 // conversion operator followed by a converting constructor.
10364 const Expr
*SrcObj
= E
->getArg(0);
10365 assert(SrcObj
->isTemporaryObject(Info
.Ctx
, FD
->getParent()));
10366 assert(Info
.Ctx
.hasSameUnqualifiedType(E
->getType(), SrcObj
->getType()));
10367 if (const MaterializeTemporaryExpr
*ME
=
10368 dyn_cast
<MaterializeTemporaryExpr
>(SrcObj
))
10369 return Visit(ME
->getSubExpr());
10372 if (ZeroInit
&& !ZeroInitialization(E
, T
))
10375 auto Args
= llvm::ArrayRef(E
->getArgs(), E
->getNumArgs());
10376 return HandleConstructorCall(E
, This
, Args
,
10377 cast
<CXXConstructorDecl
>(Definition
), Info
,
10381 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
10382 const CXXInheritedCtorInitExpr
*E
) {
10383 if (!Info
.CurrentCall
) {
10384 assert(Info
.checkingPotentialConstantExpression());
10388 const CXXConstructorDecl
*FD
= E
->getConstructor();
10389 if (FD
->isInvalidDecl() || FD
->getParent()->isInvalidDecl())
10392 const FunctionDecl
*Definition
= nullptr;
10393 auto Body
= FD
->getBody(Definition
);
10395 if (!CheckConstexprFunction(Info
, E
->getExprLoc(), FD
, Definition
, Body
))
10398 return HandleConstructorCall(E
, This
, Info
.CurrentCall
->Arguments
,
10399 cast
<CXXConstructorDecl
>(Definition
), Info
,
10403 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
10404 const CXXStdInitializerListExpr
*E
) {
10405 const ConstantArrayType
*ArrayType
=
10406 Info
.Ctx
.getAsConstantArrayType(E
->getSubExpr()->getType());
10409 if (!EvaluateLValue(E
->getSubExpr(), Array
, Info
))
10412 assert(ArrayType
&& "unexpected type for array initializer");
10414 // Get a pointer to the first element of the array.
10415 Array
.addArray(Info
, E
, ArrayType
);
10417 auto InvalidType
= [&] {
10418 Info
.FFDiag(E
, diag::note_constexpr_unsupported_layout
)
10423 // FIXME: Perform the checks on the field types in SemaInit.
10424 RecordDecl
*Record
= E
->getType()->castAs
<RecordType
>()->getDecl();
10425 RecordDecl::field_iterator Field
= Record
->field_begin();
10426 if (Field
== Record
->field_end())
10427 return InvalidType();
10430 if (!Field
->getType()->isPointerType() ||
10431 !Info
.Ctx
.hasSameType(Field
->getType()->getPointeeType(),
10432 ArrayType
->getElementType()))
10433 return InvalidType();
10435 // FIXME: What if the initializer_list type has base classes, etc?
10436 Result
= APValue(APValue::UninitStruct(), 0, 2);
10437 Array
.moveInto(Result
.getStructField(0));
10439 if (++Field
== Record
->field_end())
10440 return InvalidType();
10442 if (Field
->getType()->isPointerType() &&
10443 Info
.Ctx
.hasSameType(Field
->getType()->getPointeeType(),
10444 ArrayType
->getElementType())) {
10446 if (!HandleLValueArrayAdjustment(Info
, E
, Array
,
10447 ArrayType
->getElementType(),
10448 ArrayType
->getSize().getZExtValue()))
10450 Array
.moveInto(Result
.getStructField(1));
10451 } else if (Info
.Ctx
.hasSameType(Field
->getType(), Info
.Ctx
.getSizeType()))
10453 Result
.getStructField(1) = APValue(APSInt(ArrayType
->getSize()));
10455 return InvalidType();
10457 if (++Field
!= Record
->field_end())
10458 return InvalidType();
10463 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr
*E
) {
10464 const CXXRecordDecl
*ClosureClass
= E
->getLambdaClass();
10465 if (ClosureClass
->isInvalidDecl())
10468 const size_t NumFields
=
10469 std::distance(ClosureClass
->field_begin(), ClosureClass
->field_end());
10471 assert(NumFields
== (size_t)std::distance(E
->capture_init_begin(),
10472 E
->capture_init_end()) &&
10473 "The number of lambda capture initializers should equal the number of "
10474 "fields within the closure type");
10476 Result
= APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields
);
10477 // Iterate through all the lambda's closure object's fields and initialize
10479 auto *CaptureInitIt
= E
->capture_init_begin();
10480 bool Success
= true;
10481 const ASTRecordLayout
&Layout
= Info
.Ctx
.getASTRecordLayout(ClosureClass
);
10482 for (const auto *Field
: ClosureClass
->fields()) {
10483 assert(CaptureInitIt
!= E
->capture_init_end());
10484 // Get the initializer for this field
10485 Expr
*const CurFieldInit
= *CaptureInitIt
++;
10487 // If there is no initializer, either this is a VLA or an error has
10492 LValue Subobject
= This
;
10494 if (!HandleLValueMember(Info
, E
, Subobject
, Field
, &Layout
))
10497 APValue
&FieldVal
= Result
.getStructField(Field
->getFieldIndex());
10498 if (!EvaluateInPlace(FieldVal
, Info
, Subobject
, CurFieldInit
)) {
10499 if (!Info
.keepEvaluatingAfterFailure())
10507 static bool EvaluateRecord(const Expr
*E
, const LValue
&This
,
10508 APValue
&Result
, EvalInfo
&Info
) {
10509 assert(!E
->isValueDependent());
10510 assert(E
->isPRValue() && E
->getType()->isRecordType() &&
10511 "can't evaluate expression as a record rvalue");
10512 return RecordExprEvaluator(Info
, This
, Result
).Visit(E
);
10515 //===----------------------------------------------------------------------===//
10516 // Temporary Evaluation
10518 // Temporaries are represented in the AST as rvalues, but generally behave like
10519 // lvalues. The full-object of which the temporary is a subobject is implicitly
10520 // materialized so that a reference can bind to it.
10521 //===----------------------------------------------------------------------===//
10523 class TemporaryExprEvaluator
10524 : public LValueExprEvaluatorBase
<TemporaryExprEvaluator
> {
10526 TemporaryExprEvaluator(EvalInfo
&Info
, LValue
&Result
) :
10527 LValueExprEvaluatorBaseTy(Info
, Result
, false) {}
10529 /// Visit an expression which constructs the value of this temporary.
10530 bool VisitConstructExpr(const Expr
*E
) {
10531 APValue
&Value
= Info
.CurrentCall
->createTemporary(
10532 E
, E
->getType(), ScopeKind::FullExpression
, Result
);
10533 return EvaluateInPlace(Value
, Info
, Result
, E
);
10536 bool VisitCastExpr(const CastExpr
*E
) {
10537 switch (E
->getCastKind()) {
10539 return LValueExprEvaluatorBaseTy::VisitCastExpr(E
);
10541 case CK_ConstructorConversion
:
10542 return VisitConstructExpr(E
->getSubExpr());
10545 bool VisitInitListExpr(const InitListExpr
*E
) {
10546 return VisitConstructExpr(E
);
10548 bool VisitCXXConstructExpr(const CXXConstructExpr
*E
) {
10549 return VisitConstructExpr(E
);
10551 bool VisitCallExpr(const CallExpr
*E
) {
10552 return VisitConstructExpr(E
);
10554 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr
*E
) {
10555 return VisitConstructExpr(E
);
10557 bool VisitLambdaExpr(const LambdaExpr
*E
) {
10558 return VisitConstructExpr(E
);
10561 } // end anonymous namespace
10563 /// Evaluate an expression of record type as a temporary.
10564 static bool EvaluateTemporary(const Expr
*E
, LValue
&Result
, EvalInfo
&Info
) {
10565 assert(!E
->isValueDependent());
10566 assert(E
->isPRValue() && E
->getType()->isRecordType());
10567 return TemporaryExprEvaluator(Info
, Result
).Visit(E
);
10570 //===----------------------------------------------------------------------===//
10571 // Vector Evaluation
10572 //===----------------------------------------------------------------------===//
10575 class VectorExprEvaluator
10576 : public ExprEvaluatorBase
<VectorExprEvaluator
> {
10580 VectorExprEvaluator(EvalInfo
&info
, APValue
&Result
)
10581 : ExprEvaluatorBaseTy(info
), Result(Result
) {}
10583 bool Success(ArrayRef
<APValue
> V
, const Expr
*E
) {
10584 assert(V
.size() == E
->getType()->castAs
<VectorType
>()->getNumElements());
10585 // FIXME: remove this APValue copy.
10586 Result
= APValue(V
.data(), V
.size());
10589 bool Success(const APValue
&V
, const Expr
*E
) {
10590 assert(V
.isVector());
10594 bool ZeroInitialization(const Expr
*E
);
10596 bool VisitUnaryReal(const UnaryOperator
*E
)
10597 { return Visit(E
->getSubExpr()); }
10598 bool VisitCastExpr(const CastExpr
* E
);
10599 bool VisitInitListExpr(const InitListExpr
*E
);
10600 bool VisitUnaryImag(const UnaryOperator
*E
);
10601 bool VisitBinaryOperator(const BinaryOperator
*E
);
10602 bool VisitUnaryOperator(const UnaryOperator
*E
);
10603 // FIXME: Missing: conditional operator (for GNU
10604 // conditional select), shufflevector, ExtVectorElementExpr
10606 } // end anonymous namespace
10608 static bool EvaluateVector(const Expr
* E
, APValue
& Result
, EvalInfo
&Info
) {
10609 assert(E
->isPRValue() && E
->getType()->isVectorType() &&
10610 "not a vector prvalue");
10611 return VectorExprEvaluator(Info
, Result
).Visit(E
);
10614 bool VectorExprEvaluator::VisitCastExpr(const CastExpr
*E
) {
10615 const VectorType
*VTy
= E
->getType()->castAs
<VectorType
>();
10616 unsigned NElts
= VTy
->getNumElements();
10618 const Expr
*SE
= E
->getSubExpr();
10619 QualType SETy
= SE
->getType();
10621 switch (E
->getCastKind()) {
10622 case CK_VectorSplat
: {
10623 APValue Val
= APValue();
10624 if (SETy
->isIntegerType()) {
10626 if (!EvaluateInteger(SE
, IntResult
, Info
))
10628 Val
= APValue(std::move(IntResult
));
10629 } else if (SETy
->isRealFloatingType()) {
10630 APFloat
FloatResult(0.0);
10631 if (!EvaluateFloat(SE
, FloatResult
, Info
))
10633 Val
= APValue(std::move(FloatResult
));
10638 // Splat and create vector APValue.
10639 SmallVector
<APValue
, 4> Elts(NElts
, Val
);
10640 return Success(Elts
, E
);
10644 if (!Evaluate(SVal
, Info
, SE
))
10647 if (!SVal
.isInt() && !SVal
.isFloat() && !SVal
.isVector()) {
10648 // Give up if the input isn't an int, float, or vector. For example, we
10649 // reject "(v4i16)(intptr_t)&a".
10650 Info
.FFDiag(E
, diag::note_constexpr_invalid_cast
)
10651 << 2 << Info
.Ctx
.getLangOpts().CPlusPlus
;
10655 if (!handleRValueToRValueBitCast(Info
, Result
, SVal
, E
))
10661 return ExprEvaluatorBaseTy::VisitCastExpr(E
);
10666 VectorExprEvaluator::VisitInitListExpr(const InitListExpr
*E
) {
10667 const VectorType
*VT
= E
->getType()->castAs
<VectorType
>();
10668 unsigned NumInits
= E
->getNumInits();
10669 unsigned NumElements
= VT
->getNumElements();
10671 QualType EltTy
= VT
->getElementType();
10672 SmallVector
<APValue
, 4> Elements
;
10674 // The number of initializers can be less than the number of
10675 // vector elements. For OpenCL, this can be due to nested vector
10676 // initialization. For GCC compatibility, missing trailing elements
10677 // should be initialized with zeroes.
10678 unsigned CountInits
= 0, CountElts
= 0;
10679 while (CountElts
< NumElements
) {
10680 // Handle nested vector initialization.
10681 if (CountInits
< NumInits
10682 && E
->getInit(CountInits
)->getType()->isVectorType()) {
10684 if (!EvaluateVector(E
->getInit(CountInits
), v
, Info
))
10686 unsigned vlen
= v
.getVectorLength();
10687 for (unsigned j
= 0; j
< vlen
; j
++)
10688 Elements
.push_back(v
.getVectorElt(j
));
10690 } else if (EltTy
->isIntegerType()) {
10691 llvm::APSInt
sInt(32);
10692 if (CountInits
< NumInits
) {
10693 if (!EvaluateInteger(E
->getInit(CountInits
), sInt
, Info
))
10695 } else // trailing integer zero.
10696 sInt
= Info
.Ctx
.MakeIntValue(0, EltTy
);
10697 Elements
.push_back(APValue(sInt
));
10700 llvm::APFloat
f(0.0);
10701 if (CountInits
< NumInits
) {
10702 if (!EvaluateFloat(E
->getInit(CountInits
), f
, Info
))
10704 } else // trailing float zero.
10705 f
= APFloat::getZero(Info
.Ctx
.getFloatTypeSemantics(EltTy
));
10706 Elements
.push_back(APValue(f
));
10711 return Success(Elements
, E
);
10715 VectorExprEvaluator::ZeroInitialization(const Expr
*E
) {
10716 const auto *VT
= E
->getType()->castAs
<VectorType
>();
10717 QualType EltTy
= VT
->getElementType();
10718 APValue ZeroElement
;
10719 if (EltTy
->isIntegerType())
10720 ZeroElement
= APValue(Info
.Ctx
.MakeIntValue(0, EltTy
));
10723 APValue(APFloat::getZero(Info
.Ctx
.getFloatTypeSemantics(EltTy
)));
10725 SmallVector
<APValue
, 4> Elements(VT
->getNumElements(), ZeroElement
);
10726 return Success(Elements
, E
);
10729 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator
*E
) {
10730 VisitIgnoredValue(E
->getSubExpr());
10731 return ZeroInitialization(E
);
10734 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator
*E
) {
10735 BinaryOperatorKind Op
= E
->getOpcode();
10736 assert(Op
!= BO_PtrMemD
&& Op
!= BO_PtrMemI
&& Op
!= BO_Cmp
&&
10737 "Operation not supported on vector types");
10739 if (Op
== BO_Comma
)
10740 return ExprEvaluatorBaseTy::VisitBinaryOperator(E
);
10742 Expr
*LHS
= E
->getLHS();
10743 Expr
*RHS
= E
->getRHS();
10745 assert(LHS
->getType()->isVectorType() && RHS
->getType()->isVectorType() &&
10746 "Must both be vector types");
10747 // Checking JUST the types are the same would be fine, except shifts don't
10748 // need to have their types be the same (since you always shift by an int).
10749 assert(LHS
->getType()->castAs
<VectorType
>()->getNumElements() ==
10750 E
->getType()->castAs
<VectorType
>()->getNumElements() &&
10751 RHS
->getType()->castAs
<VectorType
>()->getNumElements() ==
10752 E
->getType()->castAs
<VectorType
>()->getNumElements() &&
10753 "All operands must be the same size.");
10757 bool LHSOK
= Evaluate(LHSValue
, Info
, LHS
);
10758 if (!LHSOK
&& !Info
.noteFailure())
10760 if (!Evaluate(RHSValue
, Info
, RHS
) || !LHSOK
)
10763 if (!handleVectorVectorBinOp(Info
, E
, Op
, LHSValue
, RHSValue
))
10766 return Success(LHSValue
, E
);
10769 static std::optional
<APValue
> handleVectorUnaryOperator(ASTContext
&Ctx
,
10771 UnaryOperatorKind Op
,
10775 // Nothing to do here.
10778 if (Elt
.getKind() == APValue::Int
) {
10779 Elt
.getInt().negate();
10781 assert(Elt
.getKind() == APValue::Float
&&
10782 "Vector can only be int or float type");
10783 Elt
.getFloat().changeSign();
10787 // This is only valid for integral types anyway, so we don't have to handle
10789 assert(Elt
.getKind() == APValue::Int
&&
10790 "Vector operator ~ can only be int");
10791 Elt
.getInt().flipAllBits();
10794 if (Elt
.getKind() == APValue::Int
) {
10795 Elt
.getInt() = !Elt
.getInt();
10796 // operator ! on vectors returns -1 for 'truth', so negate it.
10797 Elt
.getInt().negate();
10800 assert(Elt
.getKind() == APValue::Float
&&
10801 "Vector can only be int or float type");
10802 // Float types result in an int of the same size, but -1 for true, or 0 for
10804 APSInt EltResult
{Ctx
.getIntWidth(ResultTy
),
10805 ResultTy
->isUnsignedIntegerType()};
10806 if (Elt
.getFloat().isZero())
10807 EltResult
.setAllBits();
10809 EltResult
.clearAllBits();
10811 return APValue
{EltResult
};
10814 // FIXME: Implement the rest of the unary operators.
10815 return std::nullopt
;
10819 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator
*E
) {
10820 Expr
*SubExpr
= E
->getSubExpr();
10821 const auto *VD
= SubExpr
->getType()->castAs
<VectorType
>();
10822 // This result element type differs in the case of negating a floating point
10823 // vector, since the result type is the a vector of the equivilant sized
10825 const QualType ResultEltTy
= VD
->getElementType();
10826 UnaryOperatorKind Op
= E
->getOpcode();
10828 APValue SubExprValue
;
10829 if (!Evaluate(SubExprValue
, Info
, SubExpr
))
10832 // FIXME: This vector evaluator someday needs to be changed to be LValue
10833 // aware/keep LValue information around, rather than dealing with just vector
10834 // types directly. Until then, we cannot handle cases where the operand to
10835 // these unary operators is an LValue. The only case I've been able to see
10836 // cause this is operator++ assigning to a member expression (only valid in
10837 // altivec compilations) in C mode, so this shouldn't limit us too much.
10838 if (SubExprValue
.isLValue())
10841 assert(SubExprValue
.getVectorLength() == VD
->getNumElements() &&
10842 "Vector length doesn't match type?");
10844 SmallVector
<APValue
, 4> ResultElements
;
10845 for (unsigned EltNum
= 0; EltNum
< VD
->getNumElements(); ++EltNum
) {
10846 std::optional
<APValue
> Elt
= handleVectorUnaryOperator(
10847 Info
.Ctx
, ResultEltTy
, Op
, SubExprValue
.getVectorElt(EltNum
));
10850 ResultElements
.push_back(*Elt
);
10852 return Success(APValue(ResultElements
.data(), ResultElements
.size()), E
);
10855 //===----------------------------------------------------------------------===//
10856 // Array Evaluation
10857 //===----------------------------------------------------------------------===//
10860 class ArrayExprEvaluator
10861 : public ExprEvaluatorBase
<ArrayExprEvaluator
> {
10862 const LValue
&This
;
10866 ArrayExprEvaluator(EvalInfo
&Info
, const LValue
&This
, APValue
&Result
)
10867 : ExprEvaluatorBaseTy(Info
), This(This
), Result(Result
) {}
10869 bool Success(const APValue
&V
, const Expr
*E
) {
10870 assert(V
.isArray() && "expected array");
10875 bool ZeroInitialization(const Expr
*E
) {
10876 const ConstantArrayType
*CAT
=
10877 Info
.Ctx
.getAsConstantArrayType(E
->getType());
10879 if (E
->getType()->isIncompleteArrayType()) {
10880 // We can be asked to zero-initialize a flexible array member; this
10881 // is represented as an ImplicitValueInitExpr of incomplete array
10882 // type. In this case, the array has zero elements.
10883 Result
= APValue(APValue::UninitArray(), 0, 0);
10886 // FIXME: We could handle VLAs here.
10890 Result
= APValue(APValue::UninitArray(), 0,
10891 CAT
->getSize().getZExtValue());
10892 if (!Result
.hasArrayFiller())
10895 // Zero-initialize all elements.
10896 LValue Subobject
= This
;
10897 Subobject
.addArray(Info
, E
, CAT
);
10898 ImplicitValueInitExpr
VIE(CAT
->getElementType());
10899 return EvaluateInPlace(Result
.getArrayFiller(), Info
, Subobject
, &VIE
);
10902 bool VisitCallExpr(const CallExpr
*E
) {
10903 return handleCallExpr(E
, Result
, &This
);
10905 bool VisitInitListExpr(const InitListExpr
*E
,
10906 QualType AllocType
= QualType());
10907 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr
*E
);
10908 bool VisitCXXConstructExpr(const CXXConstructExpr
*E
);
10909 bool VisitCXXConstructExpr(const CXXConstructExpr
*E
,
10910 const LValue
&Subobject
,
10911 APValue
*Value
, QualType Type
);
10912 bool VisitStringLiteral(const StringLiteral
*E
,
10913 QualType AllocType
= QualType()) {
10914 expandStringLiteral(Info
, E
, Result
, AllocType
);
10917 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr
*E
);
10918 bool VisitCXXParenListOrInitListExpr(const Expr
*ExprToVisit
,
10919 ArrayRef
<Expr
*> Args
,
10920 const Expr
*ArrayFiller
,
10921 QualType AllocType
= QualType());
10923 } // end anonymous namespace
10925 static bool EvaluateArray(const Expr
*E
, const LValue
&This
,
10926 APValue
&Result
, EvalInfo
&Info
) {
10927 assert(!E
->isValueDependent());
10928 assert(E
->isPRValue() && E
->getType()->isArrayType() &&
10929 "not an array prvalue");
10930 return ArrayExprEvaluator(Info
, This
, Result
).Visit(E
);
10933 static bool EvaluateArrayNewInitList(EvalInfo
&Info
, LValue
&This
,
10934 APValue
&Result
, const InitListExpr
*ILE
,
10935 QualType AllocType
) {
10936 assert(!ILE
->isValueDependent());
10937 assert(ILE
->isPRValue() && ILE
->getType()->isArrayType() &&
10938 "not an array prvalue");
10939 return ArrayExprEvaluator(Info
, This
, Result
)
10940 .VisitInitListExpr(ILE
, AllocType
);
10943 static bool EvaluateArrayNewConstructExpr(EvalInfo
&Info
, LValue
&This
,
10945 const CXXConstructExpr
*CCE
,
10946 QualType AllocType
) {
10947 assert(!CCE
->isValueDependent());
10948 assert(CCE
->isPRValue() && CCE
->getType()->isArrayType() &&
10949 "not an array prvalue");
10950 return ArrayExprEvaluator(Info
, This
, Result
)
10951 .VisitCXXConstructExpr(CCE
, This
, &Result
, AllocType
);
10954 // Return true iff the given array filler may depend on the element index.
10955 static bool MaybeElementDependentArrayFiller(const Expr
*FillerExpr
) {
10956 // For now, just allow non-class value-initialization and initialization
10957 // lists comprised of them.
10958 if (isa
<ImplicitValueInitExpr
>(FillerExpr
))
10960 if (const InitListExpr
*ILE
= dyn_cast
<InitListExpr
>(FillerExpr
)) {
10961 for (unsigned I
= 0, E
= ILE
->getNumInits(); I
!= E
; ++I
) {
10962 if (MaybeElementDependentArrayFiller(ILE
->getInit(I
)))
10966 if (ILE
->hasArrayFiller() &&
10967 MaybeElementDependentArrayFiller(ILE
->getArrayFiller()))
10975 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr
*E
,
10976 QualType AllocType
) {
10977 const ConstantArrayType
*CAT
= Info
.Ctx
.getAsConstantArrayType(
10978 AllocType
.isNull() ? E
->getType() : AllocType
);
10982 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10983 // an appropriately-typed string literal enclosed in braces.
10984 if (E
->isStringLiteralInit()) {
10985 auto *SL
= dyn_cast
<StringLiteral
>(E
->getInit(0)->IgnoreParenImpCasts());
10986 // FIXME: Support ObjCEncodeExpr here once we support it in
10987 // ArrayExprEvaluator generally.
10990 return VisitStringLiteral(SL
, AllocType
);
10992 // Any other transparent list init will need proper handling of the
10993 // AllocType; we can't just recurse to the inner initializer.
10994 assert(!E
->isTransparent() &&
10995 "transparent array list initialization is not string literal init?");
10997 return VisitCXXParenListOrInitListExpr(E
, E
->inits(), E
->getArrayFiller(),
11001 bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
11002 const Expr
*ExprToVisit
, ArrayRef
<Expr
*> Args
, const Expr
*ArrayFiller
,
11003 QualType AllocType
) {
11004 const ConstantArrayType
*CAT
= Info
.Ctx
.getAsConstantArrayType(
11005 AllocType
.isNull() ? ExprToVisit
->getType() : AllocType
);
11007 bool Success
= true;
11009 assert((!Result
.isArray() || Result
.getArrayInitializedElts() == 0) &&
11010 "zero-initialized array shouldn't have any initialized elts");
11012 if (Result
.isArray() && Result
.hasArrayFiller())
11013 Filler
= Result
.getArrayFiller();
11015 unsigned NumEltsToInit
= Args
.size();
11016 unsigned NumElts
= CAT
->getSize().getZExtValue();
11018 // If the initializer might depend on the array index, run it for each
11020 if (NumEltsToInit
!= NumElts
&& MaybeElementDependentArrayFiller(ArrayFiller
))
11021 NumEltsToInit
= NumElts
;
11023 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
11024 << NumEltsToInit
<< ".\n");
11026 Result
= APValue(APValue::UninitArray(), NumEltsToInit
, NumElts
);
11028 // If the array was previously zero-initialized, preserve the
11029 // zero-initialized values.
11030 if (Filler
.hasValue()) {
11031 for (unsigned I
= 0, E
= Result
.getArrayInitializedElts(); I
!= E
; ++I
)
11032 Result
.getArrayInitializedElt(I
) = Filler
;
11033 if (Result
.hasArrayFiller())
11034 Result
.getArrayFiller() = Filler
;
11037 LValue Subobject
= This
;
11038 Subobject
.addArray(Info
, ExprToVisit
, CAT
);
11039 for (unsigned Index
= 0; Index
!= NumEltsToInit
; ++Index
) {
11040 const Expr
*Init
= Index
< Args
.size() ? Args
[Index
] : ArrayFiller
;
11041 if (!EvaluateInPlace(Result
.getArrayInitializedElt(Index
),
11042 Info
, Subobject
, Init
) ||
11043 !HandleLValueArrayAdjustment(Info
, Init
, Subobject
,
11044 CAT
->getElementType(), 1)) {
11045 if (!Info
.noteFailure())
11051 if (!Result
.hasArrayFiller())
11054 // If we get here, we have a trivial filler, which we can just evaluate
11055 // once and splat over the rest of the array elements.
11056 assert(ArrayFiller
&& "no array filler for incomplete init list");
11057 return EvaluateInPlace(Result
.getArrayFiller(), Info
, Subobject
,
11062 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr
*E
) {
11064 if (E
->getCommonExpr() &&
11065 !Evaluate(Info
.CurrentCall
->createTemporary(
11066 E
->getCommonExpr(),
11067 getStorageType(Info
.Ctx
, E
->getCommonExpr()),
11068 ScopeKind::FullExpression
, CommonLV
),
11069 Info
, E
->getCommonExpr()->getSourceExpr()))
11072 auto *CAT
= cast
<ConstantArrayType
>(E
->getType()->castAsArrayTypeUnsafe());
11074 uint64_t Elements
= CAT
->getSize().getZExtValue();
11075 Result
= APValue(APValue::UninitArray(), Elements
, Elements
);
11077 LValue Subobject
= This
;
11078 Subobject
.addArray(Info
, E
, CAT
);
11080 bool Success
= true;
11081 for (EvalInfo::ArrayInitLoopIndex
Index(Info
); Index
!= Elements
; ++Index
) {
11082 // C++ [class.temporary]/5
11083 // There are four contexts in which temporaries are destroyed at a different
11084 // point than the end of the full-expression. [...] The second context is
11085 // when a copy constructor is called to copy an element of an array while
11086 // the entire array is copied [...]. In either case, if the constructor has
11087 // one or more default arguments, the destruction of every temporary created
11088 // in a default argument is sequenced before the construction of the next
11089 // array element, if any.
11090 FullExpressionRAII
Scope(Info
);
11092 if (!EvaluateInPlace(Result
.getArrayInitializedElt(Index
),
11093 Info
, Subobject
, E
->getSubExpr()) ||
11094 !HandleLValueArrayAdjustment(Info
, E
, Subobject
,
11095 CAT
->getElementType(), 1)) {
11096 if (!Info
.noteFailure())
11101 // Make sure we run the destructors too.
11108 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr
*E
) {
11109 return VisitCXXConstructExpr(E
, This
, &Result
, E
->getType());
11112 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr
*E
,
11113 const LValue
&Subobject
,
11116 bool HadZeroInit
= Value
->hasValue();
11118 if (const ConstantArrayType
*CAT
= Info
.Ctx
.getAsConstantArrayType(Type
)) {
11119 unsigned FinalSize
= CAT
->getSize().getZExtValue();
11121 // Preserve the array filler if we had prior zero-initialization.
11123 HadZeroInit
&& Value
->hasArrayFiller() ? Value
->getArrayFiller()
11126 *Value
= APValue(APValue::UninitArray(), 0, FinalSize
);
11127 if (FinalSize
== 0)
11130 bool HasTrivialConstructor
= CheckTrivialDefaultConstructor(
11131 Info
, E
->getExprLoc(), E
->getConstructor(),
11132 E
->requiresZeroInitialization());
11133 LValue ArrayElt
= Subobject
;
11134 ArrayElt
.addArray(Info
, E
, CAT
);
11135 // We do the whole initialization in two passes, first for just one element,
11136 // then for the whole array. It's possible we may find out we can't do const
11137 // init in the first pass, in which case we avoid allocating a potentially
11138 // large array. We don't do more passes because expanding array requires
11139 // copying the data, which is wasteful.
11140 for (const unsigned N
: {1u, FinalSize
}) {
11141 unsigned OldElts
= Value
->getArrayInitializedElts();
11145 // Expand the array to appropriate size.
11146 APValue
NewValue(APValue::UninitArray(), N
, FinalSize
);
11147 for (unsigned I
= 0; I
< OldElts
; ++I
)
11148 NewValue
.getArrayInitializedElt(I
).swap(
11149 Value
->getArrayInitializedElt(I
));
11150 Value
->swap(NewValue
);
11153 for (unsigned I
= OldElts
; I
< N
; ++I
)
11154 Value
->getArrayInitializedElt(I
) = Filler
;
11156 if (HasTrivialConstructor
&& N
== FinalSize
&& FinalSize
!= 1) {
11157 // If we have a trivial constructor, only evaluate it once and copy
11158 // the result into all the array elements.
11159 APValue
&FirstResult
= Value
->getArrayInitializedElt(0);
11160 for (unsigned I
= OldElts
; I
< FinalSize
; ++I
)
11161 Value
->getArrayInitializedElt(I
) = FirstResult
;
11163 for (unsigned I
= OldElts
; I
< N
; ++I
) {
11164 if (!VisitCXXConstructExpr(E
, ArrayElt
,
11165 &Value
->getArrayInitializedElt(I
),
11166 CAT
->getElementType()) ||
11167 !HandleLValueArrayAdjustment(Info
, E
, ArrayElt
,
11168 CAT
->getElementType(), 1))
11170 // When checking for const initilization any diagnostic is considered
11172 if (Info
.EvalStatus
.Diag
&& !Info
.EvalStatus
.Diag
->empty() &&
11173 !Info
.keepEvaluatingAfterFailure())
11182 if (!Type
->isRecordType())
11185 return RecordExprEvaluator(Info
, Subobject
, *Value
)
11186 .VisitCXXConstructExpr(E
, Type
);
11189 bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
11190 const CXXParenListInitExpr
*E
) {
11191 assert(dyn_cast
<ConstantArrayType
>(E
->getType()) &&
11192 "Expression result is not a constant array type");
11194 return VisitCXXParenListOrInitListExpr(E
, E
->getInitExprs(),
11195 E
->getArrayFiller());
11198 //===----------------------------------------------------------------------===//
11199 // Integer Evaluation
11201 // As a GNU extension, we support casting pointers to sufficiently-wide integer
11202 // types and back in constant folding. Integer values are thus represented
11203 // either as an integer-valued APValue, or as an lvalue-valued APValue.
11204 //===----------------------------------------------------------------------===//
11207 class IntExprEvaluator
11208 : public ExprEvaluatorBase
<IntExprEvaluator
> {
11211 IntExprEvaluator(EvalInfo
&info
, APValue
&result
)
11212 : ExprEvaluatorBaseTy(info
), Result(result
) {}
11214 bool Success(const llvm::APSInt
&SI
, const Expr
*E
, APValue
&Result
) {
11215 assert(E
->getType()->isIntegralOrEnumerationType() &&
11216 "Invalid evaluation result.");
11217 assert(SI
.isSigned() == E
->getType()->isSignedIntegerOrEnumerationType() &&
11218 "Invalid evaluation result.");
11219 assert(SI
.getBitWidth() == Info
.Ctx
.getIntWidth(E
->getType()) &&
11220 "Invalid evaluation result.");
11221 Result
= APValue(SI
);
11224 bool Success(const llvm::APSInt
&SI
, const Expr
*E
) {
11225 return Success(SI
, E
, Result
);
11228 bool Success(const llvm::APInt
&I
, const Expr
*E
, APValue
&Result
) {
11229 assert(E
->getType()->isIntegralOrEnumerationType() &&
11230 "Invalid evaluation result.");
11231 assert(I
.getBitWidth() == Info
.Ctx
.getIntWidth(E
->getType()) &&
11232 "Invalid evaluation result.");
11233 Result
= APValue(APSInt(I
));
11234 Result
.getInt().setIsUnsigned(
11235 E
->getType()->isUnsignedIntegerOrEnumerationType());
11238 bool Success(const llvm::APInt
&I
, const Expr
*E
) {
11239 return Success(I
, E
, Result
);
11242 bool Success(uint64_t Value
, const Expr
*E
, APValue
&Result
) {
11243 assert(E
->getType()->isIntegralOrEnumerationType() &&
11244 "Invalid evaluation result.");
11245 Result
= APValue(Info
.Ctx
.MakeIntValue(Value
, E
->getType()));
11248 bool Success(uint64_t Value
, const Expr
*E
) {
11249 return Success(Value
, E
, Result
);
11252 bool Success(CharUnits Size
, const Expr
*E
) {
11253 return Success(Size
.getQuantity(), E
);
11256 bool Success(const APValue
&V
, const Expr
*E
) {
11257 if (V
.isLValue() || V
.isAddrLabelDiff() || V
.isIndeterminate()) {
11261 return Success(V
.getInt(), E
);
11264 bool ZeroInitialization(const Expr
*E
) { return Success(0, E
); }
11266 //===--------------------------------------------------------------------===//
11268 //===--------------------------------------------------------------------===//
11270 bool VisitIntegerLiteral(const IntegerLiteral
*E
) {
11271 return Success(E
->getValue(), E
);
11273 bool VisitCharacterLiteral(const CharacterLiteral
*E
) {
11274 return Success(E
->getValue(), E
);
11277 bool CheckReferencedDecl(const Expr
*E
, const Decl
*D
);
11278 bool VisitDeclRefExpr(const DeclRefExpr
*E
) {
11279 if (CheckReferencedDecl(E
, E
->getDecl()))
11282 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E
);
11284 bool VisitMemberExpr(const MemberExpr
*E
) {
11285 if (CheckReferencedDecl(E
, E
->getMemberDecl())) {
11286 VisitIgnoredBaseExpression(E
->getBase());
11290 return ExprEvaluatorBaseTy::VisitMemberExpr(E
);
11293 bool VisitCallExpr(const CallExpr
*E
);
11294 bool VisitBuiltinCallExpr(const CallExpr
*E
, unsigned BuiltinOp
);
11295 bool VisitBinaryOperator(const BinaryOperator
*E
);
11296 bool VisitOffsetOfExpr(const OffsetOfExpr
*E
);
11297 bool VisitUnaryOperator(const UnaryOperator
*E
);
11299 bool VisitCastExpr(const CastExpr
* E
);
11300 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr
*E
);
11302 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr
*E
) {
11303 return Success(E
->getValue(), E
);
11306 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr
*E
) {
11307 return Success(E
->getValue(), E
);
11310 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr
*E
) {
11311 if (Info
.ArrayInitIndex
== uint64_t(-1)) {
11312 // We were asked to evaluate this subexpression independent of the
11313 // enclosing ArrayInitLoopExpr. We can't do that.
11317 return Success(Info
.ArrayInitIndex
, E
);
11320 // Note, GNU defines __null as an integer, not a pointer.
11321 bool VisitGNUNullExpr(const GNUNullExpr
*E
) {
11322 return ZeroInitialization(E
);
11325 bool VisitTypeTraitExpr(const TypeTraitExpr
*E
) {
11326 return Success(E
->getValue(), E
);
11329 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr
*E
) {
11330 return Success(E
->getValue(), E
);
11333 bool VisitExpressionTraitExpr(const ExpressionTraitExpr
*E
) {
11334 return Success(E
->getValue(), E
);
11337 bool VisitUnaryReal(const UnaryOperator
*E
);
11338 bool VisitUnaryImag(const UnaryOperator
*E
);
11340 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr
*E
);
11341 bool VisitSizeOfPackExpr(const SizeOfPackExpr
*E
);
11342 bool VisitSourceLocExpr(const SourceLocExpr
*E
);
11343 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr
*E
);
11344 bool VisitRequiresExpr(const RequiresExpr
*E
);
11345 // FIXME: Missing: array subscript of vector, member of vector
11348 class FixedPointExprEvaluator
11349 : public ExprEvaluatorBase
<FixedPointExprEvaluator
> {
11353 FixedPointExprEvaluator(EvalInfo
&info
, APValue
&result
)
11354 : ExprEvaluatorBaseTy(info
), Result(result
) {}
11356 bool Success(const llvm::APInt
&I
, const Expr
*E
) {
11358 APFixedPoint(I
, Info
.Ctx
.getFixedPointSemantics(E
->getType())), E
);
11361 bool Success(uint64_t Value
, const Expr
*E
) {
11363 APFixedPoint(Value
, Info
.Ctx
.getFixedPointSemantics(E
->getType())), E
);
11366 bool Success(const APValue
&V
, const Expr
*E
) {
11367 return Success(V
.getFixedPoint(), E
);
11370 bool Success(const APFixedPoint
&V
, const Expr
*E
) {
11371 assert(E
->getType()->isFixedPointType() && "Invalid evaluation result.");
11372 assert(V
.getWidth() == Info
.Ctx
.getIntWidth(E
->getType()) &&
11373 "Invalid evaluation result.");
11374 Result
= APValue(V
);
11378 //===--------------------------------------------------------------------===//
11380 //===--------------------------------------------------------------------===//
11382 bool VisitFixedPointLiteral(const FixedPointLiteral
*E
) {
11383 return Success(E
->getValue(), E
);
11386 bool VisitCastExpr(const CastExpr
*E
);
11387 bool VisitUnaryOperator(const UnaryOperator
*E
);
11388 bool VisitBinaryOperator(const BinaryOperator
*E
);
11390 } // end anonymous namespace
11392 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
11393 /// produce either the integer value or a pointer.
11395 /// GCC has a heinous extension which folds casts between pointer types and
11396 /// pointer-sized integral types. We support this by allowing the evaluation of
11397 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
11398 /// Some simple arithmetic on such values is supported (they are treated much
11400 static bool EvaluateIntegerOrLValue(const Expr
*E
, APValue
&Result
,
11402 assert(!E
->isValueDependent());
11403 assert(E
->isPRValue() && E
->getType()->isIntegralOrEnumerationType());
11404 return IntExprEvaluator(Info
, Result
).Visit(E
);
11407 static bool EvaluateInteger(const Expr
*E
, APSInt
&Result
, EvalInfo
&Info
) {
11408 assert(!E
->isValueDependent());
11410 if (!EvaluateIntegerOrLValue(E
, Val
, Info
))
11412 if (!Val
.isInt()) {
11413 // FIXME: It would be better to produce the diagnostic for casting
11414 // a pointer to an integer.
11415 Info
.FFDiag(E
, diag::note_invalid_subexpr_in_const_expr
);
11418 Result
= Val
.getInt();
11422 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr
*E
) {
11423 APValue Evaluated
= E
->EvaluateInContext(
11424 Info
.Ctx
, Info
.CurrentCall
->CurSourceLocExprScope
.getDefaultExpr());
11425 return Success(Evaluated
, E
);
11428 static bool EvaluateFixedPoint(const Expr
*E
, APFixedPoint
&Result
,
11430 assert(!E
->isValueDependent());
11431 if (E
->getType()->isFixedPointType()) {
11433 if (!FixedPointExprEvaluator(Info
, Val
).Visit(E
))
11435 if (!Val
.isFixedPoint())
11438 Result
= Val
.getFixedPoint();
11444 static bool EvaluateFixedPointOrInteger(const Expr
*E
, APFixedPoint
&Result
,
11446 assert(!E
->isValueDependent());
11447 if (E
->getType()->isIntegerType()) {
11448 auto FXSema
= Info
.Ctx
.getFixedPointSemantics(E
->getType());
11450 if (!EvaluateInteger(E
, Val
, Info
))
11452 Result
= APFixedPoint(Val
, FXSema
);
11454 } else if (E
->getType()->isFixedPointType()) {
11455 return EvaluateFixedPoint(E
, Result
, Info
);
11460 /// Check whether the given declaration can be directly converted to an integral
11461 /// rvalue. If not, no diagnostic is produced; there are other things we can
11463 bool IntExprEvaluator::CheckReferencedDecl(const Expr
* E
, const Decl
* D
) {
11464 // Enums are integer constant exprs.
11465 if (const EnumConstantDecl
*ECD
= dyn_cast
<EnumConstantDecl
>(D
)) {
11466 // Check for signedness/width mismatches between E type and ECD value.
11467 bool SameSign
= (ECD
->getInitVal().isSigned()
11468 == E
->getType()->isSignedIntegerOrEnumerationType());
11469 bool SameWidth
= (ECD
->getInitVal().getBitWidth()
11470 == Info
.Ctx
.getIntWidth(E
->getType()));
11471 if (SameSign
&& SameWidth
)
11472 return Success(ECD
->getInitVal(), E
);
11474 // Get rid of mismatch (otherwise Success assertions will fail)
11475 // by computing a new value matching the type of E.
11476 llvm::APSInt Val
= ECD
->getInitVal();
11478 Val
.setIsSigned(!ECD
->getInitVal().isSigned());
11480 Val
= Val
.extOrTrunc(Info
.Ctx
.getIntWidth(E
->getType()));
11481 return Success(Val
, E
);
11487 /// Values returned by __builtin_classify_type, chosen to match the values
11488 /// produced by GCC's builtin.
11489 enum class GCCTypeClass
{
11493 // GCC reserves 2 for character types, but instead classifies them as
11498 // GCC reserves 6 for references, but appears to never use it (because
11499 // expressions never have reference type, presumably).
11500 PointerToDataMember
= 7,
11503 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
11504 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
11505 // GCC claims to reserve 11 for pointers to member functions, but *actually*
11506 // uses 12 for that purpose, same as for a class or struct. Maybe it
11507 // internally implements a pointer to member as a struct? Who knows.
11508 PointerToMemberFunction
= 12, // Not a bug, see above.
11509 ClassOrStruct
= 12,
11511 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
11512 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
11513 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
11517 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11519 static GCCTypeClass
11520 EvaluateBuiltinClassifyType(QualType T
, const LangOptions
&LangOpts
) {
11521 assert(!T
->isDependentType() && "unexpected dependent type");
11523 QualType CanTy
= T
.getCanonicalType();
11525 switch (CanTy
->getTypeClass()) {
11526 #define TYPE(ID, BASE)
11527 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
11528 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
11529 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
11530 #include "clang/AST/TypeNodes.inc"
11532 case Type::DeducedTemplateSpecialization
:
11533 llvm_unreachable("unexpected non-canonical or dependent type");
11535 case Type::Builtin
:
11536 switch (cast
<BuiltinType
>(CanTy
)->getKind()) {
11537 #define BUILTIN_TYPE(ID, SINGLETON_ID)
11538 #define SIGNED_TYPE(ID, SINGLETON_ID) \
11539 case BuiltinType::ID: return GCCTypeClass::Integer;
11540 #define FLOATING_TYPE(ID, SINGLETON_ID) \
11541 case BuiltinType::ID: return GCCTypeClass::RealFloat;
11542 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
11543 case BuiltinType::ID: break;
11544 #include "clang/AST/BuiltinTypes.def"
11545 case BuiltinType::Void
:
11546 return GCCTypeClass::Void
;
11548 case BuiltinType::Bool
:
11549 return GCCTypeClass::Bool
;
11551 case BuiltinType::Char_U
:
11552 case BuiltinType::UChar
:
11553 case BuiltinType::WChar_U
:
11554 case BuiltinType::Char8
:
11555 case BuiltinType::Char16
:
11556 case BuiltinType::Char32
:
11557 case BuiltinType::UShort
:
11558 case BuiltinType::UInt
:
11559 case BuiltinType::ULong
:
11560 case BuiltinType::ULongLong
:
11561 case BuiltinType::UInt128
:
11562 return GCCTypeClass::Integer
;
11564 case BuiltinType::UShortAccum
:
11565 case BuiltinType::UAccum
:
11566 case BuiltinType::ULongAccum
:
11567 case BuiltinType::UShortFract
:
11568 case BuiltinType::UFract
:
11569 case BuiltinType::ULongFract
:
11570 case BuiltinType::SatUShortAccum
:
11571 case BuiltinType::SatUAccum
:
11572 case BuiltinType::SatULongAccum
:
11573 case BuiltinType::SatUShortFract
:
11574 case BuiltinType::SatUFract
:
11575 case BuiltinType::SatULongFract
:
11576 return GCCTypeClass::None
;
11578 case BuiltinType::NullPtr
:
11580 case BuiltinType::ObjCId
:
11581 case BuiltinType::ObjCClass
:
11582 case BuiltinType::ObjCSel
:
11583 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11584 case BuiltinType::Id:
11585 #include "clang/Basic/OpenCLImageTypes.def"
11586 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11587 case BuiltinType::Id:
11588 #include "clang/Basic/OpenCLExtensionTypes.def"
11589 case BuiltinType::OCLSampler
:
11590 case BuiltinType::OCLEvent
:
11591 case BuiltinType::OCLClkEvent
:
11592 case BuiltinType::OCLQueue
:
11593 case BuiltinType::OCLReserveID
:
11594 #define SVE_TYPE(Name, Id, SingletonId) \
11595 case BuiltinType::Id:
11596 #include "clang/Basic/AArch64SVEACLETypes.def"
11597 #define PPC_VECTOR_TYPE(Name, Id, Size) \
11598 case BuiltinType::Id:
11599 #include "clang/Basic/PPCTypes.def"
11600 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11601 #include "clang/Basic/RISCVVTypes.def"
11602 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11603 #include "clang/Basic/WebAssemblyReferenceTypes.def"
11604 return GCCTypeClass::None
;
11606 case BuiltinType::Dependent
:
11607 llvm_unreachable("unexpected dependent type");
11609 llvm_unreachable("unexpected placeholder type");
11612 return LangOpts
.CPlusPlus
? GCCTypeClass::Enum
: GCCTypeClass::Integer
;
11614 case Type::Pointer
:
11615 case Type::ConstantArray
:
11616 case Type::VariableArray
:
11617 case Type::IncompleteArray
:
11618 case Type::FunctionNoProto
:
11619 case Type::FunctionProto
:
11620 return GCCTypeClass::Pointer
;
11622 case Type::MemberPointer
:
11623 return CanTy
->isMemberDataPointerType()
11624 ? GCCTypeClass::PointerToDataMember
11625 : GCCTypeClass::PointerToMemberFunction
;
11627 case Type::Complex
:
11628 return GCCTypeClass::Complex
;
11631 return CanTy
->isUnionType() ? GCCTypeClass::Union
11632 : GCCTypeClass::ClassOrStruct
;
11635 // GCC classifies _Atomic T the same as T.
11636 return EvaluateBuiltinClassifyType(
11637 CanTy
->castAs
<AtomicType
>()->getValueType(), LangOpts
);
11639 case Type::BlockPointer
:
11641 case Type::ExtVector
:
11642 case Type::ConstantMatrix
:
11643 case Type::ObjCObject
:
11644 case Type::ObjCInterface
:
11645 case Type::ObjCObjectPointer
:
11648 // GCC classifies vectors as None. We follow its lead and classify all
11649 // other types that don't fit into the regular classification the same way.
11650 return GCCTypeClass::None
;
11652 case Type::LValueReference
:
11653 case Type::RValueReference
:
11654 llvm_unreachable("invalid type for expression");
11657 llvm_unreachable("unexpected type class");
11660 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11662 static GCCTypeClass
11663 EvaluateBuiltinClassifyType(const CallExpr
*E
, const LangOptions
&LangOpts
) {
11664 // If no argument was supplied, default to None. This isn't
11665 // ideal, however it is what gcc does.
11666 if (E
->getNumArgs() == 0)
11667 return GCCTypeClass::None
;
11669 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11670 // being an ICE, but still folds it to a constant using the type of the first
11672 return EvaluateBuiltinClassifyType(E
->getArg(0)->getType(), LangOpts
);
11675 /// EvaluateBuiltinConstantPForLValue - Determine the result of
11676 /// __builtin_constant_p when applied to the given pointer.
11678 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
11679 /// or it points to the first character of a string literal.
11680 static bool EvaluateBuiltinConstantPForLValue(const APValue
&LV
) {
11681 APValue::LValueBase Base
= LV
.getLValueBase();
11682 if (Base
.isNull()) {
11683 // A null base is acceptable.
11685 } else if (const Expr
*E
= Base
.dyn_cast
<const Expr
*>()) {
11686 if (!isa
<StringLiteral
>(E
))
11688 return LV
.getLValueOffset().isZero();
11689 } else if (Base
.is
<TypeInfoLValue
>()) {
11690 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11691 // evaluate to true.
11694 // Any other base is not constant enough for GCC.
11699 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11700 /// GCC as we can manage.
11701 static bool EvaluateBuiltinConstantP(EvalInfo
&Info
, const Expr
*Arg
) {
11702 // This evaluation is not permitted to have side-effects, so evaluate it in
11703 // a speculative evaluation context.
11704 SpeculativeEvaluationRAII
SpeculativeEval(Info
);
11706 // Constant-folding is always enabled for the operand of __builtin_constant_p
11707 // (even when the enclosing evaluation context otherwise requires a strict
11708 // language-specific constant expression).
11709 FoldConstant
Fold(Info
, true);
11711 QualType ArgType
= Arg
->getType();
11713 // __builtin_constant_p always has one operand. The rules which gcc follows
11714 // are not precisely documented, but are as follows:
11716 // - If the operand is of integral, floating, complex or enumeration type,
11717 // and can be folded to a known value of that type, it returns 1.
11718 // - If the operand can be folded to a pointer to the first character
11719 // of a string literal (or such a pointer cast to an integral type)
11720 // or to a null pointer or an integer cast to a pointer, it returns 1.
11722 // Otherwise, it returns 0.
11724 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11725 // its support for this did not work prior to GCC 9 and is not yet well
11727 if (ArgType
->isIntegralOrEnumerationType() || ArgType
->isFloatingType() ||
11728 ArgType
->isAnyComplexType() || ArgType
->isPointerType() ||
11729 ArgType
->isNullPtrType()) {
11731 if (!::EvaluateAsRValue(Info
, Arg
, V
) || Info
.EvalStatus
.HasSideEffects
) {
11732 Fold
.keepDiagnostics();
11736 // For a pointer (possibly cast to integer), there are special rules.
11737 if (V
.getKind() == APValue::LValue
)
11738 return EvaluateBuiltinConstantPForLValue(V
);
11740 // Otherwise, any constant value is good enough.
11741 return V
.hasValue();
11744 // Anything else isn't considered to be sufficiently constant.
11748 /// Retrieves the "underlying object type" of the given expression,
11749 /// as used by __builtin_object_size.
11750 static QualType
getObjectType(APValue::LValueBase B
) {
11751 if (const ValueDecl
*D
= B
.dyn_cast
<const ValueDecl
*>()) {
11752 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(D
))
11753 return VD
->getType();
11754 } else if (const Expr
*E
= B
.dyn_cast
<const Expr
*>()) {
11755 if (isa
<CompoundLiteralExpr
>(E
))
11756 return E
->getType();
11757 } else if (B
.is
<TypeInfoLValue
>()) {
11758 return B
.getTypeInfoType();
11759 } else if (B
.is
<DynamicAllocLValue
>()) {
11760 return B
.getDynamicAllocType();
11766 /// A more selective version of E->IgnoreParenCasts for
11767 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11768 /// to change the type of E.
11769 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11771 /// Always returns an RValue with a pointer representation.
11772 static const Expr
*ignorePointerCastsAndParens(const Expr
*E
) {
11773 assert(E
->isPRValue() && E
->getType()->hasPointerRepresentation());
11775 auto *NoParens
= E
->IgnoreParens();
11776 auto *Cast
= dyn_cast
<CastExpr
>(NoParens
);
11777 if (Cast
== nullptr)
11780 // We only conservatively allow a few kinds of casts, because this code is
11781 // inherently a simple solution that seeks to support the common case.
11782 auto CastKind
= Cast
->getCastKind();
11783 if (CastKind
!= CK_NoOp
&& CastKind
!= CK_BitCast
&&
11784 CastKind
!= CK_AddressSpaceConversion
)
11787 auto *SubExpr
= Cast
->getSubExpr();
11788 if (!SubExpr
->getType()->hasPointerRepresentation() || !SubExpr
->isPRValue())
11790 return ignorePointerCastsAndParens(SubExpr
);
11793 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11794 /// record layout. e.g.
11795 /// struct { struct { int a, b; } fst, snd; } obj;
11798 /// obj.fst.a // no
11799 /// obj.fst.b // no
11800 /// obj.snd.a // no
11801 /// obj.snd.b // yes
11803 /// Please note: this function is specialized for how __builtin_object_size
11804 /// views "objects".
11806 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11807 /// correct result, it will always return true.
11808 static bool isDesignatorAtObjectEnd(const ASTContext
&Ctx
, const LValue
&LVal
) {
11809 assert(!LVal
.Designator
.Invalid
);
11811 auto IsLastOrInvalidFieldDecl
= [&Ctx
](const FieldDecl
*FD
, bool &Invalid
) {
11812 const RecordDecl
*Parent
= FD
->getParent();
11813 Invalid
= Parent
->isInvalidDecl();
11814 if (Invalid
|| Parent
->isUnion())
11816 const ASTRecordLayout
&Layout
= Ctx
.getASTRecordLayout(Parent
);
11817 return FD
->getFieldIndex() + 1 == Layout
.getFieldCount();
11820 auto &Base
= LVal
.getLValueBase();
11821 if (auto *ME
= dyn_cast_or_null
<MemberExpr
>(Base
.dyn_cast
<const Expr
*>())) {
11822 if (auto *FD
= dyn_cast
<FieldDecl
>(ME
->getMemberDecl())) {
11824 if (!IsLastOrInvalidFieldDecl(FD
, Invalid
))
11826 } else if (auto *IFD
= dyn_cast
<IndirectFieldDecl
>(ME
->getMemberDecl())) {
11827 for (auto *FD
: IFD
->chain()) {
11829 if (!IsLastOrInvalidFieldDecl(cast
<FieldDecl
>(FD
), Invalid
))
11836 QualType BaseType
= getType(Base
);
11837 if (LVal
.Designator
.FirstEntryIsAnUnsizedArray
) {
11838 // If we don't know the array bound, conservatively assume we're looking at
11839 // the final array element.
11841 if (BaseType
->isIncompleteArrayType())
11842 BaseType
= Ctx
.getAsArrayType(BaseType
)->getElementType();
11844 BaseType
= BaseType
->castAs
<PointerType
>()->getPointeeType();
11847 for (unsigned E
= LVal
.Designator
.Entries
.size(); I
!= E
; ++I
) {
11848 const auto &Entry
= LVal
.Designator
.Entries
[I
];
11849 if (BaseType
->isArrayType()) {
11850 // Because __builtin_object_size treats arrays as objects, we can ignore
11851 // the index iff this is the last array in the Designator.
11854 const auto *CAT
= cast
<ConstantArrayType
>(Ctx
.getAsArrayType(BaseType
));
11855 uint64_t Index
= Entry
.getAsArrayIndex();
11856 if (Index
+ 1 != CAT
->getSize())
11858 BaseType
= CAT
->getElementType();
11859 } else if (BaseType
->isAnyComplexType()) {
11860 const auto *CT
= BaseType
->castAs
<ComplexType
>();
11861 uint64_t Index
= Entry
.getAsArrayIndex();
11864 BaseType
= CT
->getElementType();
11865 } else if (auto *FD
= getAsField(Entry
)) {
11867 if (!IsLastOrInvalidFieldDecl(FD
, Invalid
))
11869 BaseType
= FD
->getType();
11871 assert(getAsBaseClass(Entry
) && "Expecting cast to a base class");
11878 /// Tests to see if the LValue has a user-specified designator (that isn't
11879 /// necessarily valid). Note that this always returns 'true' if the LValue has
11880 /// an unsized array as its first designator entry, because there's currently no
11881 /// way to tell if the user typed *foo or foo[0].
11882 static bool refersToCompleteObject(const LValue
&LVal
) {
11883 if (LVal
.Designator
.Invalid
)
11886 if (!LVal
.Designator
.Entries
.empty())
11887 return LVal
.Designator
.isMostDerivedAnUnsizedArray();
11889 if (!LVal
.InvalidBase
)
11892 // If `E` is a MemberExpr, then the first part of the designator is hiding in
11894 const auto *E
= LVal
.Base
.dyn_cast
<const Expr
*>();
11895 return !E
|| !isa
<MemberExpr
>(E
);
11898 /// Attempts to detect a user writing into a piece of memory that's impossible
11899 /// to figure out the size of by just using types.
11900 static bool isUserWritingOffTheEnd(const ASTContext
&Ctx
, const LValue
&LVal
) {
11901 const SubobjectDesignator
&Designator
= LVal
.Designator
;
11903 // - Users can only write off of the end when we have an invalid base. Invalid
11904 // bases imply we don't know where the memory came from.
11905 // - We used to be a bit more aggressive here; we'd only be conservative if
11906 // the array at the end was flexible, or if it had 0 or 1 elements. This
11907 // broke some common standard library extensions (PR30346), but was
11908 // otherwise seemingly fine. It may be useful to reintroduce this behavior
11909 // with some sort of list. OTOH, it seems that GCC is always
11910 // conservative with the last element in structs (if it's an array), so our
11911 // current behavior is more compatible than an explicit list approach would
11913 auto isFlexibleArrayMember
= [&] {
11914 using FAMKind
= LangOptions::StrictFlexArraysLevelKind
;
11915 FAMKind StrictFlexArraysLevel
=
11916 Ctx
.getLangOpts().getStrictFlexArraysLevel();
11918 if (Designator
.isMostDerivedAnUnsizedArray())
11921 if (StrictFlexArraysLevel
== FAMKind::Default
)
11924 if (Designator
.getMostDerivedArraySize() == 0 &&
11925 StrictFlexArraysLevel
!= FAMKind::IncompleteOnly
)
11928 if (Designator
.getMostDerivedArraySize() == 1 &&
11929 StrictFlexArraysLevel
== FAMKind::OneZeroOrIncomplete
)
11935 return LVal
.InvalidBase
&&
11936 Designator
.Entries
.size() == Designator
.MostDerivedPathLength
&&
11937 Designator
.MostDerivedIsArrayElement
&& isFlexibleArrayMember() &&
11938 isDesignatorAtObjectEnd(Ctx
, LVal
);
11941 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11942 /// Fails if the conversion would cause loss of precision.
11943 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt
&Int
,
11944 CharUnits
&Result
) {
11945 auto CharUnitsMax
= std::numeric_limits
<CharUnits::QuantityType
>::max();
11946 if (Int
.ugt(CharUnitsMax
))
11948 Result
= CharUnits::fromQuantity(Int
.getZExtValue());
11952 /// If we're evaluating the object size of an instance of a struct that
11953 /// contains a flexible array member, add the size of the initializer.
11954 static void addFlexibleArrayMemberInitSize(EvalInfo
&Info
, const QualType
&T
,
11955 const LValue
&LV
, CharUnits
&Size
) {
11956 if (!T
.isNull() && T
->isStructureType() &&
11957 T
->getAsStructureType()->getDecl()->hasFlexibleArrayMember())
11958 if (const auto *V
= LV
.getLValueBase().dyn_cast
<const ValueDecl
*>())
11959 if (const auto *VD
= dyn_cast
<VarDecl
>(V
))
11961 Size
+= VD
->getFlexibleArrayInitChars(Info
.Ctx
);
11964 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11965 /// determine how many bytes exist from the beginning of the object to either
11966 /// the end of the current subobject, or the end of the object itself, depending
11967 /// on what the LValue looks like + the value of Type.
11969 /// If this returns false, the value of Result is undefined.
11970 static bool determineEndOffset(EvalInfo
&Info
, SourceLocation ExprLoc
,
11971 unsigned Type
, const LValue
&LVal
,
11972 CharUnits
&EndOffset
) {
11973 bool DetermineForCompleteObject
= refersToCompleteObject(LVal
);
11975 auto CheckedHandleSizeof
= [&](QualType Ty
, CharUnits
&Result
) {
11976 if (Ty
.isNull() || Ty
->isIncompleteType() || Ty
->isFunctionType())
11978 return HandleSizeof(Info
, ExprLoc
, Ty
, Result
);
11981 // We want to evaluate the size of the entire object. This is a valid fallback
11982 // for when Type=1 and the designator is invalid, because we're asked for an
11984 if (!(Type
& 1) || LVal
.Designator
.Invalid
|| DetermineForCompleteObject
) {
11985 // Type=3 wants a lower bound, so we can't fall back to this.
11986 if (Type
== 3 && !DetermineForCompleteObject
)
11989 llvm::APInt APEndOffset
;
11990 if (isBaseAnAllocSizeCall(LVal
.getLValueBase()) &&
11991 getBytesReturnedByAllocSizeCall(Info
.Ctx
, LVal
, APEndOffset
))
11992 return convertUnsignedAPIntToCharUnits(APEndOffset
, EndOffset
);
11994 if (LVal
.InvalidBase
)
11997 QualType BaseTy
= getObjectType(LVal
.getLValueBase());
11998 const bool Ret
= CheckedHandleSizeof(BaseTy
, EndOffset
);
11999 addFlexibleArrayMemberInitSize(Info
, BaseTy
, LVal
, EndOffset
);
12003 // We want to evaluate the size of a subobject.
12004 const SubobjectDesignator
&Designator
= LVal
.Designator
;
12006 // The following is a moderately common idiom in C:
12008 // struct Foo { int a; char c[1]; };
12009 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
12010 // strcpy(&F->c[0], Bar);
12012 // In order to not break too much legacy code, we need to support it.
12013 if (isUserWritingOffTheEnd(Info
.Ctx
, LVal
)) {
12014 // If we can resolve this to an alloc_size call, we can hand that back,
12015 // because we know for certain how many bytes there are to write to.
12016 llvm::APInt APEndOffset
;
12017 if (isBaseAnAllocSizeCall(LVal
.getLValueBase()) &&
12018 getBytesReturnedByAllocSizeCall(Info
.Ctx
, LVal
, APEndOffset
))
12019 return convertUnsignedAPIntToCharUnits(APEndOffset
, EndOffset
);
12021 // If we cannot determine the size of the initial allocation, then we can't
12022 // given an accurate upper-bound. However, we are still able to give
12023 // conservative lower-bounds for Type=3.
12028 CharUnits BytesPerElem
;
12029 if (!CheckedHandleSizeof(Designator
.MostDerivedType
, BytesPerElem
))
12032 // According to the GCC documentation, we want the size of the subobject
12033 // denoted by the pointer. But that's not quite right -- what we actually
12034 // want is the size of the immediately-enclosing array, if there is one.
12035 int64_t ElemsRemaining
;
12036 if (Designator
.MostDerivedIsArrayElement
&&
12037 Designator
.Entries
.size() == Designator
.MostDerivedPathLength
) {
12038 uint64_t ArraySize
= Designator
.getMostDerivedArraySize();
12039 uint64_t ArrayIndex
= Designator
.Entries
.back().getAsArrayIndex();
12040 ElemsRemaining
= ArraySize
<= ArrayIndex
? 0 : ArraySize
- ArrayIndex
;
12042 ElemsRemaining
= Designator
.isOnePastTheEnd() ? 0 : 1;
12045 EndOffset
= LVal
.getLValueOffset() + BytesPerElem
* ElemsRemaining
;
12049 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
12050 /// returns true and stores the result in @p Size.
12052 /// If @p WasError is non-null, this will report whether the failure to evaluate
12053 /// is to be treated as an Error in IntExprEvaluator.
12054 static bool tryEvaluateBuiltinObjectSize(const Expr
*E
, unsigned Type
,
12055 EvalInfo
&Info
, uint64_t &Size
) {
12056 // Determine the denoted object.
12059 // The operand of __builtin_object_size is never evaluated for side-effects.
12060 // If there are any, but we can determine the pointed-to object anyway, then
12061 // ignore the side-effects.
12062 SpeculativeEvaluationRAII
SpeculativeEval(Info
);
12063 IgnoreSideEffectsRAII
Fold(Info
);
12065 if (E
->isGLValue()) {
12066 // It's possible for us to be given GLValues if we're called via
12067 // Expr::tryEvaluateObjectSize.
12069 if (!EvaluateAsRValue(Info
, E
, RVal
))
12071 LVal
.setFrom(Info
.Ctx
, RVal
);
12072 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E
), LVal
, Info
,
12073 /*InvalidBaseOK=*/true))
12077 // If we point to before the start of the object, there are no accessible
12079 if (LVal
.getLValueOffset().isNegative()) {
12084 CharUnits EndOffset
;
12085 if (!determineEndOffset(Info
, E
->getExprLoc(), Type
, LVal
, EndOffset
))
12088 // If we've fallen outside of the end offset, just pretend there's nothing to
12089 // write to/read from.
12090 if (EndOffset
<= LVal
.getLValueOffset())
12093 Size
= (EndOffset
- LVal
.getLValueOffset()).getQuantity();
12097 bool IntExprEvaluator::VisitCallExpr(const CallExpr
*E
) {
12098 if (!IsConstantEvaluatedBuiltinCall(E
))
12099 return ExprEvaluatorBaseTy::VisitCallExpr(E
);
12100 return VisitBuiltinCallExpr(E
, E
->getBuiltinCallee());
12103 static bool getBuiltinAlignArguments(const CallExpr
*E
, EvalInfo
&Info
,
12104 APValue
&Val
, APSInt
&Alignment
) {
12105 QualType SrcTy
= E
->getArg(0)->getType();
12106 if (!getAlignmentArgument(E
->getArg(1), SrcTy
, Info
, Alignment
))
12108 // Even though we are evaluating integer expressions we could get a pointer
12109 // argument for the __builtin_is_aligned() case.
12110 if (SrcTy
->isPointerType()) {
12112 if (!EvaluatePointer(E
->getArg(0), Ptr
, Info
))
12115 } else if (!SrcTy
->isIntegralOrEnumerationType()) {
12116 Info
.FFDiag(E
->getArg(0));
12120 if (!EvaluateInteger(E
->getArg(0), SrcInt
, Info
))
12122 assert(SrcInt
.getBitWidth() >= Alignment
.getBitWidth() &&
12123 "Bit widths must be the same");
12124 Val
= APValue(SrcInt
);
12126 assert(Val
.hasValue());
12130 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr
*E
,
12131 unsigned BuiltinOp
) {
12132 switch (BuiltinOp
) {
12136 case Builtin::BI__builtin_dynamic_object_size
:
12137 case Builtin::BI__builtin_object_size
: {
12138 // The type was checked when we built the expression.
12140 E
->getArg(1)->EvaluateKnownConstInt(Info
.Ctx
).getZExtValue();
12141 assert(Type
<= 3 && "unexpected type");
12144 if (tryEvaluateBuiltinObjectSize(E
->getArg(0), Type
, Info
, Size
))
12145 return Success(Size
, E
);
12147 if (E
->getArg(0)->HasSideEffects(Info
.Ctx
))
12148 return Success((Type
& 2) ? 0 : -1, E
);
12150 // Expression had no side effects, but we couldn't statically determine the
12151 // size of the referenced object.
12152 switch (Info
.EvalMode
) {
12153 case EvalInfo::EM_ConstantExpression
:
12154 case EvalInfo::EM_ConstantFold
:
12155 case EvalInfo::EM_IgnoreSideEffects
:
12156 // Leave it to IR generation.
12158 case EvalInfo::EM_ConstantExpressionUnevaluated
:
12159 // Reduce it to a constant now.
12160 return Success((Type
& 2) ? 0 : -1, E
);
12163 llvm_unreachable("unexpected EvalMode");
12166 case Builtin::BI__builtin_os_log_format_buffer_size
: {
12167 analyze_os_log::OSLogBufferLayout Layout
;
12168 analyze_os_log::computeOSLogBufferLayout(Info
.Ctx
, E
, Layout
);
12169 return Success(Layout
.size().getQuantity(), E
);
12172 case Builtin::BI__builtin_is_aligned
: {
12175 if (!getBuiltinAlignArguments(E
, Info
, Src
, Alignment
))
12177 if (Src
.isLValue()) {
12178 // If we evaluated a pointer, check the minimum known alignment.
12180 Ptr
.setFrom(Info
.Ctx
, Src
);
12181 CharUnits BaseAlignment
= getBaseAlignment(Info
, Ptr
);
12182 CharUnits PtrAlign
= BaseAlignment
.alignmentAtOffset(Ptr
.Offset
);
12183 // We can return true if the known alignment at the computed offset is
12184 // greater than the requested alignment.
12185 assert(PtrAlign
.isPowerOfTwo());
12186 assert(Alignment
.isPowerOf2());
12187 if (PtrAlign
.getQuantity() >= Alignment
)
12188 return Success(1, E
);
12189 // If the alignment is not known to be sufficient, some cases could still
12190 // be aligned at run time. However, if the requested alignment is less or
12191 // equal to the base alignment and the offset is not aligned, we know that
12192 // the run-time value can never be aligned.
12193 if (BaseAlignment
.getQuantity() >= Alignment
&&
12194 PtrAlign
.getQuantity() < Alignment
)
12195 return Success(0, E
);
12196 // Otherwise we can't infer whether the value is sufficiently aligned.
12197 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
12198 // in cases where we can't fully evaluate the pointer.
12199 Info
.FFDiag(E
->getArg(0), diag::note_constexpr_alignment_compute
)
12203 assert(Src
.isInt());
12204 return Success((Src
.getInt() & (Alignment
- 1)) == 0 ? 1 : 0, E
);
12206 case Builtin::BI__builtin_align_up
: {
12209 if (!getBuiltinAlignArguments(E
, Info
, Src
, Alignment
))
12213 APSInt AlignedVal
=
12214 APSInt((Src
.getInt() + (Alignment
- 1)) & ~(Alignment
- 1),
12215 Src
.getInt().isUnsigned());
12216 assert(AlignedVal
.getBitWidth() == Src
.getInt().getBitWidth());
12217 return Success(AlignedVal
, E
);
12219 case Builtin::BI__builtin_align_down
: {
12222 if (!getBuiltinAlignArguments(E
, Info
, Src
, Alignment
))
12226 APSInt AlignedVal
=
12227 APSInt(Src
.getInt() & ~(Alignment
- 1), Src
.getInt().isUnsigned());
12228 assert(AlignedVal
.getBitWidth() == Src
.getInt().getBitWidth());
12229 return Success(AlignedVal
, E
);
12232 case Builtin::BI__builtin_bitreverse8
:
12233 case Builtin::BI__builtin_bitreverse16
:
12234 case Builtin::BI__builtin_bitreverse32
:
12235 case Builtin::BI__builtin_bitreverse64
: {
12237 if (!EvaluateInteger(E
->getArg(0), Val
, Info
))
12240 return Success(Val
.reverseBits(), E
);
12243 case Builtin::BI__builtin_bswap16
:
12244 case Builtin::BI__builtin_bswap32
:
12245 case Builtin::BI__builtin_bswap64
: {
12247 if (!EvaluateInteger(E
->getArg(0), Val
, Info
))
12250 return Success(Val
.byteSwap(), E
);
12253 case Builtin::BI__builtin_classify_type
:
12254 return Success((int)EvaluateBuiltinClassifyType(E
, Info
.getLangOpts()), E
);
12256 case Builtin::BI__builtin_clrsb
:
12257 case Builtin::BI__builtin_clrsbl
:
12258 case Builtin::BI__builtin_clrsbll
: {
12260 if (!EvaluateInteger(E
->getArg(0), Val
, Info
))
12263 return Success(Val
.getBitWidth() - Val
.getSignificantBits(), E
);
12266 case Builtin::BI__builtin_clz
:
12267 case Builtin::BI__builtin_clzl
:
12268 case Builtin::BI__builtin_clzll
:
12269 case Builtin::BI__builtin_clzs
:
12270 case Builtin::BI__lzcnt16
: // Microsoft variants of count leading-zeroes
12271 case Builtin::BI__lzcnt
:
12272 case Builtin::BI__lzcnt64
: {
12274 if (!EvaluateInteger(E
->getArg(0), Val
, Info
))
12277 // When the argument is 0, the result of GCC builtins is undefined, whereas
12278 // for Microsoft intrinsics, the result is the bit-width of the argument.
12279 bool ZeroIsUndefined
= BuiltinOp
!= Builtin::BI__lzcnt16
&&
12280 BuiltinOp
!= Builtin::BI__lzcnt
&&
12281 BuiltinOp
!= Builtin::BI__lzcnt64
;
12283 if (ZeroIsUndefined
&& !Val
)
12286 return Success(Val
.countl_zero(), E
);
12289 case Builtin::BI__builtin_constant_p
: {
12290 const Expr
*Arg
= E
->getArg(0);
12291 if (EvaluateBuiltinConstantP(Info
, Arg
))
12292 return Success(true, E
);
12293 if (Info
.InConstantContext
|| Arg
->HasSideEffects(Info
.Ctx
)) {
12294 // Outside a constant context, eagerly evaluate to false in the presence
12295 // of side-effects in order to avoid -Wunsequenced false-positives in
12296 // a branch on __builtin_constant_p(expr).
12297 return Success(false, E
);
12299 Info
.FFDiag(E
, diag::note_invalid_subexpr_in_const_expr
);
12303 case Builtin::BI__builtin_is_constant_evaluated
: {
12304 const auto *Callee
= Info
.CurrentCall
->getCallee();
12305 if (Info
.InConstantContext
&& !Info
.CheckingPotentialConstantExpression
&&
12306 (Info
.CallStackDepth
== 1 ||
12307 (Info
.CallStackDepth
== 2 && Callee
->isInStdNamespace() &&
12308 Callee
->getIdentifier() &&
12309 Callee
->getIdentifier()->isStr("is_constant_evaluated")))) {
12310 // FIXME: Find a better way to avoid duplicated diagnostics.
12311 if (Info
.EvalStatus
.Diag
)
12312 Info
.report((Info
.CallStackDepth
== 1)
12314 : Info
.CurrentCall
->getCallRange().getBegin(),
12315 diag::warn_is_constant_evaluated_always_true_constexpr
)
12316 << (Info
.CallStackDepth
== 1 ? "__builtin_is_constant_evaluated"
12317 : "std::is_constant_evaluated");
12320 return Success(Info
.InConstantContext
, E
);
12323 case Builtin::BI__builtin_ctz
:
12324 case Builtin::BI__builtin_ctzl
:
12325 case Builtin::BI__builtin_ctzll
:
12326 case Builtin::BI__builtin_ctzs
: {
12328 if (!EvaluateInteger(E
->getArg(0), Val
, Info
))
12333 return Success(Val
.countr_zero(), E
);
12336 case Builtin::BI__builtin_eh_return_data_regno
: {
12337 int Operand
= E
->getArg(0)->EvaluateKnownConstInt(Info
.Ctx
).getZExtValue();
12338 Operand
= Info
.Ctx
.getTargetInfo().getEHDataRegisterNumber(Operand
);
12339 return Success(Operand
, E
);
12342 case Builtin::BI__builtin_expect
:
12343 case Builtin::BI__builtin_expect_with_probability
:
12344 return Visit(E
->getArg(0));
12346 case Builtin::BI__builtin_ffs
:
12347 case Builtin::BI__builtin_ffsl
:
12348 case Builtin::BI__builtin_ffsll
: {
12350 if (!EvaluateInteger(E
->getArg(0), Val
, Info
))
12353 unsigned N
= Val
.countr_zero();
12354 return Success(N
== Val
.getBitWidth() ? 0 : N
+ 1, E
);
12357 case Builtin::BI__builtin_fpclassify
: {
12359 if (!EvaluateFloat(E
->getArg(5), Val
, Info
))
12362 switch (Val
.getCategory()) {
12363 case APFloat::fcNaN
: Arg
= 0; break;
12364 case APFloat::fcInfinity
: Arg
= 1; break;
12365 case APFloat::fcNormal
: Arg
= Val
.isDenormal() ? 3 : 2; break;
12366 case APFloat::fcZero
: Arg
= 4; break;
12368 return Visit(E
->getArg(Arg
));
12371 case Builtin::BI__builtin_isinf_sign
: {
12373 return EvaluateFloat(E
->getArg(0), Val
, Info
) &&
12374 Success(Val
.isInfinity() ? (Val
.isNegative() ? -1 : 1) : 0, E
);
12377 case Builtin::BI__builtin_isinf
: {
12379 return EvaluateFloat(E
->getArg(0), Val
, Info
) &&
12380 Success(Val
.isInfinity() ? 1 : 0, E
);
12383 case Builtin::BI__builtin_isfinite
: {
12385 return EvaluateFloat(E
->getArg(0), Val
, Info
) &&
12386 Success(Val
.isFinite() ? 1 : 0, E
);
12389 case Builtin::BI__builtin_isnan
: {
12391 return EvaluateFloat(E
->getArg(0), Val
, Info
) &&
12392 Success(Val
.isNaN() ? 1 : 0, E
);
12395 case Builtin::BI__builtin_isnormal
: {
12397 return EvaluateFloat(E
->getArg(0), Val
, Info
) &&
12398 Success(Val
.isNormal() ? 1 : 0, E
);
12401 case Builtin::BI__builtin_issubnormal
: {
12403 return EvaluateFloat(E
->getArg(0), Val
, Info
) &&
12404 Success(Val
.isDenormal() ? 1 : 0, E
);
12407 case Builtin::BI__builtin_iszero
: {
12409 return EvaluateFloat(E
->getArg(0), Val
, Info
) &&
12410 Success(Val
.isZero() ? 1 : 0, E
);
12413 case Builtin::BI__builtin_issignaling
: {
12415 return EvaluateFloat(E
->getArg(0), Val
, Info
) &&
12416 Success(Val
.isSignaling() ? 1 : 0, E
);
12419 case Builtin::BI__builtin_isfpclass
: {
12421 if (!EvaluateInteger(E
->getArg(1), MaskVal
, Info
))
12423 unsigned Test
= static_cast<llvm::FPClassTest
>(MaskVal
.getZExtValue());
12425 return EvaluateFloat(E
->getArg(0), Val
, Info
) &&
12426 Success((Val
.classify() & Test
) ? 1 : 0, E
);
12429 case Builtin::BI__builtin_parity
:
12430 case Builtin::BI__builtin_parityl
:
12431 case Builtin::BI__builtin_parityll
: {
12433 if (!EvaluateInteger(E
->getArg(0), Val
, Info
))
12436 return Success(Val
.popcount() % 2, E
);
12439 case Builtin::BI__builtin_popcount
:
12440 case Builtin::BI__builtin_popcountl
:
12441 case Builtin::BI__builtin_popcountll
:
12442 case Builtin::BI__popcnt16
: // Microsoft variants of popcount
12443 case Builtin::BI__popcnt
:
12444 case Builtin::BI__popcnt64
: {
12446 if (!EvaluateInteger(E
->getArg(0), Val
, Info
))
12449 return Success(Val
.popcount(), E
);
12452 case Builtin::BI__builtin_rotateleft8
:
12453 case Builtin::BI__builtin_rotateleft16
:
12454 case Builtin::BI__builtin_rotateleft32
:
12455 case Builtin::BI__builtin_rotateleft64
:
12456 case Builtin::BI_rotl8
: // Microsoft variants of rotate right
12457 case Builtin::BI_rotl16
:
12458 case Builtin::BI_rotl
:
12459 case Builtin::BI_lrotl
:
12460 case Builtin::BI_rotl64
: {
12462 if (!EvaluateInteger(E
->getArg(0), Val
, Info
) ||
12463 !EvaluateInteger(E
->getArg(1), Amt
, Info
))
12466 return Success(Val
.rotl(Amt
.urem(Val
.getBitWidth())), E
);
12469 case Builtin::BI__builtin_rotateright8
:
12470 case Builtin::BI__builtin_rotateright16
:
12471 case Builtin::BI__builtin_rotateright32
:
12472 case Builtin::BI__builtin_rotateright64
:
12473 case Builtin::BI_rotr8
: // Microsoft variants of rotate right
12474 case Builtin::BI_rotr16
:
12475 case Builtin::BI_rotr
:
12476 case Builtin::BI_lrotr
:
12477 case Builtin::BI_rotr64
: {
12479 if (!EvaluateInteger(E
->getArg(0), Val
, Info
) ||
12480 !EvaluateInteger(E
->getArg(1), Amt
, Info
))
12483 return Success(Val
.rotr(Amt
.urem(Val
.getBitWidth())), E
);
12486 case Builtin::BIstrlen
:
12487 case Builtin::BIwcslen
:
12488 // A call to strlen is not a constant expression.
12489 if (Info
.getLangOpts().CPlusPlus11
)
12490 Info
.CCEDiag(E
, diag::note_constexpr_invalid_function
)
12491 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
12492 << ("'" + Info
.Ctx
.BuiltinInfo
.getName(BuiltinOp
) + "'").str();
12494 Info
.CCEDiag(E
, diag::note_invalid_subexpr_in_const_expr
);
12496 case Builtin::BI__builtin_strlen
:
12497 case Builtin::BI__builtin_wcslen
: {
12498 // As an extension, we support __builtin_strlen() as a constant expression,
12499 // and support folding strlen() to a constant.
12501 if (EvaluateBuiltinStrLen(E
->getArg(0), StrLen
, Info
))
12502 return Success(StrLen
, E
);
12506 case Builtin::BIstrcmp
:
12507 case Builtin::BIwcscmp
:
12508 case Builtin::BIstrncmp
:
12509 case Builtin::BIwcsncmp
:
12510 case Builtin::BImemcmp
:
12511 case Builtin::BIbcmp
:
12512 case Builtin::BIwmemcmp
:
12513 // A call to strlen is not a constant expression.
12514 if (Info
.getLangOpts().CPlusPlus11
)
12515 Info
.CCEDiag(E
, diag::note_constexpr_invalid_function
)
12516 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
12517 << ("'" + Info
.Ctx
.BuiltinInfo
.getName(BuiltinOp
) + "'").str();
12519 Info
.CCEDiag(E
, diag::note_invalid_subexpr_in_const_expr
);
12521 case Builtin::BI__builtin_strcmp
:
12522 case Builtin::BI__builtin_wcscmp
:
12523 case Builtin::BI__builtin_strncmp
:
12524 case Builtin::BI__builtin_wcsncmp
:
12525 case Builtin::BI__builtin_memcmp
:
12526 case Builtin::BI__builtin_bcmp
:
12527 case Builtin::BI__builtin_wmemcmp
: {
12528 LValue String1
, String2
;
12529 if (!EvaluatePointer(E
->getArg(0), String1
, Info
) ||
12530 !EvaluatePointer(E
->getArg(1), String2
, Info
))
12533 uint64_t MaxLength
= uint64_t(-1);
12534 if (BuiltinOp
!= Builtin::BIstrcmp
&&
12535 BuiltinOp
!= Builtin::BIwcscmp
&&
12536 BuiltinOp
!= Builtin::BI__builtin_strcmp
&&
12537 BuiltinOp
!= Builtin::BI__builtin_wcscmp
) {
12539 if (!EvaluateInteger(E
->getArg(2), N
, Info
))
12541 MaxLength
= N
.getZExtValue();
12544 // Empty substrings compare equal by definition.
12545 if (MaxLength
== 0u)
12546 return Success(0, E
);
12548 if (!String1
.checkNullPointerForFoldAccess(Info
, E
, AK_Read
) ||
12549 !String2
.checkNullPointerForFoldAccess(Info
, E
, AK_Read
) ||
12550 String1
.Designator
.Invalid
|| String2
.Designator
.Invalid
)
12553 QualType CharTy1
= String1
.Designator
.getType(Info
.Ctx
);
12554 QualType CharTy2
= String2
.Designator
.getType(Info
.Ctx
);
12556 bool IsRawByte
= BuiltinOp
== Builtin::BImemcmp
||
12557 BuiltinOp
== Builtin::BIbcmp
||
12558 BuiltinOp
== Builtin::BI__builtin_memcmp
||
12559 BuiltinOp
== Builtin::BI__builtin_bcmp
;
12561 assert(IsRawByte
||
12562 (Info
.Ctx
.hasSameUnqualifiedType(
12563 CharTy1
, E
->getArg(0)->getType()->getPointeeType()) &&
12564 Info
.Ctx
.hasSameUnqualifiedType(CharTy1
, CharTy2
)));
12566 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
12567 // 'char8_t', but no other types.
12569 !(isOneByteCharacterType(CharTy1
) && isOneByteCharacterType(CharTy2
))) {
12570 // FIXME: Consider using our bit_cast implementation to support this.
12571 Info
.FFDiag(E
, diag::note_constexpr_memcmp_unsupported
)
12572 << ("'" + Info
.Ctx
.BuiltinInfo
.getName(BuiltinOp
) + "'").str()
12573 << CharTy1
<< CharTy2
;
12577 const auto &ReadCurElems
= [&](APValue
&Char1
, APValue
&Char2
) {
12578 return handleLValueToRValueConversion(Info
, E
, CharTy1
, String1
, Char1
) &&
12579 handleLValueToRValueConversion(Info
, E
, CharTy2
, String2
, Char2
) &&
12580 Char1
.isInt() && Char2
.isInt();
12582 const auto &AdvanceElems
= [&] {
12583 return HandleLValueArrayAdjustment(Info
, E
, String1
, CharTy1
, 1) &&
12584 HandleLValueArrayAdjustment(Info
, E
, String2
, CharTy2
, 1);
12588 (BuiltinOp
!= Builtin::BImemcmp
&& BuiltinOp
!= Builtin::BIbcmp
&&
12589 BuiltinOp
!= Builtin::BIwmemcmp
&&
12590 BuiltinOp
!= Builtin::BI__builtin_memcmp
&&
12591 BuiltinOp
!= Builtin::BI__builtin_bcmp
&&
12592 BuiltinOp
!= Builtin::BI__builtin_wmemcmp
);
12593 bool IsWide
= BuiltinOp
== Builtin::BIwcscmp
||
12594 BuiltinOp
== Builtin::BIwcsncmp
||
12595 BuiltinOp
== Builtin::BIwmemcmp
||
12596 BuiltinOp
== Builtin::BI__builtin_wcscmp
||
12597 BuiltinOp
== Builtin::BI__builtin_wcsncmp
||
12598 BuiltinOp
== Builtin::BI__builtin_wmemcmp
;
12600 for (; MaxLength
; --MaxLength
) {
12601 APValue Char1
, Char2
;
12602 if (!ReadCurElems(Char1
, Char2
))
12604 if (Char1
.getInt().ne(Char2
.getInt())) {
12605 if (IsWide
) // wmemcmp compares with wchar_t signedness.
12606 return Success(Char1
.getInt() < Char2
.getInt() ? -1 : 1, E
);
12607 // memcmp always compares unsigned chars.
12608 return Success(Char1
.getInt().ult(Char2
.getInt()) ? -1 : 1, E
);
12610 if (StopAtNull
&& !Char1
.getInt())
12611 return Success(0, E
);
12612 assert(!(StopAtNull
&& !Char2
.getInt()));
12613 if (!AdvanceElems())
12616 // We hit the strncmp / memcmp limit.
12617 return Success(0, E
);
12620 case Builtin::BI__atomic_always_lock_free
:
12621 case Builtin::BI__atomic_is_lock_free
:
12622 case Builtin::BI__c11_atomic_is_lock_free
: {
12624 if (!EvaluateInteger(E
->getArg(0), SizeVal
, Info
))
12627 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
12628 // of two less than or equal to the maximum inline atomic width, we know it
12629 // is lock-free. If the size isn't a power of two, or greater than the
12630 // maximum alignment where we promote atomics, we know it is not lock-free
12631 // (at least not in the sense of atomic_is_lock_free). Otherwise,
12632 // the answer can only be determined at runtime; for example, 16-byte
12633 // atomics have lock-free implementations on some, but not all,
12634 // x86-64 processors.
12636 // Check power-of-two.
12637 CharUnits Size
= CharUnits::fromQuantity(SizeVal
.getZExtValue());
12638 if (Size
.isPowerOfTwo()) {
12639 // Check against inlining width.
12640 unsigned InlineWidthBits
=
12641 Info
.Ctx
.getTargetInfo().getMaxAtomicInlineWidth();
12642 if (Size
<= Info
.Ctx
.toCharUnitsFromBits(InlineWidthBits
)) {
12643 if (BuiltinOp
== Builtin::BI__c11_atomic_is_lock_free
||
12644 Size
== CharUnits::One() ||
12645 E
->getArg(1)->isNullPointerConstant(Info
.Ctx
,
12646 Expr::NPC_NeverValueDependent
))
12647 // OK, we will inline appropriately-aligned operations of this size,
12648 // and _Atomic(T) is appropriately-aligned.
12649 return Success(1, E
);
12651 QualType PointeeType
= E
->getArg(1)->IgnoreImpCasts()->getType()->
12652 castAs
<PointerType
>()->getPointeeType();
12653 if (!PointeeType
->isIncompleteType() &&
12654 Info
.Ctx
.getTypeAlignInChars(PointeeType
) >= Size
) {
12655 // OK, we will inline operations on this object.
12656 return Success(1, E
);
12661 return BuiltinOp
== Builtin::BI__atomic_always_lock_free
?
12662 Success(0, E
) : Error(E
);
12664 case Builtin::BI__builtin_add_overflow
:
12665 case Builtin::BI__builtin_sub_overflow
:
12666 case Builtin::BI__builtin_mul_overflow
:
12667 case Builtin::BI__builtin_sadd_overflow
:
12668 case Builtin::BI__builtin_uadd_overflow
:
12669 case Builtin::BI__builtin_uaddl_overflow
:
12670 case Builtin::BI__builtin_uaddll_overflow
:
12671 case Builtin::BI__builtin_usub_overflow
:
12672 case Builtin::BI__builtin_usubl_overflow
:
12673 case Builtin::BI__builtin_usubll_overflow
:
12674 case Builtin::BI__builtin_umul_overflow
:
12675 case Builtin::BI__builtin_umull_overflow
:
12676 case Builtin::BI__builtin_umulll_overflow
:
12677 case Builtin::BI__builtin_saddl_overflow
:
12678 case Builtin::BI__builtin_saddll_overflow
:
12679 case Builtin::BI__builtin_ssub_overflow
:
12680 case Builtin::BI__builtin_ssubl_overflow
:
12681 case Builtin::BI__builtin_ssubll_overflow
:
12682 case Builtin::BI__builtin_smul_overflow
:
12683 case Builtin::BI__builtin_smull_overflow
:
12684 case Builtin::BI__builtin_smulll_overflow
: {
12685 LValue ResultLValue
;
12688 QualType ResultType
= E
->getArg(2)->getType()->getPointeeType();
12689 if (!EvaluateInteger(E
->getArg(0), LHS
, Info
) ||
12690 !EvaluateInteger(E
->getArg(1), RHS
, Info
) ||
12691 !EvaluatePointer(E
->getArg(2), ResultLValue
, Info
))
12695 bool DidOverflow
= false;
12697 // If the types don't have to match, enlarge all 3 to the largest of them.
12698 if (BuiltinOp
== Builtin::BI__builtin_add_overflow
||
12699 BuiltinOp
== Builtin::BI__builtin_sub_overflow
||
12700 BuiltinOp
== Builtin::BI__builtin_mul_overflow
) {
12701 bool IsSigned
= LHS
.isSigned() || RHS
.isSigned() ||
12702 ResultType
->isSignedIntegerOrEnumerationType();
12703 bool AllSigned
= LHS
.isSigned() && RHS
.isSigned() &&
12704 ResultType
->isSignedIntegerOrEnumerationType();
12705 uint64_t LHSSize
= LHS
.getBitWidth();
12706 uint64_t RHSSize
= RHS
.getBitWidth();
12707 uint64_t ResultSize
= Info
.Ctx
.getTypeSize(ResultType
);
12708 uint64_t MaxBits
= std::max(std::max(LHSSize
, RHSSize
), ResultSize
);
12710 // Add an additional bit if the signedness isn't uniformly agreed to. We
12711 // could do this ONLY if there is a signed and an unsigned that both have
12712 // MaxBits, but the code to check that is pretty nasty. The issue will be
12713 // caught in the shrink-to-result later anyway.
12714 if (IsSigned
&& !AllSigned
)
12717 LHS
= APSInt(LHS
.extOrTrunc(MaxBits
), !IsSigned
);
12718 RHS
= APSInt(RHS
.extOrTrunc(MaxBits
), !IsSigned
);
12719 Result
= APSInt(MaxBits
, !IsSigned
);
12722 // Find largest int.
12723 switch (BuiltinOp
) {
12725 llvm_unreachable("Invalid value for BuiltinOp");
12726 case Builtin::BI__builtin_add_overflow
:
12727 case Builtin::BI__builtin_sadd_overflow
:
12728 case Builtin::BI__builtin_saddl_overflow
:
12729 case Builtin::BI__builtin_saddll_overflow
:
12730 case Builtin::BI__builtin_uadd_overflow
:
12731 case Builtin::BI__builtin_uaddl_overflow
:
12732 case Builtin::BI__builtin_uaddll_overflow
:
12733 Result
= LHS
.isSigned() ? LHS
.sadd_ov(RHS
, DidOverflow
)
12734 : LHS
.uadd_ov(RHS
, DidOverflow
);
12736 case Builtin::BI__builtin_sub_overflow
:
12737 case Builtin::BI__builtin_ssub_overflow
:
12738 case Builtin::BI__builtin_ssubl_overflow
:
12739 case Builtin::BI__builtin_ssubll_overflow
:
12740 case Builtin::BI__builtin_usub_overflow
:
12741 case Builtin::BI__builtin_usubl_overflow
:
12742 case Builtin::BI__builtin_usubll_overflow
:
12743 Result
= LHS
.isSigned() ? LHS
.ssub_ov(RHS
, DidOverflow
)
12744 : LHS
.usub_ov(RHS
, DidOverflow
);
12746 case Builtin::BI__builtin_mul_overflow
:
12747 case Builtin::BI__builtin_smul_overflow
:
12748 case Builtin::BI__builtin_smull_overflow
:
12749 case Builtin::BI__builtin_smulll_overflow
:
12750 case Builtin::BI__builtin_umul_overflow
:
12751 case Builtin::BI__builtin_umull_overflow
:
12752 case Builtin::BI__builtin_umulll_overflow
:
12753 Result
= LHS
.isSigned() ? LHS
.smul_ov(RHS
, DidOverflow
)
12754 : LHS
.umul_ov(RHS
, DidOverflow
);
12758 // In the case where multiple sizes are allowed, truncate and see if
12759 // the values are the same.
12760 if (BuiltinOp
== Builtin::BI__builtin_add_overflow
||
12761 BuiltinOp
== Builtin::BI__builtin_sub_overflow
||
12762 BuiltinOp
== Builtin::BI__builtin_mul_overflow
) {
12763 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12764 // since it will give us the behavior of a TruncOrSelf in the case where
12765 // its parameter <= its size. We previously set Result to be at least the
12766 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12767 // will work exactly like TruncOrSelf.
12768 APSInt Temp
= Result
.extOrTrunc(Info
.Ctx
.getTypeSize(ResultType
));
12769 Temp
.setIsSigned(ResultType
->isSignedIntegerOrEnumerationType());
12771 if (!APSInt::isSameValue(Temp
, Result
))
12772 DidOverflow
= true;
12776 APValue APV
{Result
};
12777 if (!handleAssignment(Info
, E
, ResultLValue
, ResultType
, APV
))
12779 return Success(DidOverflow
, E
);
12784 /// Determine whether this is a pointer past the end of the complete
12785 /// object referred to by the lvalue.
12786 static bool isOnePastTheEndOfCompleteObject(const ASTContext
&Ctx
,
12787 const LValue
&LV
) {
12788 // A null pointer can be viewed as being "past the end" but we don't
12789 // choose to look at it that way here.
12790 if (!LV
.getLValueBase())
12793 // If the designator is valid and refers to a subobject, we're not pointing
12795 if (!LV
.getLValueDesignator().Invalid
&&
12796 !LV
.getLValueDesignator().isOnePastTheEnd())
12799 // A pointer to an incomplete type might be past-the-end if the type's size is
12800 // zero. We cannot tell because the type is incomplete.
12801 QualType Ty
= getType(LV
.getLValueBase());
12802 if (Ty
->isIncompleteType())
12805 // We're a past-the-end pointer if we point to the byte after the object,
12806 // no matter what our type or path is.
12807 auto Size
= Ctx
.getTypeSizeInChars(Ty
);
12808 return LV
.getLValueOffset() == Size
;
12813 /// Data recursive integer evaluator of certain binary operators.
12815 /// We use a data recursive algorithm for binary operators so that we are able
12816 /// to handle extreme cases of chained binary operators without causing stack
12818 class DataRecursiveIntBinOpEvaluator
{
12819 struct EvalResult
{
12821 bool Failed
= false;
12823 EvalResult() = default;
12825 void swap(EvalResult
&RHS
) {
12827 Failed
= RHS
.Failed
;
12828 RHS
.Failed
= false;
12834 EvalResult LHSResult
; // meaningful only for binary operator expression.
12835 enum { AnyExprKind
, BinOpKind
, BinOpVisitedLHSKind
} Kind
;
12838 Job(Job
&&) = default;
12840 void startSpeculativeEval(EvalInfo
&Info
) {
12841 SpecEvalRAII
= SpeculativeEvaluationRAII(Info
);
12845 SpeculativeEvaluationRAII SpecEvalRAII
;
12848 SmallVector
<Job
, 16> Queue
;
12850 IntExprEvaluator
&IntEval
;
12852 APValue
&FinalResult
;
12855 DataRecursiveIntBinOpEvaluator(IntExprEvaluator
&IntEval
, APValue
&Result
)
12856 : IntEval(IntEval
), Info(IntEval
.getEvalInfo()), FinalResult(Result
) { }
12858 /// True if \param E is a binary operator that we are going to handle
12859 /// data recursively.
12860 /// We handle binary operators that are comma, logical, or that have operands
12861 /// with integral or enumeration type.
12862 static bool shouldEnqueue(const BinaryOperator
*E
) {
12863 return E
->getOpcode() == BO_Comma
|| E
->isLogicalOp() ||
12864 (E
->isPRValue() && E
->getType()->isIntegralOrEnumerationType() &&
12865 E
->getLHS()->getType()->isIntegralOrEnumerationType() &&
12866 E
->getRHS()->getType()->isIntegralOrEnumerationType());
12869 bool Traverse(const BinaryOperator
*E
) {
12871 EvalResult PrevResult
;
12872 while (!Queue
.empty())
12873 process(PrevResult
);
12875 if (PrevResult
.Failed
) return false;
12877 FinalResult
.swap(PrevResult
.Val
);
12882 bool Success(uint64_t Value
, const Expr
*E
, APValue
&Result
) {
12883 return IntEval
.Success(Value
, E
, Result
);
12885 bool Success(const APSInt
&Value
, const Expr
*E
, APValue
&Result
) {
12886 return IntEval
.Success(Value
, E
, Result
);
12888 bool Error(const Expr
*E
) {
12889 return IntEval
.Error(E
);
12891 bool Error(const Expr
*E
, diag::kind D
) {
12892 return IntEval
.Error(E
, D
);
12895 OptionalDiagnostic
CCEDiag(const Expr
*E
, diag::kind D
) {
12896 return Info
.CCEDiag(E
, D
);
12899 // Returns true if visiting the RHS is necessary, false otherwise.
12900 bool VisitBinOpLHSOnly(EvalResult
&LHSResult
, const BinaryOperator
*E
,
12901 bool &SuppressRHSDiags
);
12903 bool VisitBinOp(const EvalResult
&LHSResult
, const EvalResult
&RHSResult
,
12904 const BinaryOperator
*E
, APValue
&Result
);
12906 void EvaluateExpr(const Expr
*E
, EvalResult
&Result
) {
12907 Result
.Failed
= !Evaluate(Result
.Val
, Info
, E
);
12909 Result
.Val
= APValue();
12912 void process(EvalResult
&Result
);
12914 void enqueue(const Expr
*E
) {
12915 E
= E
->IgnoreParens();
12916 Queue
.resize(Queue
.size()+1);
12917 Queue
.back().E
= E
;
12918 Queue
.back().Kind
= Job::AnyExprKind
;
12924 bool DataRecursiveIntBinOpEvaluator::
12925 VisitBinOpLHSOnly(EvalResult
&LHSResult
, const BinaryOperator
*E
,
12926 bool &SuppressRHSDiags
) {
12927 if (E
->getOpcode() == BO_Comma
) {
12928 // Ignore LHS but note if we could not evaluate it.
12929 if (LHSResult
.Failed
)
12930 return Info
.noteSideEffect();
12934 if (E
->isLogicalOp()) {
12936 if (!LHSResult
.Failed
&& HandleConversionToBool(LHSResult
.Val
, LHSAsBool
)) {
12937 // We were able to evaluate the LHS, see if we can get away with not
12938 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12939 if (LHSAsBool
== (E
->getOpcode() == BO_LOr
)) {
12940 Success(LHSAsBool
, E
, LHSResult
.Val
);
12941 return false; // Ignore RHS
12944 LHSResult
.Failed
= true;
12946 // Since we weren't able to evaluate the left hand side, it
12947 // might have had side effects.
12948 if (!Info
.noteSideEffect())
12951 // We can't evaluate the LHS; however, sometimes the result
12952 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12953 // Don't ignore RHS and suppress diagnostics from this arm.
12954 SuppressRHSDiags
= true;
12960 assert(E
->getLHS()->getType()->isIntegralOrEnumerationType() &&
12961 E
->getRHS()->getType()->isIntegralOrEnumerationType());
12963 if (LHSResult
.Failed
&& !Info
.noteFailure())
12964 return false; // Ignore RHS;
12969 static void addOrSubLValueAsInteger(APValue
&LVal
, const APSInt
&Index
,
12971 // Compute the new offset in the appropriate width, wrapping at 64 bits.
12972 // FIXME: When compiling for a 32-bit target, we should use 32-bit
12974 assert(!LVal
.hasLValuePath() && "have designator for integer lvalue");
12975 CharUnits
&Offset
= LVal
.getLValueOffset();
12976 uint64_t Offset64
= Offset
.getQuantity();
12977 uint64_t Index64
= Index
.extOrTrunc(64).getZExtValue();
12978 Offset
= CharUnits::fromQuantity(IsSub
? Offset64
- Index64
12979 : Offset64
+ Index64
);
12982 bool DataRecursiveIntBinOpEvaluator::
12983 VisitBinOp(const EvalResult
&LHSResult
, const EvalResult
&RHSResult
,
12984 const BinaryOperator
*E
, APValue
&Result
) {
12985 if (E
->getOpcode() == BO_Comma
) {
12986 if (RHSResult
.Failed
)
12988 Result
= RHSResult
.Val
;
12992 if (E
->isLogicalOp()) {
12993 bool lhsResult
, rhsResult
;
12994 bool LHSIsOK
= HandleConversionToBool(LHSResult
.Val
, lhsResult
);
12995 bool RHSIsOK
= HandleConversionToBool(RHSResult
.Val
, rhsResult
);
12999 if (E
->getOpcode() == BO_LOr
)
13000 return Success(lhsResult
|| rhsResult
, E
, Result
);
13002 return Success(lhsResult
&& rhsResult
, E
, Result
);
13006 // We can't evaluate the LHS; however, sometimes the result
13007 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
13008 if (rhsResult
== (E
->getOpcode() == BO_LOr
))
13009 return Success(rhsResult
, E
, Result
);
13016 assert(E
->getLHS()->getType()->isIntegralOrEnumerationType() &&
13017 E
->getRHS()->getType()->isIntegralOrEnumerationType());
13019 if (LHSResult
.Failed
|| RHSResult
.Failed
)
13022 const APValue
&LHSVal
= LHSResult
.Val
;
13023 const APValue
&RHSVal
= RHSResult
.Val
;
13025 // Handle cases like (unsigned long)&a + 4.
13026 if (E
->isAdditiveOp() && LHSVal
.isLValue() && RHSVal
.isInt()) {
13028 addOrSubLValueAsInteger(Result
, RHSVal
.getInt(), E
->getOpcode() == BO_Sub
);
13032 // Handle cases like 4 + (unsigned long)&a
13033 if (E
->getOpcode() == BO_Add
&&
13034 RHSVal
.isLValue() && LHSVal
.isInt()) {
13036 addOrSubLValueAsInteger(Result
, LHSVal
.getInt(), /*IsSub*/false);
13040 if (E
->getOpcode() == BO_Sub
&& LHSVal
.isLValue() && RHSVal
.isLValue()) {
13041 // Handle (intptr_t)&&A - (intptr_t)&&B.
13042 if (!LHSVal
.getLValueOffset().isZero() ||
13043 !RHSVal
.getLValueOffset().isZero())
13045 const Expr
*LHSExpr
= LHSVal
.getLValueBase().dyn_cast
<const Expr
*>();
13046 const Expr
*RHSExpr
= RHSVal
.getLValueBase().dyn_cast
<const Expr
*>();
13047 if (!LHSExpr
|| !RHSExpr
)
13049 const AddrLabelExpr
*LHSAddrExpr
= dyn_cast
<AddrLabelExpr
>(LHSExpr
);
13050 const AddrLabelExpr
*RHSAddrExpr
= dyn_cast
<AddrLabelExpr
>(RHSExpr
);
13051 if (!LHSAddrExpr
|| !RHSAddrExpr
)
13053 // Make sure both labels come from the same function.
13054 if (LHSAddrExpr
->getLabel()->getDeclContext() !=
13055 RHSAddrExpr
->getLabel()->getDeclContext())
13057 Result
= APValue(LHSAddrExpr
, RHSAddrExpr
);
13061 // All the remaining cases expect both operands to be an integer
13062 if (!LHSVal
.isInt() || !RHSVal
.isInt())
13065 // Set up the width and signedness manually, in case it can't be deduced
13066 // from the operation we're performing.
13067 // FIXME: Don't do this in the cases where we can deduce it.
13068 APSInt
Value(Info
.Ctx
.getIntWidth(E
->getType()),
13069 E
->getType()->isUnsignedIntegerOrEnumerationType());
13070 if (!handleIntIntBinOp(Info
, E
, LHSVal
.getInt(), E
->getOpcode(),
13071 RHSVal
.getInt(), Value
))
13073 return Success(Value
, E
, Result
);
13076 void DataRecursiveIntBinOpEvaluator::process(EvalResult
&Result
) {
13077 Job
&job
= Queue
.back();
13079 switch (job
.Kind
) {
13080 case Job::AnyExprKind
: {
13081 if (const BinaryOperator
*Bop
= dyn_cast
<BinaryOperator
>(job
.E
)) {
13082 if (shouldEnqueue(Bop
)) {
13083 job
.Kind
= Job::BinOpKind
;
13084 enqueue(Bop
->getLHS());
13089 EvaluateExpr(job
.E
, Result
);
13094 case Job::BinOpKind
: {
13095 const BinaryOperator
*Bop
= cast
<BinaryOperator
>(job
.E
);
13096 bool SuppressRHSDiags
= false;
13097 if (!VisitBinOpLHSOnly(Result
, Bop
, SuppressRHSDiags
)) {
13101 if (SuppressRHSDiags
)
13102 job
.startSpeculativeEval(Info
);
13103 job
.LHSResult
.swap(Result
);
13104 job
.Kind
= Job::BinOpVisitedLHSKind
;
13105 enqueue(Bop
->getRHS());
13109 case Job::BinOpVisitedLHSKind
: {
13110 const BinaryOperator
*Bop
= cast
<BinaryOperator
>(job
.E
);
13113 Result
.Failed
= !VisitBinOp(job
.LHSResult
, RHS
, Bop
, Result
.Val
);
13119 llvm_unreachable("Invalid Job::Kind!");
13123 enum class CmpResult
{
13132 template <class SuccessCB
, class AfterCB
>
13134 EvaluateComparisonBinaryOperator(EvalInfo
&Info
, const BinaryOperator
*E
,
13135 SuccessCB
&&Success
, AfterCB
&&DoAfter
) {
13136 assert(!E
->isValueDependent());
13137 assert(E
->isComparisonOp() && "expected comparison operator");
13138 assert((E
->getOpcode() == BO_Cmp
||
13139 E
->getType()->isIntegralOrEnumerationType()) &&
13140 "unsupported binary expression evaluation");
13141 auto Error
= [&](const Expr
*E
) {
13142 Info
.FFDiag(E
, diag::note_invalid_subexpr_in_const_expr
);
13146 bool IsRelational
= E
->isRelationalOp() || E
->getOpcode() == BO_Cmp
;
13147 bool IsEquality
= E
->isEqualityOp();
13149 QualType LHSTy
= E
->getLHS()->getType();
13150 QualType RHSTy
= E
->getRHS()->getType();
13152 if (LHSTy
->isIntegralOrEnumerationType() &&
13153 RHSTy
->isIntegralOrEnumerationType()) {
13155 bool LHSOK
= EvaluateInteger(E
->getLHS(), LHS
, Info
);
13156 if (!LHSOK
&& !Info
.noteFailure())
13158 if (!EvaluateInteger(E
->getRHS(), RHS
, Info
) || !LHSOK
)
13161 return Success(CmpResult::Less
, E
);
13163 return Success(CmpResult::Greater
, E
);
13164 return Success(CmpResult::Equal
, E
);
13167 if (LHSTy
->isFixedPointType() || RHSTy
->isFixedPointType()) {
13168 APFixedPoint
LHSFX(Info
.Ctx
.getFixedPointSemantics(LHSTy
));
13169 APFixedPoint
RHSFX(Info
.Ctx
.getFixedPointSemantics(RHSTy
));
13171 bool LHSOK
= EvaluateFixedPointOrInteger(E
->getLHS(), LHSFX
, Info
);
13172 if (!LHSOK
&& !Info
.noteFailure())
13174 if (!EvaluateFixedPointOrInteger(E
->getRHS(), RHSFX
, Info
) || !LHSOK
)
13177 return Success(CmpResult::Less
, E
);
13179 return Success(CmpResult::Greater
, E
);
13180 return Success(CmpResult::Equal
, E
);
13183 if (LHSTy
->isAnyComplexType() || RHSTy
->isAnyComplexType()) {
13184 ComplexValue LHS
, RHS
;
13186 if (E
->isAssignmentOp()) {
13188 EvaluateLValue(E
->getLHS(), LV
, Info
);
13190 } else if (LHSTy
->isRealFloatingType()) {
13191 LHSOK
= EvaluateFloat(E
->getLHS(), LHS
.FloatReal
, Info
);
13193 LHS
.makeComplexFloat();
13194 LHS
.FloatImag
= APFloat(LHS
.FloatReal
.getSemantics());
13197 LHSOK
= EvaluateComplex(E
->getLHS(), LHS
, Info
);
13199 if (!LHSOK
&& !Info
.noteFailure())
13202 if (E
->getRHS()->getType()->isRealFloatingType()) {
13203 if (!EvaluateFloat(E
->getRHS(), RHS
.FloatReal
, Info
) || !LHSOK
)
13205 RHS
.makeComplexFloat();
13206 RHS
.FloatImag
= APFloat(RHS
.FloatReal
.getSemantics());
13207 } else if (!EvaluateComplex(E
->getRHS(), RHS
, Info
) || !LHSOK
)
13210 if (LHS
.isComplexFloat()) {
13211 APFloat::cmpResult CR_r
=
13212 LHS
.getComplexFloatReal().compare(RHS
.getComplexFloatReal());
13213 APFloat::cmpResult CR_i
=
13214 LHS
.getComplexFloatImag().compare(RHS
.getComplexFloatImag());
13215 bool IsEqual
= CR_r
== APFloat::cmpEqual
&& CR_i
== APFloat::cmpEqual
;
13216 return Success(IsEqual
? CmpResult::Equal
: CmpResult::Unequal
, E
);
13218 assert(IsEquality
&& "invalid complex comparison");
13219 bool IsEqual
= LHS
.getComplexIntReal() == RHS
.getComplexIntReal() &&
13220 LHS
.getComplexIntImag() == RHS
.getComplexIntImag();
13221 return Success(IsEqual
? CmpResult::Equal
: CmpResult::Unequal
, E
);
13225 if (LHSTy
->isRealFloatingType() &&
13226 RHSTy
->isRealFloatingType()) {
13227 APFloat
RHS(0.0), LHS(0.0);
13229 bool LHSOK
= EvaluateFloat(E
->getRHS(), RHS
, Info
);
13230 if (!LHSOK
&& !Info
.noteFailure())
13233 if (!EvaluateFloat(E
->getLHS(), LHS
, Info
) || !LHSOK
)
13236 assert(E
->isComparisonOp() && "Invalid binary operator!");
13237 llvm::APFloatBase::cmpResult APFloatCmpResult
= LHS
.compare(RHS
);
13238 if (!Info
.InConstantContext
&&
13239 APFloatCmpResult
== APFloat::cmpUnordered
&&
13240 E
->getFPFeaturesInEffect(Info
.Ctx
.getLangOpts()).isFPConstrained()) {
13241 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
13242 Info
.FFDiag(E
, diag::note_constexpr_float_arithmetic_strict
);
13245 auto GetCmpRes
= [&]() {
13246 switch (APFloatCmpResult
) {
13247 case APFloat::cmpEqual
:
13248 return CmpResult::Equal
;
13249 case APFloat::cmpLessThan
:
13250 return CmpResult::Less
;
13251 case APFloat::cmpGreaterThan
:
13252 return CmpResult::Greater
;
13253 case APFloat::cmpUnordered
:
13254 return CmpResult::Unordered
;
13256 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
13258 return Success(GetCmpRes(), E
);
13261 if (LHSTy
->isPointerType() && RHSTy
->isPointerType()) {
13262 LValue LHSValue
, RHSValue
;
13264 bool LHSOK
= EvaluatePointer(E
->getLHS(), LHSValue
, Info
);
13265 if (!LHSOK
&& !Info
.noteFailure())
13268 if (!EvaluatePointer(E
->getRHS(), RHSValue
, Info
) || !LHSOK
)
13271 // Reject differing bases from the normal codepath; we special-case
13272 // comparisons to null.
13273 if (!HasSameBase(LHSValue
, RHSValue
)) {
13274 auto DiagComparison
= [&] (unsigned DiagID
, bool Reversed
= false) {
13275 std::string LHS
= LHSValue
.toString(Info
.Ctx
, E
->getLHS()->getType());
13276 std::string RHS
= RHSValue
.toString(Info
.Ctx
, E
->getRHS()->getType());
13277 Info
.FFDiag(E
, DiagID
)
13278 << (Reversed
? RHS
: LHS
) << (Reversed
? LHS
: RHS
);
13281 // Inequalities and subtractions between unrelated pointers have
13282 // unspecified or undefined behavior.
13284 return DiagComparison(
13285 diag::note_constexpr_pointer_comparison_unspecified
);
13286 // A constant address may compare equal to the address of a symbol.
13287 // The one exception is that address of an object cannot compare equal
13288 // to a null pointer constant.
13289 // TODO: Should we restrict this to actual null pointers, and exclude the
13290 // case of zero cast to pointer type?
13291 if ((!LHSValue
.Base
&& !LHSValue
.Offset
.isZero()) ||
13292 (!RHSValue
.Base
&& !RHSValue
.Offset
.isZero()))
13293 return DiagComparison(diag::note_constexpr_pointer_constant_comparison
,
13295 // It's implementation-defined whether distinct literals will have
13296 // distinct addresses. In clang, the result of such a comparison is
13297 // unspecified, so it is not a constant expression. However, we do know
13298 // that the address of a literal will be non-null.
13299 if ((IsLiteralLValue(LHSValue
) || IsLiteralLValue(RHSValue
)) &&
13300 LHSValue
.Base
&& RHSValue
.Base
)
13301 return DiagComparison(diag::note_constexpr_literal_comparison
);
13302 // We can't tell whether weak symbols will end up pointing to the same
13304 if (IsWeakLValue(LHSValue
) || IsWeakLValue(RHSValue
))
13305 return DiagComparison(diag::note_constexpr_pointer_weak_comparison
,
13306 !IsWeakLValue(LHSValue
));
13307 // We can't compare the address of the start of one object with the
13308 // past-the-end address of another object, per C++ DR1652.
13309 if (LHSValue
.Base
&& LHSValue
.Offset
.isZero() &&
13310 isOnePastTheEndOfCompleteObject(Info
.Ctx
, RHSValue
))
13311 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end
,
13313 if (RHSValue
.Base
&& RHSValue
.Offset
.isZero() &&
13314 isOnePastTheEndOfCompleteObject(Info
.Ctx
, LHSValue
))
13315 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end
,
13317 // We can't tell whether an object is at the same address as another
13318 // zero sized object.
13319 if ((RHSValue
.Base
&& isZeroSized(LHSValue
)) ||
13320 (LHSValue
.Base
&& isZeroSized(RHSValue
)))
13321 return DiagComparison(
13322 diag::note_constexpr_pointer_comparison_zero_sized
);
13323 return Success(CmpResult::Unequal
, E
);
13326 const CharUnits
&LHSOffset
= LHSValue
.getLValueOffset();
13327 const CharUnits
&RHSOffset
= RHSValue
.getLValueOffset();
13329 SubobjectDesignator
&LHSDesignator
= LHSValue
.getLValueDesignator();
13330 SubobjectDesignator
&RHSDesignator
= RHSValue
.getLValueDesignator();
13332 // C++11 [expr.rel]p3:
13333 // Pointers to void (after pointer conversions) can be compared, with a
13334 // result defined as follows: If both pointers represent the same
13335 // address or are both the null pointer value, the result is true if the
13336 // operator is <= or >= and false otherwise; otherwise the result is
13338 // We interpret this as applying to pointers to *cv* void.
13339 if (LHSTy
->isVoidPointerType() && LHSOffset
!= RHSOffset
&& IsRelational
)
13340 Info
.CCEDiag(E
, diag::note_constexpr_void_comparison
);
13342 // C++11 [expr.rel]p2:
13343 // - If two pointers point to non-static data members of the same object,
13344 // or to subobjects or array elements fo such members, recursively, the
13345 // pointer to the later declared member compares greater provided the
13346 // two members have the same access control and provided their class is
13349 // - Otherwise pointer comparisons are unspecified.
13350 if (!LHSDesignator
.Invalid
&& !RHSDesignator
.Invalid
&& IsRelational
) {
13351 bool WasArrayIndex
;
13352 unsigned Mismatch
= FindDesignatorMismatch(
13353 getType(LHSValue
.Base
), LHSDesignator
, RHSDesignator
, WasArrayIndex
);
13354 // At the point where the designators diverge, the comparison has a
13355 // specified value if:
13356 // - we are comparing array indices
13357 // - we are comparing fields of a union, or fields with the same access
13358 // Otherwise, the result is unspecified and thus the comparison is not a
13359 // constant expression.
13360 if (!WasArrayIndex
&& Mismatch
< LHSDesignator
.Entries
.size() &&
13361 Mismatch
< RHSDesignator
.Entries
.size()) {
13362 const FieldDecl
*LF
= getAsField(LHSDesignator
.Entries
[Mismatch
]);
13363 const FieldDecl
*RF
= getAsField(RHSDesignator
.Entries
[Mismatch
]);
13365 Info
.CCEDiag(E
, diag::note_constexpr_pointer_comparison_base_classes
);
13367 Info
.CCEDiag(E
, diag::note_constexpr_pointer_comparison_base_field
)
13368 << getAsBaseClass(LHSDesignator
.Entries
[Mismatch
])
13369 << RF
->getParent() << RF
;
13371 Info
.CCEDiag(E
, diag::note_constexpr_pointer_comparison_base_field
)
13372 << getAsBaseClass(RHSDesignator
.Entries
[Mismatch
])
13373 << LF
->getParent() << LF
;
13374 else if (!LF
->getParent()->isUnion() &&
13375 LF
->getAccess() != RF
->getAccess())
13377 diag::note_constexpr_pointer_comparison_differing_access
)
13378 << LF
<< LF
->getAccess() << RF
<< RF
->getAccess()
13379 << LF
->getParent();
13383 // The comparison here must be unsigned, and performed with the same
13384 // width as the pointer.
13385 unsigned PtrSize
= Info
.Ctx
.getTypeSize(LHSTy
);
13386 uint64_t CompareLHS
= LHSOffset
.getQuantity();
13387 uint64_t CompareRHS
= RHSOffset
.getQuantity();
13388 assert(PtrSize
<= 64 && "Unexpected pointer width");
13389 uint64_t Mask
= ~0ULL >> (64 - PtrSize
);
13390 CompareLHS
&= Mask
;
13391 CompareRHS
&= Mask
;
13393 // If there is a base and this is a relational operator, we can only
13394 // compare pointers within the object in question; otherwise, the result
13395 // depends on where the object is located in memory.
13396 if (!LHSValue
.Base
.isNull() && IsRelational
) {
13397 QualType BaseTy
= getType(LHSValue
.Base
);
13398 if (BaseTy
->isIncompleteType())
13400 CharUnits Size
= Info
.Ctx
.getTypeSizeInChars(BaseTy
);
13401 uint64_t OffsetLimit
= Size
.getQuantity();
13402 if (CompareLHS
> OffsetLimit
|| CompareRHS
> OffsetLimit
)
13406 if (CompareLHS
< CompareRHS
)
13407 return Success(CmpResult::Less
, E
);
13408 if (CompareLHS
> CompareRHS
)
13409 return Success(CmpResult::Greater
, E
);
13410 return Success(CmpResult::Equal
, E
);
13413 if (LHSTy
->isMemberPointerType()) {
13414 assert(IsEquality
&& "unexpected member pointer operation");
13415 assert(RHSTy
->isMemberPointerType() && "invalid comparison");
13417 MemberPtr LHSValue
, RHSValue
;
13419 bool LHSOK
= EvaluateMemberPointer(E
->getLHS(), LHSValue
, Info
);
13420 if (!LHSOK
&& !Info
.noteFailure())
13423 if (!EvaluateMemberPointer(E
->getRHS(), RHSValue
, Info
) || !LHSOK
)
13426 // If either operand is a pointer to a weak function, the comparison is not
13428 if (LHSValue
.getDecl() && LHSValue
.getDecl()->isWeak()) {
13429 Info
.FFDiag(E
, diag::note_constexpr_mem_pointer_weak_comparison
)
13430 << LHSValue
.getDecl();
13433 if (RHSValue
.getDecl() && RHSValue
.getDecl()->isWeak()) {
13434 Info
.FFDiag(E
, diag::note_constexpr_mem_pointer_weak_comparison
)
13435 << RHSValue
.getDecl();
13439 // C++11 [expr.eq]p2:
13440 // If both operands are null, they compare equal. Otherwise if only one is
13441 // null, they compare unequal.
13442 if (!LHSValue
.getDecl() || !RHSValue
.getDecl()) {
13443 bool Equal
= !LHSValue
.getDecl() && !RHSValue
.getDecl();
13444 return Success(Equal
? CmpResult::Equal
: CmpResult::Unequal
, E
);
13447 // Otherwise if either is a pointer to a virtual member function, the
13448 // result is unspecified.
13449 if (const CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(LHSValue
.getDecl()))
13450 if (MD
->isVirtual())
13451 Info
.CCEDiag(E
, diag::note_constexpr_compare_virtual_mem_ptr
) << MD
;
13452 if (const CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(RHSValue
.getDecl()))
13453 if (MD
->isVirtual())
13454 Info
.CCEDiag(E
, diag::note_constexpr_compare_virtual_mem_ptr
) << MD
;
13456 // Otherwise they compare equal if and only if they would refer to the
13457 // same member of the same most derived object or the same subobject if
13458 // they were dereferenced with a hypothetical object of the associated
13460 bool Equal
= LHSValue
== RHSValue
;
13461 return Success(Equal
? CmpResult::Equal
: CmpResult::Unequal
, E
);
13464 if (LHSTy
->isNullPtrType()) {
13465 assert(E
->isComparisonOp() && "unexpected nullptr operation");
13466 assert(RHSTy
->isNullPtrType() && "missing pointer conversion");
13467 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
13468 // are compared, the result is true of the operator is <=, >= or ==, and
13469 // false otherwise.
13471 if (!EvaluatePointer(E
->getLHS(), Res
, Info
) ||
13472 !EvaluatePointer(E
->getRHS(), Res
, Info
))
13474 return Success(CmpResult::Equal
, E
);
13480 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator
*E
) {
13481 if (!CheckLiteralType(Info
, E
))
13484 auto OnSuccess
= [&](CmpResult CR
, const BinaryOperator
*E
) {
13485 ComparisonCategoryResult CCR
;
13487 case CmpResult::Unequal
:
13488 llvm_unreachable("should never produce Unequal for three-way comparison");
13489 case CmpResult::Less
:
13490 CCR
= ComparisonCategoryResult::Less
;
13492 case CmpResult::Equal
:
13493 CCR
= ComparisonCategoryResult::Equal
;
13495 case CmpResult::Greater
:
13496 CCR
= ComparisonCategoryResult::Greater
;
13498 case CmpResult::Unordered
:
13499 CCR
= ComparisonCategoryResult::Unordered
;
13502 // Evaluation succeeded. Lookup the information for the comparison category
13503 // type and fetch the VarDecl for the result.
13504 const ComparisonCategoryInfo
&CmpInfo
=
13505 Info
.Ctx
.CompCategories
.getInfoForType(E
->getType());
13506 const VarDecl
*VD
= CmpInfo
.getValueInfo(CmpInfo
.makeWeakResult(CCR
))->VD
;
13507 // Check and evaluate the result as a constant expression.
13510 if (!handleLValueToRValueConversion(Info
, E
, E
->getType(), LV
, Result
))
13512 return CheckConstantExpression(Info
, E
->getExprLoc(), E
->getType(), Result
,
13513 ConstantExprKind::Normal
);
13515 return EvaluateComparisonBinaryOperator(Info
, E
, OnSuccess
, [&]() {
13516 return ExprEvaluatorBaseTy::VisitBinCmp(E
);
13520 bool RecordExprEvaluator::VisitCXXParenListInitExpr(
13521 const CXXParenListInitExpr
*E
) {
13522 return VisitCXXParenListOrInitListExpr(E
, E
->getInitExprs());
13525 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator
*E
) {
13526 // We don't support assignment in C. C++ assignments don't get here because
13527 // assignment is an lvalue in C++.
13528 if (E
->isAssignmentOp()) {
13530 if (!Info
.noteFailure())
13534 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E
))
13535 return DataRecursiveIntBinOpEvaluator(*this, Result
).Traverse(E
);
13537 assert((!E
->getLHS()->getType()->isIntegralOrEnumerationType() ||
13538 !E
->getRHS()->getType()->isIntegralOrEnumerationType()) &&
13539 "DataRecursiveIntBinOpEvaluator should have handled integral types");
13541 if (E
->isComparisonOp()) {
13542 // Evaluate builtin binary comparisons by evaluating them as three-way
13543 // comparisons and then translating the result.
13544 auto OnSuccess
= [&](CmpResult CR
, const BinaryOperator
*E
) {
13545 assert((CR
!= CmpResult::Unequal
|| E
->isEqualityOp()) &&
13546 "should only produce Unequal for equality comparisons");
13547 bool IsEqual
= CR
== CmpResult::Equal
,
13548 IsLess
= CR
== CmpResult::Less
,
13549 IsGreater
= CR
== CmpResult::Greater
;
13550 auto Op
= E
->getOpcode();
13553 llvm_unreachable("unsupported binary operator");
13556 return Success(IsEqual
== (Op
== BO_EQ
), E
);
13558 return Success(IsLess
, E
);
13560 return Success(IsGreater
, E
);
13562 return Success(IsEqual
|| IsLess
, E
);
13564 return Success(IsEqual
|| IsGreater
, E
);
13567 return EvaluateComparisonBinaryOperator(Info
, E
, OnSuccess
, [&]() {
13568 return ExprEvaluatorBaseTy::VisitBinaryOperator(E
);
13572 QualType LHSTy
= E
->getLHS()->getType();
13573 QualType RHSTy
= E
->getRHS()->getType();
13575 if (LHSTy
->isPointerType() && RHSTy
->isPointerType() &&
13576 E
->getOpcode() == BO_Sub
) {
13577 LValue LHSValue
, RHSValue
;
13579 bool LHSOK
= EvaluatePointer(E
->getLHS(), LHSValue
, Info
);
13580 if (!LHSOK
&& !Info
.noteFailure())
13583 if (!EvaluatePointer(E
->getRHS(), RHSValue
, Info
) || !LHSOK
)
13586 // Reject differing bases from the normal codepath; we special-case
13587 // comparisons to null.
13588 if (!HasSameBase(LHSValue
, RHSValue
)) {
13589 // Handle &&A - &&B.
13590 if (!LHSValue
.Offset
.isZero() || !RHSValue
.Offset
.isZero())
13592 const Expr
*LHSExpr
= LHSValue
.Base
.dyn_cast
<const Expr
*>();
13593 const Expr
*RHSExpr
= RHSValue
.Base
.dyn_cast
<const Expr
*>();
13594 if (!LHSExpr
|| !RHSExpr
)
13596 const AddrLabelExpr
*LHSAddrExpr
= dyn_cast
<AddrLabelExpr
>(LHSExpr
);
13597 const AddrLabelExpr
*RHSAddrExpr
= dyn_cast
<AddrLabelExpr
>(RHSExpr
);
13598 if (!LHSAddrExpr
|| !RHSAddrExpr
)
13600 // Make sure both labels come from the same function.
13601 if (LHSAddrExpr
->getLabel()->getDeclContext() !=
13602 RHSAddrExpr
->getLabel()->getDeclContext())
13604 return Success(APValue(LHSAddrExpr
, RHSAddrExpr
), E
);
13606 const CharUnits
&LHSOffset
= LHSValue
.getLValueOffset();
13607 const CharUnits
&RHSOffset
= RHSValue
.getLValueOffset();
13609 SubobjectDesignator
&LHSDesignator
= LHSValue
.getLValueDesignator();
13610 SubobjectDesignator
&RHSDesignator
= RHSValue
.getLValueDesignator();
13612 // C++11 [expr.add]p6:
13613 // Unless both pointers point to elements of the same array object, or
13614 // one past the last element of the array object, the behavior is
13616 if (!LHSDesignator
.Invalid
&& !RHSDesignator
.Invalid
&&
13617 !AreElementsOfSameArray(getType(LHSValue
.Base
), LHSDesignator
,
13619 Info
.CCEDiag(E
, diag::note_constexpr_pointer_subtraction_not_same_array
);
13621 QualType Type
= E
->getLHS()->getType();
13622 QualType ElementType
= Type
->castAs
<PointerType
>()->getPointeeType();
13624 CharUnits ElementSize
;
13625 if (!HandleSizeof(Info
, E
->getExprLoc(), ElementType
, ElementSize
))
13628 // As an extension, a type may have zero size (empty struct or union in
13629 // C, array of zero length). Pointer subtraction in such cases has
13630 // undefined behavior, so is not constant.
13631 if (ElementSize
.isZero()) {
13632 Info
.FFDiag(E
, diag::note_constexpr_pointer_subtraction_zero_size
)
13637 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
13638 // and produce incorrect results when it overflows. Such behavior
13639 // appears to be non-conforming, but is common, so perhaps we should
13640 // assume the standard intended for such cases to be undefined behavior
13641 // and check for them.
13643 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
13644 // overflow in the final conversion to ptrdiff_t.
13645 APSInt
LHS(llvm::APInt(65, (int64_t)LHSOffset
.getQuantity(), true), false);
13646 APSInt
RHS(llvm::APInt(65, (int64_t)RHSOffset
.getQuantity(), true), false);
13647 APSInt
ElemSize(llvm::APInt(65, (int64_t)ElementSize
.getQuantity(), true),
13649 APSInt TrueResult
= (LHS
- RHS
) / ElemSize
;
13650 APSInt Result
= TrueResult
.trunc(Info
.Ctx
.getIntWidth(E
->getType()));
13652 if (Result
.extend(65) != TrueResult
&&
13653 !HandleOverflow(Info
, E
, TrueResult
, E
->getType()))
13655 return Success(Result
, E
);
13658 return ExprEvaluatorBaseTy::VisitBinaryOperator(E
);
13661 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
13662 /// a result as the expression's type.
13663 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
13664 const UnaryExprOrTypeTraitExpr
*E
) {
13665 switch(E
->getKind()) {
13666 case UETT_PreferredAlignOf
:
13667 case UETT_AlignOf
: {
13668 if (E
->isArgumentType())
13669 return Success(GetAlignOfType(Info
, E
->getArgumentType(), E
->getKind()),
13672 return Success(GetAlignOfExpr(Info
, E
->getArgumentExpr(), E
->getKind()),
13676 case UETT_VecStep
: {
13677 QualType Ty
= E
->getTypeOfArgument();
13679 if (Ty
->isVectorType()) {
13680 unsigned n
= Ty
->castAs
<VectorType
>()->getNumElements();
13682 // The vec_step built-in functions that take a 3-component
13683 // vector return 4. (OpenCL 1.1 spec 6.11.12)
13687 return Success(n
, E
);
13689 return Success(1, E
);
13692 case UETT_SizeOf
: {
13693 QualType SrcTy
= E
->getTypeOfArgument();
13694 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13695 // the result is the size of the referenced type."
13696 if (const ReferenceType
*Ref
= SrcTy
->getAs
<ReferenceType
>())
13697 SrcTy
= Ref
->getPointeeType();
13700 if (!HandleSizeof(Info
, E
->getExprLoc(), SrcTy
, Sizeof
))
13702 return Success(Sizeof
, E
);
13704 case UETT_OpenMPRequiredSimdAlign
:
13705 assert(E
->isArgumentType());
13707 Info
.Ctx
.toCharUnitsFromBits(
13708 Info
.Ctx
.getOpenMPDefaultSimdAlign(E
->getArgumentType()))
13711 case UETT_VectorElements
: {
13712 QualType Ty
= E
->getTypeOfArgument();
13713 // If the vector has a fixed size, we can determine the number of elements
13714 // at compile time.
13715 if (Ty
->isVectorType())
13716 return Success(Ty
->castAs
<VectorType
>()->getNumElements(), E
);
13718 assert(Ty
->isSizelessVectorType());
13719 if (Info
.InConstantContext
)
13720 Info
.CCEDiag(E
, diag::note_constexpr_non_const_vectorelements
)
13721 << E
->getSourceRange();
13727 llvm_unreachable("unknown expr/type trait");
13730 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr
*OOE
) {
13732 unsigned n
= OOE
->getNumComponents();
13735 QualType CurrentType
= OOE
->getTypeSourceInfo()->getType();
13736 for (unsigned i
= 0; i
!= n
; ++i
) {
13737 OffsetOfNode ON
= OOE
->getComponent(i
);
13738 switch (ON
.getKind()) {
13739 case OffsetOfNode::Array
: {
13740 const Expr
*Idx
= OOE
->getIndexExpr(ON
.getArrayExprIndex());
13742 if (!EvaluateInteger(Idx
, IdxResult
, Info
))
13744 const ArrayType
*AT
= Info
.Ctx
.getAsArrayType(CurrentType
);
13747 CurrentType
= AT
->getElementType();
13748 CharUnits ElementSize
= Info
.Ctx
.getTypeSizeInChars(CurrentType
);
13749 Result
+= IdxResult
.getSExtValue() * ElementSize
;
13753 case OffsetOfNode::Field
: {
13754 FieldDecl
*MemberDecl
= ON
.getField();
13755 const RecordType
*RT
= CurrentType
->getAs
<RecordType
>();
13758 RecordDecl
*RD
= RT
->getDecl();
13759 if (RD
->isInvalidDecl()) return false;
13760 const ASTRecordLayout
&RL
= Info
.Ctx
.getASTRecordLayout(RD
);
13761 unsigned i
= MemberDecl
->getFieldIndex();
13762 assert(i
< RL
.getFieldCount() && "offsetof field in wrong type");
13763 Result
+= Info
.Ctx
.toCharUnitsFromBits(RL
.getFieldOffset(i
));
13764 CurrentType
= MemberDecl
->getType().getNonReferenceType();
13768 case OffsetOfNode::Identifier
:
13769 llvm_unreachable("dependent __builtin_offsetof");
13771 case OffsetOfNode::Base
: {
13772 CXXBaseSpecifier
*BaseSpec
= ON
.getBase();
13773 if (BaseSpec
->isVirtual())
13776 // Find the layout of the class whose base we are looking into.
13777 const RecordType
*RT
= CurrentType
->getAs
<RecordType
>();
13780 RecordDecl
*RD
= RT
->getDecl();
13781 if (RD
->isInvalidDecl()) return false;
13782 const ASTRecordLayout
&RL
= Info
.Ctx
.getASTRecordLayout(RD
);
13784 // Find the base class itself.
13785 CurrentType
= BaseSpec
->getType();
13786 const RecordType
*BaseRT
= CurrentType
->getAs
<RecordType
>();
13790 // Add the offset to the base.
13791 Result
+= RL
.getBaseClassOffset(cast
<CXXRecordDecl
>(BaseRT
->getDecl()));
13796 return Success(Result
, OOE
);
13799 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator
*E
) {
13800 switch (E
->getOpcode()) {
13802 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13806 // FIXME: Should extension allow i-c-e extension expressions in its scope?
13807 // If so, we could clear the diagnostic ID.
13808 return Visit(E
->getSubExpr());
13810 // The result is just the value.
13811 return Visit(E
->getSubExpr());
13813 if (!Visit(E
->getSubExpr()))
13815 if (!Result
.isInt()) return Error(E
);
13816 const APSInt
&Value
= Result
.getInt();
13817 if (Value
.isSigned() && Value
.isMinSignedValue() && E
->canOverflow()) {
13818 if (Info
.checkingForUndefinedBehavior())
13819 Info
.Ctx
.getDiagnostics().Report(E
->getExprLoc(),
13820 diag::warn_integer_constant_overflow
)
13821 << toString(Value
, 10) << E
->getType() << E
->getSourceRange();
13823 if (!HandleOverflow(Info
, E
, -Value
.extend(Value
.getBitWidth() + 1),
13827 return Success(-Value
, E
);
13830 if (!Visit(E
->getSubExpr()))
13832 if (!Result
.isInt()) return Error(E
);
13833 return Success(~Result
.getInt(), E
);
13837 if (!EvaluateAsBooleanCondition(E
->getSubExpr(), bres
, Info
))
13839 return Success(!bres
, E
);
13844 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13845 /// result type is integer.
13846 bool IntExprEvaluator::VisitCastExpr(const CastExpr
*E
) {
13847 const Expr
*SubExpr
= E
->getSubExpr();
13848 QualType DestType
= E
->getType();
13849 QualType SrcType
= SubExpr
->getType();
13851 switch (E
->getCastKind()) {
13852 case CK_BaseToDerived
:
13853 case CK_DerivedToBase
:
13854 case CK_UncheckedDerivedToBase
:
13857 case CK_ArrayToPointerDecay
:
13858 case CK_FunctionToPointerDecay
:
13859 case CK_NullToPointer
:
13860 case CK_NullToMemberPointer
:
13861 case CK_BaseToDerivedMemberPointer
:
13862 case CK_DerivedToBaseMemberPointer
:
13863 case CK_ReinterpretMemberPointer
:
13864 case CK_ConstructorConversion
:
13865 case CK_IntegralToPointer
:
13867 case CK_VectorSplat
:
13868 case CK_IntegralToFloating
:
13869 case CK_FloatingCast
:
13870 case CK_CPointerToObjCPointerCast
:
13871 case CK_BlockPointerToObjCPointerCast
:
13872 case CK_AnyPointerToBlockPointerCast
:
13873 case CK_ObjCObjectLValueCast
:
13874 case CK_FloatingRealToComplex
:
13875 case CK_FloatingComplexToReal
:
13876 case CK_FloatingComplexCast
:
13877 case CK_FloatingComplexToIntegralComplex
:
13878 case CK_IntegralRealToComplex
:
13879 case CK_IntegralComplexCast
:
13880 case CK_IntegralComplexToFloatingComplex
:
13881 case CK_BuiltinFnToFnPtr
:
13882 case CK_ZeroToOCLOpaqueType
:
13883 case CK_NonAtomicToAtomic
:
13884 case CK_AddressSpaceConversion
:
13885 case CK_IntToOCLSampler
:
13886 case CK_FloatingToFixedPoint
:
13887 case CK_FixedPointToFloating
:
13888 case CK_FixedPointCast
:
13889 case CK_IntegralToFixedPoint
:
13890 case CK_MatrixCast
:
13891 llvm_unreachable("invalid cast kind for integral value");
13895 case CK_LValueBitCast
:
13896 case CK_ARCProduceObject
:
13897 case CK_ARCConsumeObject
:
13898 case CK_ARCReclaimReturnedObject
:
13899 case CK_ARCExtendBlockObject
:
13900 case CK_CopyAndAutoreleaseBlockObject
:
13903 case CK_UserDefinedConversion
:
13904 case CK_LValueToRValue
:
13905 case CK_AtomicToNonAtomic
:
13907 case CK_LValueToRValueBitCast
:
13908 return ExprEvaluatorBaseTy::VisitCastExpr(E
);
13910 case CK_MemberPointerToBoolean
:
13911 case CK_PointerToBoolean
:
13912 case CK_IntegralToBoolean
:
13913 case CK_FloatingToBoolean
:
13914 case CK_BooleanToSignedIntegral
:
13915 case CK_FloatingComplexToBoolean
:
13916 case CK_IntegralComplexToBoolean
: {
13918 if (!EvaluateAsBooleanCondition(SubExpr
, BoolResult
, Info
))
13920 uint64_t IntResult
= BoolResult
;
13921 if (BoolResult
&& E
->getCastKind() == CK_BooleanToSignedIntegral
)
13922 IntResult
= (uint64_t)-1;
13923 return Success(IntResult
, E
);
13926 case CK_FixedPointToIntegral
: {
13927 APFixedPoint
Src(Info
.Ctx
.getFixedPointSemantics(SrcType
));
13928 if (!EvaluateFixedPoint(SubExpr
, Src
, Info
))
13931 llvm::APSInt Result
= Src
.convertToInt(
13932 Info
.Ctx
.getIntWidth(DestType
),
13933 DestType
->isSignedIntegerOrEnumerationType(), &Overflowed
);
13934 if (Overflowed
&& !HandleOverflow(Info
, E
, Result
, DestType
))
13936 return Success(Result
, E
);
13939 case CK_FixedPointToBoolean
: {
13940 // Unsigned padding does not affect this.
13942 if (!Evaluate(Val
, Info
, SubExpr
))
13944 return Success(Val
.getFixedPoint().getBoolValue(), E
);
13947 case CK_IntegralCast
: {
13948 if (!Visit(SubExpr
))
13951 if (!Result
.isInt()) {
13952 // Allow casts of address-of-label differences if they are no-ops
13953 // or narrowing. (The narrowing case isn't actually guaranteed to
13954 // be constant-evaluatable except in some narrow cases which are hard
13955 // to detect here. We let it through on the assumption the user knows
13956 // what they are doing.)
13957 if (Result
.isAddrLabelDiff())
13958 return Info
.Ctx
.getTypeSize(DestType
) <= Info
.Ctx
.getTypeSize(SrcType
);
13959 // Only allow casts of lvalues if they are lossless.
13960 return Info
.Ctx
.getTypeSize(DestType
) == Info
.Ctx
.getTypeSize(SrcType
);
13963 if (Info
.Ctx
.getLangOpts().CPlusPlus
&& Info
.InConstantContext
&&
13964 Info
.EvalMode
== EvalInfo::EM_ConstantExpression
&&
13965 DestType
->isEnumeralType()) {
13967 bool ConstexprVar
= true;
13969 // We know if we are here that we are in a context that we might require
13970 // a constant expression or a context that requires a constant
13971 // value. But if we are initializing a value we don't know if it is a
13972 // constexpr variable or not. We can check the EvaluatingDecl to determine
13973 // if it constexpr or not. If not then we don't want to emit a diagnostic.
13974 if (const auto *VD
= dyn_cast_or_null
<VarDecl
>(
13975 Info
.EvaluatingDecl
.dyn_cast
<const ValueDecl
*>()))
13976 ConstexprVar
= VD
->isConstexpr();
13978 const EnumType
*ET
= dyn_cast
<EnumType
>(DestType
.getCanonicalType());
13979 const EnumDecl
*ED
= ET
->getDecl();
13980 // Check that the value is within the range of the enumeration values.
13982 // This corressponds to [expr.static.cast]p10 which says:
13983 // A value of integral or enumeration type can be explicitly converted
13984 // to a complete enumeration type ... If the enumeration type does not
13985 // have a fixed underlying type, the value is unchanged if the original
13986 // value is within the range of the enumeration values ([dcl.enum]), and
13987 // otherwise, the behavior is undefined.
13989 // This was resolved as part of DR2338 which has CD5 status.
13990 if (!ED
->isFixed()) {
13994 ED
->getValueRange(Max
, Min
);
13997 if (ED
->getNumNegativeBits() && ConstexprVar
&&
13998 (Max
.slt(Result
.getInt().getSExtValue()) ||
13999 Min
.sgt(Result
.getInt().getSExtValue())))
14000 Info
.Ctx
.getDiagnostics().Report(
14001 E
->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range
)
14002 << llvm::toString(Result
.getInt(), 10) << Min
.getSExtValue()
14003 << Max
.getSExtValue() << ED
;
14004 else if (!ED
->getNumNegativeBits() && ConstexprVar
&&
14005 Max
.ult(Result
.getInt().getZExtValue()))
14006 Info
.Ctx
.getDiagnostics().Report(
14007 E
->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range
)
14008 << llvm::toString(Result
.getInt(), 10) << Min
.getZExtValue()
14009 << Max
.getZExtValue() << ED
;
14013 return Success(HandleIntToIntCast(Info
, E
, DestType
, SrcType
,
14014 Result
.getInt()), E
);
14017 case CK_PointerToIntegral
: {
14018 CCEDiag(E
, diag::note_constexpr_invalid_cast
)
14019 << 2 << Info
.Ctx
.getLangOpts().CPlusPlus
<< E
->getSourceRange();
14022 if (!EvaluatePointer(SubExpr
, LV
, Info
))
14025 if (LV
.getLValueBase()) {
14026 // Only allow based lvalue casts if they are lossless.
14027 // FIXME: Allow a larger integer size than the pointer size, and allow
14028 // narrowing back down to pointer width in subsequent integral casts.
14029 // FIXME: Check integer type's active bits, not its type size.
14030 if (Info
.Ctx
.getTypeSize(DestType
) != Info
.Ctx
.getTypeSize(SrcType
))
14033 LV
.Designator
.setInvalid();
14034 LV
.moveInto(Result
);
14041 if (!V
.toIntegralConstant(AsInt
, SrcType
, Info
.Ctx
))
14042 llvm_unreachable("Can't cast this!");
14044 return Success(HandleIntToIntCast(Info
, E
, DestType
, SrcType
, AsInt
), E
);
14047 case CK_IntegralComplexToReal
: {
14049 if (!EvaluateComplex(SubExpr
, C
, Info
))
14051 return Success(C
.getComplexIntReal(), E
);
14054 case CK_FloatingToIntegral
: {
14056 if (!EvaluateFloat(SubExpr
, F
, Info
))
14060 if (!HandleFloatToIntCast(Info
, E
, SrcType
, F
, DestType
, Value
))
14062 return Success(Value
, E
);
14066 llvm_unreachable("unknown cast resulting in integral value");
14069 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator
*E
) {
14070 if (E
->getSubExpr()->getType()->isAnyComplexType()) {
14072 if (!EvaluateComplex(E
->getSubExpr(), LV
, Info
))
14074 if (!LV
.isComplexInt())
14076 return Success(LV
.getComplexIntReal(), E
);
14079 return Visit(E
->getSubExpr());
14082 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator
*E
) {
14083 if (E
->getSubExpr()->getType()->isComplexIntegerType()) {
14085 if (!EvaluateComplex(E
->getSubExpr(), LV
, Info
))
14087 if (!LV
.isComplexInt())
14089 return Success(LV
.getComplexIntImag(), E
);
14092 VisitIgnoredValue(E
->getSubExpr());
14093 return Success(0, E
);
14096 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr
*E
) {
14097 return Success(E
->getPackLength(), E
);
14100 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr
*E
) {
14101 return Success(E
->getValue(), E
);
14104 bool IntExprEvaluator::VisitConceptSpecializationExpr(
14105 const ConceptSpecializationExpr
*E
) {
14106 return Success(E
->isSatisfied(), E
);
14109 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr
*E
) {
14110 return Success(E
->isSatisfied(), E
);
14113 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator
*E
) {
14114 switch (E
->getOpcode()) {
14116 // Invalid unary operators
14119 // The result is just the value.
14120 return Visit(E
->getSubExpr());
14122 if (!Visit(E
->getSubExpr())) return false;
14123 if (!Result
.isFixedPoint())
14126 APFixedPoint Negated
= Result
.getFixedPoint().negate(&Overflowed
);
14127 if (Overflowed
&& !HandleOverflow(Info
, E
, Negated
, E
->getType()))
14129 return Success(Negated
, E
);
14133 if (!EvaluateAsBooleanCondition(E
->getSubExpr(), bres
, Info
))
14135 return Success(!bres
, E
);
14140 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr
*E
) {
14141 const Expr
*SubExpr
= E
->getSubExpr();
14142 QualType DestType
= E
->getType();
14143 assert(DestType
->isFixedPointType() &&
14144 "Expected destination type to be a fixed point type");
14145 auto DestFXSema
= Info
.Ctx
.getFixedPointSemantics(DestType
);
14147 switch (E
->getCastKind()) {
14148 case CK_FixedPointCast
: {
14149 APFixedPoint
Src(Info
.Ctx
.getFixedPointSemantics(SubExpr
->getType()));
14150 if (!EvaluateFixedPoint(SubExpr
, Src
, Info
))
14153 APFixedPoint Result
= Src
.convert(DestFXSema
, &Overflowed
);
14155 if (Info
.checkingForUndefinedBehavior())
14156 Info
.Ctx
.getDiagnostics().Report(E
->getExprLoc(),
14157 diag::warn_fixedpoint_constant_overflow
)
14158 << Result
.toString() << E
->getType();
14159 if (!HandleOverflow(Info
, E
, Result
, E
->getType()))
14162 return Success(Result
, E
);
14164 case CK_IntegralToFixedPoint
: {
14166 if (!EvaluateInteger(SubExpr
, Src
, Info
))
14170 APFixedPoint IntResult
= APFixedPoint::getFromIntValue(
14171 Src
, Info
.Ctx
.getFixedPointSemantics(DestType
), &Overflowed
);
14174 if (Info
.checkingForUndefinedBehavior())
14175 Info
.Ctx
.getDiagnostics().Report(E
->getExprLoc(),
14176 diag::warn_fixedpoint_constant_overflow
)
14177 << IntResult
.toString() << E
->getType();
14178 if (!HandleOverflow(Info
, E
, IntResult
, E
->getType()))
14182 return Success(IntResult
, E
);
14184 case CK_FloatingToFixedPoint
: {
14186 if (!EvaluateFloat(SubExpr
, Src
, Info
))
14190 APFixedPoint Result
= APFixedPoint::getFromFloatValue(
14191 Src
, Info
.Ctx
.getFixedPointSemantics(DestType
), &Overflowed
);
14194 if (Info
.checkingForUndefinedBehavior())
14195 Info
.Ctx
.getDiagnostics().Report(E
->getExprLoc(),
14196 diag::warn_fixedpoint_constant_overflow
)
14197 << Result
.toString() << E
->getType();
14198 if (!HandleOverflow(Info
, E
, Result
, E
->getType()))
14202 return Success(Result
, E
);
14205 case CK_LValueToRValue
:
14206 return ExprEvaluatorBaseTy::VisitCastExpr(E
);
14212 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator
*E
) {
14213 if (E
->isPtrMemOp() || E
->isAssignmentOp() || E
->getOpcode() == BO_Comma
)
14214 return ExprEvaluatorBaseTy::VisitBinaryOperator(E
);
14216 const Expr
*LHS
= E
->getLHS();
14217 const Expr
*RHS
= E
->getRHS();
14218 FixedPointSemantics ResultFXSema
=
14219 Info
.Ctx
.getFixedPointSemantics(E
->getType());
14221 APFixedPoint
LHSFX(Info
.Ctx
.getFixedPointSemantics(LHS
->getType()));
14222 if (!EvaluateFixedPointOrInteger(LHS
, LHSFX
, Info
))
14224 APFixedPoint
RHSFX(Info
.Ctx
.getFixedPointSemantics(RHS
->getType()));
14225 if (!EvaluateFixedPointOrInteger(RHS
, RHSFX
, Info
))
14228 bool OpOverflow
= false, ConversionOverflow
= false;
14229 APFixedPoint
Result(LHSFX
.getSemantics());
14230 switch (E
->getOpcode()) {
14232 Result
= LHSFX
.add(RHSFX
, &OpOverflow
)
14233 .convert(ResultFXSema
, &ConversionOverflow
);
14237 Result
= LHSFX
.sub(RHSFX
, &OpOverflow
)
14238 .convert(ResultFXSema
, &ConversionOverflow
);
14242 Result
= LHSFX
.mul(RHSFX
, &OpOverflow
)
14243 .convert(ResultFXSema
, &ConversionOverflow
);
14247 if (RHSFX
.getValue() == 0) {
14248 Info
.FFDiag(E
, diag::note_expr_divide_by_zero
);
14251 Result
= LHSFX
.div(RHSFX
, &OpOverflow
)
14252 .convert(ResultFXSema
, &ConversionOverflow
);
14257 FixedPointSemantics LHSSema
= LHSFX
.getSemantics();
14258 llvm::APSInt RHSVal
= RHSFX
.getValue();
14261 LHSSema
.getWidth() - (unsigned)LHSSema
.hasUnsignedPadding();
14262 unsigned Amt
= RHSVal
.getLimitedValue(ShiftBW
- 1);
14263 // Embedded-C 4.1.6.2.2:
14264 // The right operand must be nonnegative and less than the total number
14265 // of (nonpadding) bits of the fixed-point operand ...
14266 if (RHSVal
.isNegative())
14267 Info
.CCEDiag(E
, diag::note_constexpr_negative_shift
) << RHSVal
;
14268 else if (Amt
!= RHSVal
)
14269 Info
.CCEDiag(E
, diag::note_constexpr_large_shift
)
14270 << RHSVal
<< E
->getType() << ShiftBW
;
14272 if (E
->getOpcode() == BO_Shl
)
14273 Result
= LHSFX
.shl(Amt
, &OpOverflow
);
14275 Result
= LHSFX
.shr(Amt
, &OpOverflow
);
14281 if (OpOverflow
|| ConversionOverflow
) {
14282 if (Info
.checkingForUndefinedBehavior())
14283 Info
.Ctx
.getDiagnostics().Report(E
->getExprLoc(),
14284 diag::warn_fixedpoint_constant_overflow
)
14285 << Result
.toString() << E
->getType();
14286 if (!HandleOverflow(Info
, E
, Result
, E
->getType()))
14289 return Success(Result
, E
);
14292 //===----------------------------------------------------------------------===//
14293 // Float Evaluation
14294 //===----------------------------------------------------------------------===//
14297 class FloatExprEvaluator
14298 : public ExprEvaluatorBase
<FloatExprEvaluator
> {
14301 FloatExprEvaluator(EvalInfo
&info
, APFloat
&result
)
14302 : ExprEvaluatorBaseTy(info
), Result(result
) {}
14304 bool Success(const APValue
&V
, const Expr
*e
) {
14305 Result
= V
.getFloat();
14309 bool ZeroInitialization(const Expr
*E
) {
14310 Result
= APFloat::getZero(Info
.Ctx
.getFloatTypeSemantics(E
->getType()));
14314 bool VisitCallExpr(const CallExpr
*E
);
14316 bool VisitUnaryOperator(const UnaryOperator
*E
);
14317 bool VisitBinaryOperator(const BinaryOperator
*E
);
14318 bool VisitFloatingLiteral(const FloatingLiteral
*E
);
14319 bool VisitCastExpr(const CastExpr
*E
);
14321 bool VisitUnaryReal(const UnaryOperator
*E
);
14322 bool VisitUnaryImag(const UnaryOperator
*E
);
14324 // FIXME: Missing: array subscript of vector, member of vector
14326 } // end anonymous namespace
14328 static bool EvaluateFloat(const Expr
* E
, APFloat
& Result
, EvalInfo
&Info
) {
14329 assert(!E
->isValueDependent());
14330 assert(E
->isPRValue() && E
->getType()->isRealFloatingType());
14331 return FloatExprEvaluator(Info
, Result
).Visit(E
);
14334 static bool TryEvaluateBuiltinNaN(const ASTContext
&Context
,
14338 llvm::APFloat
&Result
) {
14339 const StringLiteral
*S
= dyn_cast
<StringLiteral
>(Arg
->IgnoreParenCasts());
14340 if (!S
) return false;
14342 const llvm::fltSemantics
&Sem
= Context
.getFloatTypeSemantics(ResultTy
);
14346 // Treat empty strings as if they were zero.
14347 if (S
->getString().empty())
14348 fill
= llvm::APInt(32, 0);
14349 else if (S
->getString().getAsInteger(0, fill
))
14352 if (Context
.getTargetInfo().isNan2008()) {
14354 Result
= llvm::APFloat::getSNaN(Sem
, false, &fill
);
14356 Result
= llvm::APFloat::getQNaN(Sem
, false, &fill
);
14358 // Prior to IEEE 754-2008, architectures were allowed to choose whether
14359 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
14360 // a different encoding to what became a standard in 2008, and for pre-
14361 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
14362 // sNaN. This is now known as "legacy NaN" encoding.
14364 Result
= llvm::APFloat::getQNaN(Sem
, false, &fill
);
14366 Result
= llvm::APFloat::getSNaN(Sem
, false, &fill
);
14372 bool FloatExprEvaluator::VisitCallExpr(const CallExpr
*E
) {
14373 if (!IsConstantEvaluatedBuiltinCall(E
))
14374 return ExprEvaluatorBaseTy::VisitCallExpr(E
);
14376 switch (E
->getBuiltinCallee()) {
14380 case Builtin::BI__builtin_huge_val
:
14381 case Builtin::BI__builtin_huge_valf
:
14382 case Builtin::BI__builtin_huge_vall
:
14383 case Builtin::BI__builtin_huge_valf16
:
14384 case Builtin::BI__builtin_huge_valf128
:
14385 case Builtin::BI__builtin_inf
:
14386 case Builtin::BI__builtin_inff
:
14387 case Builtin::BI__builtin_infl
:
14388 case Builtin::BI__builtin_inff16
:
14389 case Builtin::BI__builtin_inff128
: {
14390 const llvm::fltSemantics
&Sem
=
14391 Info
.Ctx
.getFloatTypeSemantics(E
->getType());
14392 Result
= llvm::APFloat::getInf(Sem
);
14396 case Builtin::BI__builtin_nans
:
14397 case Builtin::BI__builtin_nansf
:
14398 case Builtin::BI__builtin_nansl
:
14399 case Builtin::BI__builtin_nansf16
:
14400 case Builtin::BI__builtin_nansf128
:
14401 if (!TryEvaluateBuiltinNaN(Info
.Ctx
, E
->getType(), E
->getArg(0),
14406 case Builtin::BI__builtin_nan
:
14407 case Builtin::BI__builtin_nanf
:
14408 case Builtin::BI__builtin_nanl
:
14409 case Builtin::BI__builtin_nanf16
:
14410 case Builtin::BI__builtin_nanf128
:
14411 // If this is __builtin_nan() turn this into a nan, otherwise we
14412 // can't constant fold it.
14413 if (!TryEvaluateBuiltinNaN(Info
.Ctx
, E
->getType(), E
->getArg(0),
14418 case Builtin::BI__builtin_fabs
:
14419 case Builtin::BI__builtin_fabsf
:
14420 case Builtin::BI__builtin_fabsl
:
14421 case Builtin::BI__builtin_fabsf128
:
14422 // The C standard says "fabs raises no floating-point exceptions,
14423 // even if x is a signaling NaN. The returned value is independent of
14424 // the current rounding direction mode." Therefore constant folding can
14425 // proceed without regard to the floating point settings.
14426 // Reference, WG14 N2478 F.10.4.3
14427 if (!EvaluateFloat(E
->getArg(0), Result
, Info
))
14430 if (Result
.isNegative())
14431 Result
.changeSign();
14434 case Builtin::BI__arithmetic_fence
:
14435 return EvaluateFloat(E
->getArg(0), Result
, Info
);
14437 // FIXME: Builtin::BI__builtin_powi
14438 // FIXME: Builtin::BI__builtin_powif
14439 // FIXME: Builtin::BI__builtin_powil
14441 case Builtin::BI__builtin_copysign
:
14442 case Builtin::BI__builtin_copysignf
:
14443 case Builtin::BI__builtin_copysignl
:
14444 case Builtin::BI__builtin_copysignf128
: {
14446 if (!EvaluateFloat(E
->getArg(0), Result
, Info
) ||
14447 !EvaluateFloat(E
->getArg(1), RHS
, Info
))
14449 Result
.copySign(RHS
);
14453 case Builtin::BI__builtin_fmax
:
14454 case Builtin::BI__builtin_fmaxf
:
14455 case Builtin::BI__builtin_fmaxl
:
14456 case Builtin::BI__builtin_fmaxf16
:
14457 case Builtin::BI__builtin_fmaxf128
: {
14458 // TODO: Handle sNaN.
14460 if (!EvaluateFloat(E
->getArg(0), Result
, Info
) ||
14461 !EvaluateFloat(E
->getArg(1), RHS
, Info
))
14463 // When comparing zeroes, return +0.0 if one of the zeroes is positive.
14464 if (Result
.isZero() && RHS
.isZero() && Result
.isNegative())
14466 else if (Result
.isNaN() || RHS
> Result
)
14471 case Builtin::BI__builtin_fmin
:
14472 case Builtin::BI__builtin_fminf
:
14473 case Builtin::BI__builtin_fminl
:
14474 case Builtin::BI__builtin_fminf16
:
14475 case Builtin::BI__builtin_fminf128
: {
14476 // TODO: Handle sNaN.
14478 if (!EvaluateFloat(E
->getArg(0), Result
, Info
) ||
14479 !EvaluateFloat(E
->getArg(1), RHS
, Info
))
14481 // When comparing zeroes, return -0.0 if one of the zeroes is negative.
14482 if (Result
.isZero() && RHS
.isZero() && RHS
.isNegative())
14484 else if (Result
.isNaN() || RHS
< Result
)
14491 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator
*E
) {
14492 if (E
->getSubExpr()->getType()->isAnyComplexType()) {
14494 if (!EvaluateComplex(E
->getSubExpr(), CV
, Info
))
14496 Result
= CV
.FloatReal
;
14500 return Visit(E
->getSubExpr());
14503 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator
*E
) {
14504 if (E
->getSubExpr()->getType()->isAnyComplexType()) {
14506 if (!EvaluateComplex(E
->getSubExpr(), CV
, Info
))
14508 Result
= CV
.FloatImag
;
14512 VisitIgnoredValue(E
->getSubExpr());
14513 const llvm::fltSemantics
&Sem
= Info
.Ctx
.getFloatTypeSemantics(E
->getType());
14514 Result
= llvm::APFloat::getZero(Sem
);
14518 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator
*E
) {
14519 switch (E
->getOpcode()) {
14520 default: return Error(E
);
14522 return EvaluateFloat(E
->getSubExpr(), Result
, Info
);
14524 // In C standard, WG14 N2478 F.3 p4
14525 // "the unary - raises no floating point exceptions,
14526 // even if the operand is signalling."
14527 if (!EvaluateFloat(E
->getSubExpr(), Result
, Info
))
14529 Result
.changeSign();
14534 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator
*E
) {
14535 if (E
->isPtrMemOp() || E
->isAssignmentOp() || E
->getOpcode() == BO_Comma
)
14536 return ExprEvaluatorBaseTy::VisitBinaryOperator(E
);
14539 bool LHSOK
= EvaluateFloat(E
->getLHS(), Result
, Info
);
14540 if (!LHSOK
&& !Info
.noteFailure())
14542 return EvaluateFloat(E
->getRHS(), RHS
, Info
) && LHSOK
&&
14543 handleFloatFloatBinOp(Info
, E
, Result
, E
->getOpcode(), RHS
);
14546 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral
*E
) {
14547 Result
= E
->getValue();
14551 bool FloatExprEvaluator::VisitCastExpr(const CastExpr
*E
) {
14552 const Expr
* SubExpr
= E
->getSubExpr();
14554 switch (E
->getCastKind()) {
14556 return ExprEvaluatorBaseTy::VisitCastExpr(E
);
14558 case CK_IntegralToFloating
: {
14560 const FPOptions FPO
= E
->getFPFeaturesInEffect(
14561 Info
.Ctx
.getLangOpts());
14562 return EvaluateInteger(SubExpr
, IntResult
, Info
) &&
14563 HandleIntToFloatCast(Info
, E
, FPO
, SubExpr
->getType(),
14564 IntResult
, E
->getType(), Result
);
14567 case CK_FixedPointToFloating
: {
14568 APFixedPoint
FixResult(Info
.Ctx
.getFixedPointSemantics(SubExpr
->getType()));
14569 if (!EvaluateFixedPoint(SubExpr
, FixResult
, Info
))
14572 FixResult
.convertToFloat(Info
.Ctx
.getFloatTypeSemantics(E
->getType()));
14576 case CK_FloatingCast
: {
14577 if (!Visit(SubExpr
))
14579 return HandleFloatToFloatCast(Info
, E
, SubExpr
->getType(), E
->getType(),
14583 case CK_FloatingComplexToReal
: {
14585 if (!EvaluateComplex(SubExpr
, V
, Info
))
14587 Result
= V
.getComplexFloatReal();
14593 //===----------------------------------------------------------------------===//
14594 // Complex Evaluation (for float and integer)
14595 //===----------------------------------------------------------------------===//
14598 class ComplexExprEvaluator
14599 : public ExprEvaluatorBase
<ComplexExprEvaluator
> {
14600 ComplexValue
&Result
;
14603 ComplexExprEvaluator(EvalInfo
&info
, ComplexValue
&Result
)
14604 : ExprEvaluatorBaseTy(info
), Result(Result
) {}
14606 bool Success(const APValue
&V
, const Expr
*e
) {
14611 bool ZeroInitialization(const Expr
*E
);
14613 //===--------------------------------------------------------------------===//
14615 //===--------------------------------------------------------------------===//
14617 bool VisitImaginaryLiteral(const ImaginaryLiteral
*E
);
14618 bool VisitCastExpr(const CastExpr
*E
);
14619 bool VisitBinaryOperator(const BinaryOperator
*E
);
14620 bool VisitUnaryOperator(const UnaryOperator
*E
);
14621 bool VisitInitListExpr(const InitListExpr
*E
);
14622 bool VisitCallExpr(const CallExpr
*E
);
14624 } // end anonymous namespace
14626 static bool EvaluateComplex(const Expr
*E
, ComplexValue
&Result
,
14628 assert(!E
->isValueDependent());
14629 assert(E
->isPRValue() && E
->getType()->isAnyComplexType());
14630 return ComplexExprEvaluator(Info
, Result
).Visit(E
);
14633 bool ComplexExprEvaluator::ZeroInitialization(const Expr
*E
) {
14634 QualType ElemTy
= E
->getType()->castAs
<ComplexType
>()->getElementType();
14635 if (ElemTy
->isRealFloatingType()) {
14636 Result
.makeComplexFloat();
14637 APFloat Zero
= APFloat::getZero(Info
.Ctx
.getFloatTypeSemantics(ElemTy
));
14638 Result
.FloatReal
= Zero
;
14639 Result
.FloatImag
= Zero
;
14641 Result
.makeComplexInt();
14642 APSInt Zero
= Info
.Ctx
.MakeIntValue(0, ElemTy
);
14643 Result
.IntReal
= Zero
;
14644 Result
.IntImag
= Zero
;
14649 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral
*E
) {
14650 const Expr
* SubExpr
= E
->getSubExpr();
14652 if (SubExpr
->getType()->isRealFloatingType()) {
14653 Result
.makeComplexFloat();
14654 APFloat
&Imag
= Result
.FloatImag
;
14655 if (!EvaluateFloat(SubExpr
, Imag
, Info
))
14658 Result
.FloatReal
= APFloat(Imag
.getSemantics());
14661 assert(SubExpr
->getType()->isIntegerType() &&
14662 "Unexpected imaginary literal.");
14664 Result
.makeComplexInt();
14665 APSInt
&Imag
= Result
.IntImag
;
14666 if (!EvaluateInteger(SubExpr
, Imag
, Info
))
14669 Result
.IntReal
= APSInt(Imag
.getBitWidth(), !Imag
.isSigned());
14674 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr
*E
) {
14676 switch (E
->getCastKind()) {
14678 case CK_BaseToDerived
:
14679 case CK_DerivedToBase
:
14680 case CK_UncheckedDerivedToBase
:
14683 case CK_ArrayToPointerDecay
:
14684 case CK_FunctionToPointerDecay
:
14685 case CK_NullToPointer
:
14686 case CK_NullToMemberPointer
:
14687 case CK_BaseToDerivedMemberPointer
:
14688 case CK_DerivedToBaseMemberPointer
:
14689 case CK_MemberPointerToBoolean
:
14690 case CK_ReinterpretMemberPointer
:
14691 case CK_ConstructorConversion
:
14692 case CK_IntegralToPointer
:
14693 case CK_PointerToIntegral
:
14694 case CK_PointerToBoolean
:
14696 case CK_VectorSplat
:
14697 case CK_IntegralCast
:
14698 case CK_BooleanToSignedIntegral
:
14699 case CK_IntegralToBoolean
:
14700 case CK_IntegralToFloating
:
14701 case CK_FloatingToIntegral
:
14702 case CK_FloatingToBoolean
:
14703 case CK_FloatingCast
:
14704 case CK_CPointerToObjCPointerCast
:
14705 case CK_BlockPointerToObjCPointerCast
:
14706 case CK_AnyPointerToBlockPointerCast
:
14707 case CK_ObjCObjectLValueCast
:
14708 case CK_FloatingComplexToReal
:
14709 case CK_FloatingComplexToBoolean
:
14710 case CK_IntegralComplexToReal
:
14711 case CK_IntegralComplexToBoolean
:
14712 case CK_ARCProduceObject
:
14713 case CK_ARCConsumeObject
:
14714 case CK_ARCReclaimReturnedObject
:
14715 case CK_ARCExtendBlockObject
:
14716 case CK_CopyAndAutoreleaseBlockObject
:
14717 case CK_BuiltinFnToFnPtr
:
14718 case CK_ZeroToOCLOpaqueType
:
14719 case CK_NonAtomicToAtomic
:
14720 case CK_AddressSpaceConversion
:
14721 case CK_IntToOCLSampler
:
14722 case CK_FloatingToFixedPoint
:
14723 case CK_FixedPointToFloating
:
14724 case CK_FixedPointCast
:
14725 case CK_FixedPointToBoolean
:
14726 case CK_FixedPointToIntegral
:
14727 case CK_IntegralToFixedPoint
:
14728 case CK_MatrixCast
:
14729 llvm_unreachable("invalid cast kind for complex value");
14731 case CK_LValueToRValue
:
14732 case CK_AtomicToNonAtomic
:
14734 case CK_LValueToRValueBitCast
:
14735 return ExprEvaluatorBaseTy::VisitCastExpr(E
);
14738 case CK_LValueBitCast
:
14739 case CK_UserDefinedConversion
:
14742 case CK_FloatingRealToComplex
: {
14743 APFloat
&Real
= Result
.FloatReal
;
14744 if (!EvaluateFloat(E
->getSubExpr(), Real
, Info
))
14747 Result
.makeComplexFloat();
14748 Result
.FloatImag
= APFloat(Real
.getSemantics());
14752 case CK_FloatingComplexCast
: {
14753 if (!Visit(E
->getSubExpr()))
14756 QualType To
= E
->getType()->castAs
<ComplexType
>()->getElementType();
14758 = E
->getSubExpr()->getType()->castAs
<ComplexType
>()->getElementType();
14760 return HandleFloatToFloatCast(Info
, E
, From
, To
, Result
.FloatReal
) &&
14761 HandleFloatToFloatCast(Info
, E
, From
, To
, Result
.FloatImag
);
14764 case CK_FloatingComplexToIntegralComplex
: {
14765 if (!Visit(E
->getSubExpr()))
14768 QualType To
= E
->getType()->castAs
<ComplexType
>()->getElementType();
14770 = E
->getSubExpr()->getType()->castAs
<ComplexType
>()->getElementType();
14771 Result
.makeComplexInt();
14772 return HandleFloatToIntCast(Info
, E
, From
, Result
.FloatReal
,
14773 To
, Result
.IntReal
) &&
14774 HandleFloatToIntCast(Info
, E
, From
, Result
.FloatImag
,
14775 To
, Result
.IntImag
);
14778 case CK_IntegralRealToComplex
: {
14779 APSInt
&Real
= Result
.IntReal
;
14780 if (!EvaluateInteger(E
->getSubExpr(), Real
, Info
))
14783 Result
.makeComplexInt();
14784 Result
.IntImag
= APSInt(Real
.getBitWidth(), !Real
.isSigned());
14788 case CK_IntegralComplexCast
: {
14789 if (!Visit(E
->getSubExpr()))
14792 QualType To
= E
->getType()->castAs
<ComplexType
>()->getElementType();
14794 = E
->getSubExpr()->getType()->castAs
<ComplexType
>()->getElementType();
14796 Result
.IntReal
= HandleIntToIntCast(Info
, E
, To
, From
, Result
.IntReal
);
14797 Result
.IntImag
= HandleIntToIntCast(Info
, E
, To
, From
, Result
.IntImag
);
14801 case CK_IntegralComplexToFloatingComplex
: {
14802 if (!Visit(E
->getSubExpr()))
14805 const FPOptions FPO
= E
->getFPFeaturesInEffect(
14806 Info
.Ctx
.getLangOpts());
14807 QualType To
= E
->getType()->castAs
<ComplexType
>()->getElementType();
14809 = E
->getSubExpr()->getType()->castAs
<ComplexType
>()->getElementType();
14810 Result
.makeComplexFloat();
14811 return HandleIntToFloatCast(Info
, E
, FPO
, From
, Result
.IntReal
,
14812 To
, Result
.FloatReal
) &&
14813 HandleIntToFloatCast(Info
, E
, FPO
, From
, Result
.IntImag
,
14814 To
, Result
.FloatImag
);
14818 llvm_unreachable("unknown cast resulting in complex value");
14821 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator
*E
) {
14822 if (E
->isPtrMemOp() || E
->isAssignmentOp() || E
->getOpcode() == BO_Comma
)
14823 return ExprEvaluatorBaseTy::VisitBinaryOperator(E
);
14825 // Track whether the LHS or RHS is real at the type system level. When this is
14826 // the case we can simplify our evaluation strategy.
14827 bool LHSReal
= false, RHSReal
= false;
14830 if (E
->getLHS()->getType()->isRealFloatingType()) {
14832 APFloat
&Real
= Result
.FloatReal
;
14833 LHSOK
= EvaluateFloat(E
->getLHS(), Real
, Info
);
14835 Result
.makeComplexFloat();
14836 Result
.FloatImag
= APFloat(Real
.getSemantics());
14839 LHSOK
= Visit(E
->getLHS());
14841 if (!LHSOK
&& !Info
.noteFailure())
14845 if (E
->getRHS()->getType()->isRealFloatingType()) {
14847 APFloat
&Real
= RHS
.FloatReal
;
14848 if (!EvaluateFloat(E
->getRHS(), Real
, Info
) || !LHSOK
)
14850 RHS
.makeComplexFloat();
14851 RHS
.FloatImag
= APFloat(Real
.getSemantics());
14852 } else if (!EvaluateComplex(E
->getRHS(), RHS
, Info
) || !LHSOK
)
14855 assert(!(LHSReal
&& RHSReal
) &&
14856 "Cannot have both operands of a complex operation be real.");
14857 switch (E
->getOpcode()) {
14858 default: return Error(E
);
14860 if (Result
.isComplexFloat()) {
14861 Result
.getComplexFloatReal().add(RHS
.getComplexFloatReal(),
14862 APFloat::rmNearestTiesToEven
);
14864 Result
.getComplexFloatImag() = RHS
.getComplexFloatImag();
14866 Result
.getComplexFloatImag().add(RHS
.getComplexFloatImag(),
14867 APFloat::rmNearestTiesToEven
);
14869 Result
.getComplexIntReal() += RHS
.getComplexIntReal();
14870 Result
.getComplexIntImag() += RHS
.getComplexIntImag();
14874 if (Result
.isComplexFloat()) {
14875 Result
.getComplexFloatReal().subtract(RHS
.getComplexFloatReal(),
14876 APFloat::rmNearestTiesToEven
);
14878 Result
.getComplexFloatImag() = RHS
.getComplexFloatImag();
14879 Result
.getComplexFloatImag().changeSign();
14880 } else if (!RHSReal
) {
14881 Result
.getComplexFloatImag().subtract(RHS
.getComplexFloatImag(),
14882 APFloat::rmNearestTiesToEven
);
14885 Result
.getComplexIntReal() -= RHS
.getComplexIntReal();
14886 Result
.getComplexIntImag() -= RHS
.getComplexIntImag();
14890 if (Result
.isComplexFloat()) {
14891 // This is an implementation of complex multiplication according to the
14892 // constraints laid out in C11 Annex G. The implementation uses the
14893 // following naming scheme:
14894 // (a + ib) * (c + id)
14895 ComplexValue LHS
= Result
;
14896 APFloat
&A
= LHS
.getComplexFloatReal();
14897 APFloat
&B
= LHS
.getComplexFloatImag();
14898 APFloat
&C
= RHS
.getComplexFloatReal();
14899 APFloat
&D
= RHS
.getComplexFloatImag();
14900 APFloat
&ResR
= Result
.getComplexFloatReal();
14901 APFloat
&ResI
= Result
.getComplexFloatImag();
14903 assert(!RHSReal
&& "Cannot have two real operands for a complex op!");
14906 } else if (RHSReal
) {
14910 // In the fully general case, we need to handle NaNs and infinities
14912 APFloat AC
= A
* C
;
14913 APFloat BD
= B
* D
;
14914 APFloat AD
= A
* D
;
14915 APFloat BC
= B
* C
;
14918 if (ResR
.isNaN() && ResI
.isNaN()) {
14919 bool Recalc
= false;
14920 if (A
.isInfinity() || B
.isInfinity()) {
14921 A
= APFloat::copySign(
14922 APFloat(A
.getSemantics(), A
.isInfinity() ? 1 : 0), A
);
14923 B
= APFloat::copySign(
14924 APFloat(B
.getSemantics(), B
.isInfinity() ? 1 : 0), B
);
14926 C
= APFloat::copySign(APFloat(C
.getSemantics()), C
);
14928 D
= APFloat::copySign(APFloat(D
.getSemantics()), D
);
14931 if (C
.isInfinity() || D
.isInfinity()) {
14932 C
= APFloat::copySign(
14933 APFloat(C
.getSemantics(), C
.isInfinity() ? 1 : 0), C
);
14934 D
= APFloat::copySign(
14935 APFloat(D
.getSemantics(), D
.isInfinity() ? 1 : 0), D
);
14937 A
= APFloat::copySign(APFloat(A
.getSemantics()), A
);
14939 B
= APFloat::copySign(APFloat(B
.getSemantics()), B
);
14942 if (!Recalc
&& (AC
.isInfinity() || BD
.isInfinity() ||
14943 AD
.isInfinity() || BC
.isInfinity())) {
14945 A
= APFloat::copySign(APFloat(A
.getSemantics()), A
);
14947 B
= APFloat::copySign(APFloat(B
.getSemantics()), B
);
14949 C
= APFloat::copySign(APFloat(C
.getSemantics()), C
);
14951 D
= APFloat::copySign(APFloat(D
.getSemantics()), D
);
14955 ResR
= APFloat::getInf(A
.getSemantics()) * (A
* C
- B
* D
);
14956 ResI
= APFloat::getInf(A
.getSemantics()) * (A
* D
+ B
* C
);
14961 ComplexValue LHS
= Result
;
14962 Result
.getComplexIntReal() =
14963 (LHS
.getComplexIntReal() * RHS
.getComplexIntReal() -
14964 LHS
.getComplexIntImag() * RHS
.getComplexIntImag());
14965 Result
.getComplexIntImag() =
14966 (LHS
.getComplexIntReal() * RHS
.getComplexIntImag() +
14967 LHS
.getComplexIntImag() * RHS
.getComplexIntReal());
14971 if (Result
.isComplexFloat()) {
14972 // This is an implementation of complex division according to the
14973 // constraints laid out in C11 Annex G. The implementation uses the
14974 // following naming scheme:
14975 // (a + ib) / (c + id)
14976 ComplexValue LHS
= Result
;
14977 APFloat
&A
= LHS
.getComplexFloatReal();
14978 APFloat
&B
= LHS
.getComplexFloatImag();
14979 APFloat
&C
= RHS
.getComplexFloatReal();
14980 APFloat
&D
= RHS
.getComplexFloatImag();
14981 APFloat
&ResR
= Result
.getComplexFloatReal();
14982 APFloat
&ResI
= Result
.getComplexFloatImag();
14988 // No real optimizations we can do here, stub out with zero.
14989 B
= APFloat::getZero(A
.getSemantics());
14992 APFloat MaxCD
= maxnum(abs(C
), abs(D
));
14993 if (MaxCD
.isFinite()) {
14994 DenomLogB
= ilogb(MaxCD
);
14995 C
= scalbn(C
, -DenomLogB
, APFloat::rmNearestTiesToEven
);
14996 D
= scalbn(D
, -DenomLogB
, APFloat::rmNearestTiesToEven
);
14998 APFloat Denom
= C
* C
+ D
* D
;
14999 ResR
= scalbn((A
* C
+ B
* D
) / Denom
, -DenomLogB
,
15000 APFloat::rmNearestTiesToEven
);
15001 ResI
= scalbn((B
* C
- A
* D
) / Denom
, -DenomLogB
,
15002 APFloat::rmNearestTiesToEven
);
15003 if (ResR
.isNaN() && ResI
.isNaN()) {
15004 if (Denom
.isPosZero() && (!A
.isNaN() || !B
.isNaN())) {
15005 ResR
= APFloat::getInf(ResR
.getSemantics(), C
.isNegative()) * A
;
15006 ResI
= APFloat::getInf(ResR
.getSemantics(), C
.isNegative()) * B
;
15007 } else if ((A
.isInfinity() || B
.isInfinity()) && C
.isFinite() &&
15009 A
= APFloat::copySign(
15010 APFloat(A
.getSemantics(), A
.isInfinity() ? 1 : 0), A
);
15011 B
= APFloat::copySign(
15012 APFloat(B
.getSemantics(), B
.isInfinity() ? 1 : 0), B
);
15013 ResR
= APFloat::getInf(ResR
.getSemantics()) * (A
* C
+ B
* D
);
15014 ResI
= APFloat::getInf(ResI
.getSemantics()) * (B
* C
- A
* D
);
15015 } else if (MaxCD
.isInfinity() && A
.isFinite() && B
.isFinite()) {
15016 C
= APFloat::copySign(
15017 APFloat(C
.getSemantics(), C
.isInfinity() ? 1 : 0), C
);
15018 D
= APFloat::copySign(
15019 APFloat(D
.getSemantics(), D
.isInfinity() ? 1 : 0), D
);
15020 ResR
= APFloat::getZero(ResR
.getSemantics()) * (A
* C
+ B
* D
);
15021 ResI
= APFloat::getZero(ResI
.getSemantics()) * (B
* C
- A
* D
);
15026 if (RHS
.getComplexIntReal() == 0 && RHS
.getComplexIntImag() == 0)
15027 return Error(E
, diag::note_expr_divide_by_zero
);
15029 ComplexValue LHS
= Result
;
15030 APSInt Den
= RHS
.getComplexIntReal() * RHS
.getComplexIntReal() +
15031 RHS
.getComplexIntImag() * RHS
.getComplexIntImag();
15032 Result
.getComplexIntReal() =
15033 (LHS
.getComplexIntReal() * RHS
.getComplexIntReal() +
15034 LHS
.getComplexIntImag() * RHS
.getComplexIntImag()) / Den
;
15035 Result
.getComplexIntImag() =
15036 (LHS
.getComplexIntImag() * RHS
.getComplexIntReal() -
15037 LHS
.getComplexIntReal() * RHS
.getComplexIntImag()) / Den
;
15045 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator
*E
) {
15046 // Get the operand value into 'Result'.
15047 if (!Visit(E
->getSubExpr()))
15050 switch (E
->getOpcode()) {
15056 // The result is always just the subexpr.
15059 if (Result
.isComplexFloat()) {
15060 Result
.getComplexFloatReal().changeSign();
15061 Result
.getComplexFloatImag().changeSign();
15064 Result
.getComplexIntReal() = -Result
.getComplexIntReal();
15065 Result
.getComplexIntImag() = -Result
.getComplexIntImag();
15069 if (Result
.isComplexFloat())
15070 Result
.getComplexFloatImag().changeSign();
15072 Result
.getComplexIntImag() = -Result
.getComplexIntImag();
15077 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr
*E
) {
15078 if (E
->getNumInits() == 2) {
15079 if (E
->getType()->isComplexType()) {
15080 Result
.makeComplexFloat();
15081 if (!EvaluateFloat(E
->getInit(0), Result
.FloatReal
, Info
))
15083 if (!EvaluateFloat(E
->getInit(1), Result
.FloatImag
, Info
))
15086 Result
.makeComplexInt();
15087 if (!EvaluateInteger(E
->getInit(0), Result
.IntReal
, Info
))
15089 if (!EvaluateInteger(E
->getInit(1), Result
.IntImag
, Info
))
15094 return ExprEvaluatorBaseTy::VisitInitListExpr(E
);
15097 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr
*E
) {
15098 if (!IsConstantEvaluatedBuiltinCall(E
))
15099 return ExprEvaluatorBaseTy::VisitCallExpr(E
);
15101 switch (E
->getBuiltinCallee()) {
15102 case Builtin::BI__builtin_complex
:
15103 Result
.makeComplexFloat();
15104 if (!EvaluateFloat(E
->getArg(0), Result
.FloatReal
, Info
))
15106 if (!EvaluateFloat(E
->getArg(1), Result
.FloatImag
, Info
))
15115 //===----------------------------------------------------------------------===//
15116 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
15117 // implicit conversion.
15118 //===----------------------------------------------------------------------===//
15121 class AtomicExprEvaluator
:
15122 public ExprEvaluatorBase
<AtomicExprEvaluator
> {
15123 const LValue
*This
;
15126 AtomicExprEvaluator(EvalInfo
&Info
, const LValue
*This
, APValue
&Result
)
15127 : ExprEvaluatorBaseTy(Info
), This(This
), Result(Result
) {}
15129 bool Success(const APValue
&V
, const Expr
*E
) {
15134 bool ZeroInitialization(const Expr
*E
) {
15135 ImplicitValueInitExpr
VIE(
15136 E
->getType()->castAs
<AtomicType
>()->getValueType());
15137 // For atomic-qualified class (and array) types in C++, initialize the
15138 // _Atomic-wrapped subobject directly, in-place.
15139 return This
? EvaluateInPlace(Result
, Info
, *This
, &VIE
)
15140 : Evaluate(Result
, Info
, &VIE
);
15143 bool VisitCastExpr(const CastExpr
*E
) {
15144 switch (E
->getCastKind()) {
15146 return ExprEvaluatorBaseTy::VisitCastExpr(E
);
15147 case CK_NullToPointer
:
15148 VisitIgnoredValue(E
->getSubExpr());
15149 return ZeroInitialization(E
);
15150 case CK_NonAtomicToAtomic
:
15151 return This
? EvaluateInPlace(Result
, Info
, *This
, E
->getSubExpr())
15152 : Evaluate(Result
, Info
, E
->getSubExpr());
15156 } // end anonymous namespace
15158 static bool EvaluateAtomic(const Expr
*E
, const LValue
*This
, APValue
&Result
,
15160 assert(!E
->isValueDependent());
15161 assert(E
->isPRValue() && E
->getType()->isAtomicType());
15162 return AtomicExprEvaluator(Info
, This
, Result
).Visit(E
);
15165 //===----------------------------------------------------------------------===//
15166 // Void expression evaluation, primarily for a cast to void on the LHS of a
15168 //===----------------------------------------------------------------------===//
15171 class VoidExprEvaluator
15172 : public ExprEvaluatorBase
<VoidExprEvaluator
> {
15174 VoidExprEvaluator(EvalInfo
&Info
) : ExprEvaluatorBaseTy(Info
) {}
15176 bool Success(const APValue
&V
, const Expr
*e
) { return true; }
15178 bool ZeroInitialization(const Expr
*E
) { return true; }
15180 bool VisitCastExpr(const CastExpr
*E
) {
15181 switch (E
->getCastKind()) {
15183 return ExprEvaluatorBaseTy::VisitCastExpr(E
);
15185 VisitIgnoredValue(E
->getSubExpr());
15190 bool VisitCallExpr(const CallExpr
*E
) {
15191 if (!IsConstantEvaluatedBuiltinCall(E
))
15192 return ExprEvaluatorBaseTy::VisitCallExpr(E
);
15194 switch (E
->getBuiltinCallee()) {
15195 case Builtin::BI__assume
:
15196 case Builtin::BI__builtin_assume
:
15197 // The argument is not evaluated!
15200 case Builtin::BI__builtin_operator_delete
:
15201 return HandleOperatorDeleteCall(Info
, E
);
15208 bool VisitCXXDeleteExpr(const CXXDeleteExpr
*E
);
15210 } // end anonymous namespace
15212 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr
*E
) {
15213 // We cannot speculatively evaluate a delete expression.
15214 if (Info
.SpeculativeEvaluationDepth
)
15217 FunctionDecl
*OperatorDelete
= E
->getOperatorDelete();
15218 if (!OperatorDelete
->isReplaceableGlobalAllocationFunction()) {
15219 Info
.FFDiag(E
, diag::note_constexpr_new_non_replaceable
)
15220 << isa
<CXXMethodDecl
>(OperatorDelete
) << OperatorDelete
;
15224 const Expr
*Arg
= E
->getArgument();
15227 if (!EvaluatePointer(Arg
, Pointer
, Info
))
15229 if (Pointer
.Designator
.Invalid
)
15232 // Deleting a null pointer has no effect.
15233 if (Pointer
.isNullPointer()) {
15234 // This is the only case where we need to produce an extension warning:
15235 // the only other way we can succeed is if we find a dynamic allocation,
15236 // and we will have warned when we allocated it in that case.
15237 if (!Info
.getLangOpts().CPlusPlus20
)
15238 Info
.CCEDiag(E
, diag::note_constexpr_new
);
15242 std::optional
<DynAlloc
*> Alloc
= CheckDeleteKind(
15243 Info
, E
, Pointer
, E
->isArrayForm() ? DynAlloc::ArrayNew
: DynAlloc::New
);
15246 QualType AllocType
= Pointer
.Base
.getDynamicAllocType();
15248 // For the non-array case, the designator must be empty if the static type
15249 // does not have a virtual destructor.
15250 if (!E
->isArrayForm() && Pointer
.Designator
.Entries
.size() != 0 &&
15251 !hasVirtualDestructor(Arg
->getType()->getPointeeType())) {
15252 Info
.FFDiag(E
, diag::note_constexpr_delete_base_nonvirt_dtor
)
15253 << Arg
->getType()->getPointeeType() << AllocType
;
15257 // For a class type with a virtual destructor, the selected operator delete
15258 // is the one looked up when building the destructor.
15259 if (!E
->isArrayForm() && !E
->isGlobalDelete()) {
15260 const FunctionDecl
*VirtualDelete
= getVirtualOperatorDelete(AllocType
);
15261 if (VirtualDelete
&&
15262 !VirtualDelete
->isReplaceableGlobalAllocationFunction()) {
15263 Info
.FFDiag(E
, diag::note_constexpr_new_non_replaceable
)
15264 << isa
<CXXMethodDecl
>(VirtualDelete
) << VirtualDelete
;
15269 if (!HandleDestruction(Info
, E
->getExprLoc(), Pointer
.getLValueBase(),
15270 (*Alloc
)->Value
, AllocType
))
15273 if (!Info
.HeapAllocs
.erase(Pointer
.Base
.dyn_cast
<DynamicAllocLValue
>())) {
15274 // The element was already erased. This means the destructor call also
15275 // deleted the object.
15276 // FIXME: This probably results in undefined behavior before we get this
15277 // far, and should be diagnosed elsewhere first.
15278 Info
.FFDiag(E
, diag::note_constexpr_double_delete
);
15285 static bool EvaluateVoid(const Expr
*E
, EvalInfo
&Info
) {
15286 assert(!E
->isValueDependent());
15287 assert(E
->isPRValue() && E
->getType()->isVoidType());
15288 return VoidExprEvaluator(Info
).Visit(E
);
15291 //===----------------------------------------------------------------------===//
15292 // Top level Expr::EvaluateAsRValue method.
15293 //===----------------------------------------------------------------------===//
15295 static bool Evaluate(APValue
&Result
, EvalInfo
&Info
, const Expr
*E
) {
15296 assert(!E
->isValueDependent());
15297 // In C, function designators are not lvalues, but we evaluate them as if they
15299 QualType T
= E
->getType();
15300 if (E
->isGLValue() || T
->isFunctionType()) {
15302 if (!EvaluateLValue(E
, LV
, Info
))
15304 LV
.moveInto(Result
);
15305 } else if (T
->isVectorType()) {
15306 if (!EvaluateVector(E
, Result
, Info
))
15308 } else if (T
->isIntegralOrEnumerationType()) {
15309 if (!IntExprEvaluator(Info
, Result
).Visit(E
))
15311 } else if (T
->hasPointerRepresentation()) {
15313 if (!EvaluatePointer(E
, LV
, Info
))
15315 LV
.moveInto(Result
);
15316 } else if (T
->isRealFloatingType()) {
15317 llvm::APFloat
F(0.0);
15318 if (!EvaluateFloat(E
, F
, Info
))
15320 Result
= APValue(F
);
15321 } else if (T
->isAnyComplexType()) {
15323 if (!EvaluateComplex(E
, C
, Info
))
15325 C
.moveInto(Result
);
15326 } else if (T
->isFixedPointType()) {
15327 if (!FixedPointExprEvaluator(Info
, Result
).Visit(E
)) return false;
15328 } else if (T
->isMemberPointerType()) {
15330 if (!EvaluateMemberPointer(E
, P
, Info
))
15332 P
.moveInto(Result
);
15334 } else if (T
->isArrayType()) {
15337 Info
.CurrentCall
->createTemporary(E
, T
, ScopeKind::FullExpression
, LV
);
15338 if (!EvaluateArray(E
, LV
, Value
, Info
))
15341 } else if (T
->isRecordType()) {
15344 Info
.CurrentCall
->createTemporary(E
, T
, ScopeKind::FullExpression
, LV
);
15345 if (!EvaluateRecord(E
, LV
, Value
, Info
))
15348 } else if (T
->isVoidType()) {
15349 if (!Info
.getLangOpts().CPlusPlus11
)
15350 Info
.CCEDiag(E
, diag::note_constexpr_nonliteral
)
15352 if (!EvaluateVoid(E
, Info
))
15354 } else if (T
->isAtomicType()) {
15355 QualType Unqual
= T
.getAtomicUnqualifiedType();
15356 if (Unqual
->isArrayType() || Unqual
->isRecordType()) {
15358 APValue
&Value
= Info
.CurrentCall
->createTemporary(
15359 E
, Unqual
, ScopeKind::FullExpression
, LV
);
15360 if (!EvaluateAtomic(E
, &LV
, Value
, Info
))
15364 if (!EvaluateAtomic(E
, nullptr, Result
, Info
))
15367 } else if (Info
.getLangOpts().CPlusPlus11
) {
15368 Info
.FFDiag(E
, diag::note_constexpr_nonliteral
) << E
->getType();
15371 Info
.FFDiag(E
, diag::note_invalid_subexpr_in_const_expr
);
15378 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
15379 /// cases, the in-place evaluation is essential, since later initializers for
15380 /// an object can indirectly refer to subobjects which were initialized earlier.
15381 static bool EvaluateInPlace(APValue
&Result
, EvalInfo
&Info
, const LValue
&This
,
15382 const Expr
*E
, bool AllowNonLiteralTypes
) {
15383 assert(!E
->isValueDependent());
15385 if (!AllowNonLiteralTypes
&& !CheckLiteralType(Info
, E
, &This
))
15388 if (E
->isPRValue()) {
15389 // Evaluate arrays and record types in-place, so that later initializers can
15390 // refer to earlier-initialized members of the object.
15391 QualType T
= E
->getType();
15392 if (T
->isArrayType())
15393 return EvaluateArray(E
, This
, Result
, Info
);
15394 else if (T
->isRecordType())
15395 return EvaluateRecord(E
, This
, Result
, Info
);
15396 else if (T
->isAtomicType()) {
15397 QualType Unqual
= T
.getAtomicUnqualifiedType();
15398 if (Unqual
->isArrayType() || Unqual
->isRecordType())
15399 return EvaluateAtomic(E
, &This
, Result
, Info
);
15403 // For any other type, in-place evaluation is unimportant.
15404 return Evaluate(Result
, Info
, E
);
15407 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
15408 /// lvalue-to-rvalue cast if it is an lvalue.
15409 static bool EvaluateAsRValue(EvalInfo
&Info
, const Expr
*E
, APValue
&Result
) {
15410 assert(!E
->isValueDependent());
15412 if (E
->getType().isNull())
15415 if (!CheckLiteralType(Info
, E
))
15418 if (Info
.EnableNewConstInterp
) {
15419 if (!Info
.Ctx
.getInterpContext().evaluateAsRValue(Info
, E
, Result
))
15422 if (!::Evaluate(Result
, Info
, E
))
15426 // Implicit lvalue-to-rvalue cast.
15427 if (E
->isGLValue()) {
15429 LV
.setFrom(Info
.Ctx
, Result
);
15430 if (!handleLValueToRValueConversion(Info
, E
, E
->getType(), LV
, Result
))
15434 // Check this core constant expression is a constant expression.
15435 return CheckConstantExpression(Info
, E
->getExprLoc(), E
->getType(), Result
,
15436 ConstantExprKind::Normal
) &&
15437 CheckMemoryLeaks(Info
);
15440 static bool FastEvaluateAsRValue(const Expr
*Exp
, Expr::EvalResult
&Result
,
15441 const ASTContext
&Ctx
, bool &IsConst
) {
15442 // Fast-path evaluations of integer literals, since we sometimes see files
15443 // containing vast quantities of these.
15444 if (const IntegerLiteral
*L
= dyn_cast
<IntegerLiteral
>(Exp
)) {
15445 Result
.Val
= APValue(APSInt(L
->getValue(),
15446 L
->getType()->isUnsignedIntegerType()));
15451 if (const auto *L
= dyn_cast
<CXXBoolLiteralExpr
>(Exp
)) {
15452 Result
.Val
= APValue(APSInt(APInt(1, L
->getValue())));
15457 if (const auto *CE
= dyn_cast
<ConstantExpr
>(Exp
)) {
15458 if (CE
->hasAPValueResult()) {
15459 Result
.Val
= CE
->getAPValueResult();
15464 // The SubExpr is usually just an IntegerLiteral.
15465 return FastEvaluateAsRValue(CE
->getSubExpr(), Result
, Ctx
, IsConst
);
15468 // This case should be rare, but we need to check it before we check on
15470 if (Exp
->getType().isNull()) {
15478 static bool hasUnacceptableSideEffect(Expr::EvalStatus
&Result
,
15479 Expr::SideEffectsKind SEK
) {
15480 return (SEK
< Expr::SE_AllowSideEffects
&& Result
.HasSideEffects
) ||
15481 (SEK
< Expr::SE_AllowUndefinedBehavior
&& Result
.HasUndefinedBehavior
);
15484 static bool EvaluateAsRValue(const Expr
*E
, Expr::EvalResult
&Result
,
15485 const ASTContext
&Ctx
, EvalInfo
&Info
) {
15486 assert(!E
->isValueDependent());
15488 if (FastEvaluateAsRValue(E
, Result
, Ctx
, IsConst
))
15491 return EvaluateAsRValue(Info
, E
, Result
.Val
);
15494 static bool EvaluateAsInt(const Expr
*E
, Expr::EvalResult
&ExprResult
,
15495 const ASTContext
&Ctx
,
15496 Expr::SideEffectsKind AllowSideEffects
,
15498 assert(!E
->isValueDependent());
15499 if (!E
->getType()->isIntegralOrEnumerationType())
15502 if (!::EvaluateAsRValue(E
, ExprResult
, Ctx
, Info
) ||
15503 !ExprResult
.Val
.isInt() ||
15504 hasUnacceptableSideEffect(ExprResult
, AllowSideEffects
))
15510 static bool EvaluateAsFixedPoint(const Expr
*E
, Expr::EvalResult
&ExprResult
,
15511 const ASTContext
&Ctx
,
15512 Expr::SideEffectsKind AllowSideEffects
,
15514 assert(!E
->isValueDependent());
15515 if (!E
->getType()->isFixedPointType())
15518 if (!::EvaluateAsRValue(E
, ExprResult
, Ctx
, Info
))
15521 if (!ExprResult
.Val
.isFixedPoint() ||
15522 hasUnacceptableSideEffect(ExprResult
, AllowSideEffects
))
15528 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
15529 /// any crazy technique (that has nothing to do with language standards) that
15530 /// we want to. If this function returns true, it returns the folded constant
15531 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
15532 /// will be applied to the result.
15533 bool Expr::EvaluateAsRValue(EvalResult
&Result
, const ASTContext
&Ctx
,
15534 bool InConstantContext
) const {
15535 assert(!isValueDependent() &&
15536 "Expression evaluator can't be called on a dependent expression.");
15537 ExprTimeTraceScope
TimeScope(this, Ctx
, "EvaluateAsRValue");
15538 EvalInfo
Info(Ctx
, Result
, EvalInfo::EM_IgnoreSideEffects
);
15539 Info
.InConstantContext
= InConstantContext
;
15540 return ::EvaluateAsRValue(this, Result
, Ctx
, Info
);
15543 bool Expr::EvaluateAsBooleanCondition(bool &Result
, const ASTContext
&Ctx
,
15544 bool InConstantContext
) const {
15545 assert(!isValueDependent() &&
15546 "Expression evaluator can't be called on a dependent expression.");
15547 ExprTimeTraceScope
TimeScope(this, Ctx
, "EvaluateAsBooleanCondition");
15548 EvalResult Scratch
;
15549 return EvaluateAsRValue(Scratch
, Ctx
, InConstantContext
) &&
15550 HandleConversionToBool(Scratch
.Val
, Result
);
15553 bool Expr::EvaluateAsInt(EvalResult
&Result
, const ASTContext
&Ctx
,
15554 SideEffectsKind AllowSideEffects
,
15555 bool InConstantContext
) const {
15556 assert(!isValueDependent() &&
15557 "Expression evaluator can't be called on a dependent expression.");
15558 ExprTimeTraceScope
TimeScope(this, Ctx
, "EvaluateAsInt");
15559 EvalInfo
Info(Ctx
, Result
, EvalInfo::EM_IgnoreSideEffects
);
15560 Info
.InConstantContext
= InConstantContext
;
15561 return ::EvaluateAsInt(this, Result
, Ctx
, AllowSideEffects
, Info
);
15564 bool Expr::EvaluateAsFixedPoint(EvalResult
&Result
, const ASTContext
&Ctx
,
15565 SideEffectsKind AllowSideEffects
,
15566 bool InConstantContext
) const {
15567 assert(!isValueDependent() &&
15568 "Expression evaluator can't be called on a dependent expression.");
15569 ExprTimeTraceScope
TimeScope(this, Ctx
, "EvaluateAsFixedPoint");
15570 EvalInfo
Info(Ctx
, Result
, EvalInfo::EM_IgnoreSideEffects
);
15571 Info
.InConstantContext
= InConstantContext
;
15572 return ::EvaluateAsFixedPoint(this, Result
, Ctx
, AllowSideEffects
, Info
);
15575 bool Expr::EvaluateAsFloat(APFloat
&Result
, const ASTContext
&Ctx
,
15576 SideEffectsKind AllowSideEffects
,
15577 bool InConstantContext
) const {
15578 assert(!isValueDependent() &&
15579 "Expression evaluator can't be called on a dependent expression.");
15581 if (!getType()->isRealFloatingType())
15584 ExprTimeTraceScope
TimeScope(this, Ctx
, "EvaluateAsFloat");
15585 EvalResult ExprResult
;
15586 if (!EvaluateAsRValue(ExprResult
, Ctx
, InConstantContext
) ||
15587 !ExprResult
.Val
.isFloat() ||
15588 hasUnacceptableSideEffect(ExprResult
, AllowSideEffects
))
15591 Result
= ExprResult
.Val
.getFloat();
15595 bool Expr::EvaluateAsLValue(EvalResult
&Result
, const ASTContext
&Ctx
,
15596 bool InConstantContext
) const {
15597 assert(!isValueDependent() &&
15598 "Expression evaluator can't be called on a dependent expression.");
15600 ExprTimeTraceScope
TimeScope(this, Ctx
, "EvaluateAsLValue");
15601 EvalInfo
Info(Ctx
, Result
, EvalInfo::EM_ConstantFold
);
15602 Info
.InConstantContext
= InConstantContext
;
15604 CheckedTemporaries CheckedTemps
;
15605 if (!EvaluateLValue(this, LV
, Info
) || !Info
.discardCleanups() ||
15606 Result
.HasSideEffects
||
15607 !CheckLValueConstantExpression(Info
, getExprLoc(),
15608 Ctx
.getLValueReferenceType(getType()), LV
,
15609 ConstantExprKind::Normal
, CheckedTemps
))
15612 LV
.moveInto(Result
.Val
);
15616 static bool EvaluateDestruction(const ASTContext
&Ctx
, APValue::LValueBase Base
,
15617 APValue DestroyedValue
, QualType Type
,
15618 SourceLocation Loc
, Expr::EvalStatus
&EStatus
,
15619 bool IsConstantDestruction
) {
15620 EvalInfo
Info(Ctx
, EStatus
,
15621 IsConstantDestruction
? EvalInfo::EM_ConstantExpression
15622 : EvalInfo::EM_ConstantFold
);
15623 Info
.setEvaluatingDecl(Base
, DestroyedValue
,
15624 EvalInfo::EvaluatingDeclKind::Dtor
);
15625 Info
.InConstantContext
= IsConstantDestruction
;
15630 if (!HandleDestruction(Info
, Loc
, Base
, DestroyedValue
, Type
) ||
15631 EStatus
.HasSideEffects
)
15634 if (!Info
.discardCleanups())
15635 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15640 bool Expr::EvaluateAsConstantExpr(EvalResult
&Result
, const ASTContext
&Ctx
,
15641 ConstantExprKind Kind
) const {
15642 assert(!isValueDependent() &&
15643 "Expression evaluator can't be called on a dependent expression.");
15645 if (FastEvaluateAsRValue(this, Result
, Ctx
, IsConst
) && Result
.Val
.hasValue())
15648 ExprTimeTraceScope
TimeScope(this, Ctx
, "EvaluateAsConstantExpr");
15649 EvalInfo::EvaluationMode EM
= EvalInfo::EM_ConstantExpression
;
15650 EvalInfo
Info(Ctx
, Result
, EM
);
15651 Info
.InConstantContext
= true;
15653 // The type of the object we're initializing is 'const T' for a class NTTP.
15654 QualType T
= getType();
15655 if (Kind
== ConstantExprKind::ClassTemplateArgument
)
15658 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
15659 // represent the result of the evaluation. CheckConstantExpression ensures
15660 // this doesn't escape.
15661 MaterializeTemporaryExpr
BaseMTE(T
, const_cast<Expr
*>(this), true);
15662 APValue::LValueBase
Base(&BaseMTE
);
15664 Info
.setEvaluatingDecl(Base
, Result
.Val
);
15669 // C++23 [intro.execution]/p5
15670 // A full-expression is [...] a constant-expression
15671 // So we need to make sure temporary objects are destroyed after having
15672 // evaluating the expression (per C++23 [class.temporary]/p4).
15673 FullExpressionRAII
Scope(Info
);
15674 if (!::EvaluateInPlace(Result
.Val
, Info
, LVal
, this) ||
15675 Result
.HasSideEffects
|| !Scope
.destroy())
15679 if (!Info
.discardCleanups())
15680 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15682 if (!CheckConstantExpression(Info
, getExprLoc(), getStorageType(Ctx
, this),
15685 if (!CheckMemoryLeaks(Info
))
15688 // If this is a class template argument, it's required to have constant
15689 // destruction too.
15690 if (Kind
== ConstantExprKind::ClassTemplateArgument
&&
15691 (!EvaluateDestruction(Ctx
, Base
, Result
.Val
, T
, getBeginLoc(), Result
,
15693 Result
.HasSideEffects
)) {
15694 // FIXME: Prefix a note to indicate that the problem is lack of constant
15702 bool Expr::EvaluateAsInitializer(APValue
&Value
, const ASTContext
&Ctx
,
15704 SmallVectorImpl
<PartialDiagnosticAt
> &Notes
,
15705 bool IsConstantInitialization
) const {
15706 assert(!isValueDependent() &&
15707 "Expression evaluator can't be called on a dependent expression.");
15709 llvm::TimeTraceScope
TimeScope("EvaluateAsInitializer", [&] {
15711 llvm::raw_string_ostream
OS(Name
);
15712 VD
->printQualifiedName(OS
);
15716 Expr::EvalStatus EStatus
;
15717 EStatus
.Diag
= &Notes
;
15719 EvalInfo
Info(Ctx
, EStatus
,
15720 (IsConstantInitialization
&& Ctx
.getLangOpts().CPlusPlus
)
15721 ? EvalInfo::EM_ConstantExpression
15722 : EvalInfo::EM_ConstantFold
);
15723 Info
.setEvaluatingDecl(VD
, Value
);
15724 Info
.InConstantContext
= IsConstantInitialization
;
15726 if (Info
.EnableNewConstInterp
) {
15727 auto &InterpCtx
= const_cast<ASTContext
&>(Ctx
).getInterpContext();
15728 if (!InterpCtx
.evaluateAsInitializer(Info
, VD
, Value
))
15734 if (!EvaluateInPlace(Value
, Info
, LVal
, this,
15735 /*AllowNonLiteralTypes=*/true) ||
15736 EStatus
.HasSideEffects
)
15739 // At this point, any lifetime-extended temporaries are completely
15741 Info
.performLifetimeExtension();
15743 if (!Info
.discardCleanups())
15744 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15747 SourceLocation DeclLoc
= VD
->getLocation();
15748 QualType DeclTy
= VD
->getType();
15749 return CheckConstantExpression(Info
, DeclLoc
, DeclTy
, Value
,
15750 ConstantExprKind::Normal
) &&
15751 CheckMemoryLeaks(Info
);
15754 bool VarDecl::evaluateDestruction(
15755 SmallVectorImpl
<PartialDiagnosticAt
> &Notes
) const {
15756 Expr::EvalStatus EStatus
;
15757 EStatus
.Diag
= &Notes
;
15759 // Only treat the destruction as constant destruction if we formally have
15760 // constant initialization (or are usable in a constant expression).
15761 bool IsConstantDestruction
= hasConstantInitialization();
15763 // Make a copy of the value for the destructor to mutate, if we know it.
15764 // Otherwise, treat the value as default-initialized; if the destructor works
15765 // anyway, then the destruction is constant (and must be essentially empty).
15766 APValue DestroyedValue
;
15767 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
15768 DestroyedValue
= *getEvaluatedValue();
15769 else if (!handleDefaultInitValue(getType(), DestroyedValue
))
15772 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue
),
15773 getType(), getLocation(), EStatus
,
15774 IsConstantDestruction
) ||
15775 EStatus
.HasSideEffects
)
15778 ensureEvaluatedStmt()->HasConstantDestruction
= true;
15782 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
15783 /// constant folded, but discard the result.
15784 bool Expr::isEvaluatable(const ASTContext
&Ctx
, SideEffectsKind SEK
) const {
15785 assert(!isValueDependent() &&
15786 "Expression evaluator can't be called on a dependent expression.");
15789 return EvaluateAsRValue(Result
, Ctx
, /* in constant context */ true) &&
15790 !hasUnacceptableSideEffect(Result
, SEK
);
15793 APSInt
Expr::EvaluateKnownConstInt(const ASTContext
&Ctx
,
15794 SmallVectorImpl
<PartialDiagnosticAt
> *Diag
) const {
15795 assert(!isValueDependent() &&
15796 "Expression evaluator can't be called on a dependent expression.");
15798 ExprTimeTraceScope
TimeScope(this, Ctx
, "EvaluateKnownConstInt");
15799 EvalResult EVResult
;
15800 EVResult
.Diag
= Diag
;
15801 EvalInfo
Info(Ctx
, EVResult
, EvalInfo::EM_IgnoreSideEffects
);
15802 Info
.InConstantContext
= true;
15804 bool Result
= ::EvaluateAsRValue(this, EVResult
, Ctx
, Info
);
15806 assert(Result
&& "Could not evaluate expression");
15807 assert(EVResult
.Val
.isInt() && "Expression did not evaluate to integer");
15809 return EVResult
.Val
.getInt();
15812 APSInt
Expr::EvaluateKnownConstIntCheckOverflow(
15813 const ASTContext
&Ctx
, SmallVectorImpl
<PartialDiagnosticAt
> *Diag
) const {
15814 assert(!isValueDependent() &&
15815 "Expression evaluator can't be called on a dependent expression.");
15817 ExprTimeTraceScope
TimeScope(this, Ctx
, "EvaluateKnownConstIntCheckOverflow");
15818 EvalResult EVResult
;
15819 EVResult
.Diag
= Diag
;
15820 EvalInfo
Info(Ctx
, EVResult
, EvalInfo::EM_IgnoreSideEffects
);
15821 Info
.InConstantContext
= true;
15822 Info
.CheckingForUndefinedBehavior
= true;
15824 bool Result
= ::EvaluateAsRValue(Info
, this, EVResult
.Val
);
15826 assert(Result
&& "Could not evaluate expression");
15827 assert(EVResult
.Val
.isInt() && "Expression did not evaluate to integer");
15829 return EVResult
.Val
.getInt();
15832 void Expr::EvaluateForOverflow(const ASTContext
&Ctx
) const {
15833 assert(!isValueDependent() &&
15834 "Expression evaluator can't be called on a dependent expression.");
15836 ExprTimeTraceScope
TimeScope(this, Ctx
, "EvaluateForOverflow");
15838 EvalResult EVResult
;
15839 if (!FastEvaluateAsRValue(this, EVResult
, Ctx
, IsConst
)) {
15840 EvalInfo
Info(Ctx
, EVResult
, EvalInfo::EM_IgnoreSideEffects
);
15841 Info
.CheckingForUndefinedBehavior
= true;
15842 (void)::EvaluateAsRValue(Info
, this, EVResult
.Val
);
15846 bool Expr::EvalResult::isGlobalLValue() const {
15847 assert(Val
.isLValue());
15848 return IsGlobalLValue(Val
.getLValueBase());
15851 /// isIntegerConstantExpr - this recursive routine will test if an expression is
15852 /// an integer constant expression.
15854 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15857 // CheckICE - This function does the fundamental ICE checking: the returned
15858 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15859 // and a (possibly null) SourceLocation indicating the location of the problem.
15861 // Note that to reduce code duplication, this helper does no evaluation
15862 // itself; the caller checks whether the expression is evaluatable, and
15863 // in the rare cases where CheckICE actually cares about the evaluated
15864 // value, it calls into Evaluate.
15869 /// This expression is an ICE.
15871 /// This expression is not an ICE, but if it isn't evaluated, it's
15872 /// a legal subexpression for an ICE. This return value is used to handle
15873 /// the comma operator in C99 mode, and non-constant subexpressions.
15874 IK_ICEIfUnevaluated
,
15875 /// This expression is not an ICE, and is not a legal subexpression for one.
15881 SourceLocation Loc
;
15883 ICEDiag(ICEKind IK
, SourceLocation l
) : Kind(IK
), Loc(l
) {}
15888 static ICEDiag
NoDiag() { return ICEDiag(IK_ICE
, SourceLocation()); }
15890 static ICEDiag
Worst(ICEDiag A
, ICEDiag B
) { return A
.Kind
>= B
.Kind
? A
: B
; }
15892 static ICEDiag
CheckEvalInICE(const Expr
* E
, const ASTContext
&Ctx
) {
15893 Expr::EvalResult EVResult
;
15894 Expr::EvalStatus Status
;
15895 EvalInfo
Info(Ctx
, Status
, EvalInfo::EM_ConstantExpression
);
15897 Info
.InConstantContext
= true;
15898 if (!::EvaluateAsRValue(E
, EVResult
, Ctx
, Info
) || EVResult
.HasSideEffects
||
15899 !EVResult
.Val
.isInt())
15900 return ICEDiag(IK_NotICE
, E
->getBeginLoc());
15905 static ICEDiag
CheckICE(const Expr
* E
, const ASTContext
&Ctx
) {
15906 assert(!E
->isValueDependent() && "Should not see value dependent exprs!");
15907 if (!E
->getType()->isIntegralOrEnumerationType())
15908 return ICEDiag(IK_NotICE
, E
->getBeginLoc());
15910 switch (E
->getStmtClass()) {
15911 #define ABSTRACT_STMT(Node)
15912 #define STMT(Node, Base) case Expr::Node##Class:
15913 #define EXPR(Node, Base)
15914 #include "clang/AST/StmtNodes.inc"
15915 case Expr::PredefinedExprClass
:
15916 case Expr::FloatingLiteralClass
:
15917 case Expr::ImaginaryLiteralClass
:
15918 case Expr::StringLiteralClass
:
15919 case Expr::ArraySubscriptExprClass
:
15920 case Expr::MatrixSubscriptExprClass
:
15921 case Expr::OMPArraySectionExprClass
:
15922 case Expr::OMPArrayShapingExprClass
:
15923 case Expr::OMPIteratorExprClass
:
15924 case Expr::MemberExprClass
:
15925 case Expr::CompoundAssignOperatorClass
:
15926 case Expr::CompoundLiteralExprClass
:
15927 case Expr::ExtVectorElementExprClass
:
15928 case Expr::DesignatedInitExprClass
:
15929 case Expr::ArrayInitLoopExprClass
:
15930 case Expr::ArrayInitIndexExprClass
:
15931 case Expr::NoInitExprClass
:
15932 case Expr::DesignatedInitUpdateExprClass
:
15933 case Expr::ImplicitValueInitExprClass
:
15934 case Expr::ParenListExprClass
:
15935 case Expr::VAArgExprClass
:
15936 case Expr::AddrLabelExprClass
:
15937 case Expr::StmtExprClass
:
15938 case Expr::CXXMemberCallExprClass
:
15939 case Expr::CUDAKernelCallExprClass
:
15940 case Expr::CXXAddrspaceCastExprClass
:
15941 case Expr::CXXDynamicCastExprClass
:
15942 case Expr::CXXTypeidExprClass
:
15943 case Expr::CXXUuidofExprClass
:
15944 case Expr::MSPropertyRefExprClass
:
15945 case Expr::MSPropertySubscriptExprClass
:
15946 case Expr::CXXNullPtrLiteralExprClass
:
15947 case Expr::UserDefinedLiteralClass
:
15948 case Expr::CXXThisExprClass
:
15949 case Expr::CXXThrowExprClass
:
15950 case Expr::CXXNewExprClass
:
15951 case Expr::CXXDeleteExprClass
:
15952 case Expr::CXXPseudoDestructorExprClass
:
15953 case Expr::UnresolvedLookupExprClass
:
15954 case Expr::TypoExprClass
:
15955 case Expr::RecoveryExprClass
:
15956 case Expr::DependentScopeDeclRefExprClass
:
15957 case Expr::CXXConstructExprClass
:
15958 case Expr::CXXInheritedCtorInitExprClass
:
15959 case Expr::CXXStdInitializerListExprClass
:
15960 case Expr::CXXBindTemporaryExprClass
:
15961 case Expr::ExprWithCleanupsClass
:
15962 case Expr::CXXTemporaryObjectExprClass
:
15963 case Expr::CXXUnresolvedConstructExprClass
:
15964 case Expr::CXXDependentScopeMemberExprClass
:
15965 case Expr::UnresolvedMemberExprClass
:
15966 case Expr::ObjCStringLiteralClass
:
15967 case Expr::ObjCBoxedExprClass
:
15968 case Expr::ObjCArrayLiteralClass
:
15969 case Expr::ObjCDictionaryLiteralClass
:
15970 case Expr::ObjCEncodeExprClass
:
15971 case Expr::ObjCMessageExprClass
:
15972 case Expr::ObjCSelectorExprClass
:
15973 case Expr::ObjCProtocolExprClass
:
15974 case Expr::ObjCIvarRefExprClass
:
15975 case Expr::ObjCPropertyRefExprClass
:
15976 case Expr::ObjCSubscriptRefExprClass
:
15977 case Expr::ObjCIsaExprClass
:
15978 case Expr::ObjCAvailabilityCheckExprClass
:
15979 case Expr::ShuffleVectorExprClass
:
15980 case Expr::ConvertVectorExprClass
:
15981 case Expr::BlockExprClass
:
15982 case Expr::NoStmtClass
:
15983 case Expr::OpaqueValueExprClass
:
15984 case Expr::PackExpansionExprClass
:
15985 case Expr::SubstNonTypeTemplateParmPackExprClass
:
15986 case Expr::FunctionParmPackExprClass
:
15987 case Expr::AsTypeExprClass
:
15988 case Expr::ObjCIndirectCopyRestoreExprClass
:
15989 case Expr::MaterializeTemporaryExprClass
:
15990 case Expr::PseudoObjectExprClass
:
15991 case Expr::AtomicExprClass
:
15992 case Expr::LambdaExprClass
:
15993 case Expr::CXXFoldExprClass
:
15994 case Expr::CoawaitExprClass
:
15995 case Expr::DependentCoawaitExprClass
:
15996 case Expr::CoyieldExprClass
:
15997 case Expr::SYCLUniqueStableNameExprClass
:
15998 case Expr::CXXParenListInitExprClass
:
15999 return ICEDiag(IK_NotICE
, E
->getBeginLoc());
16001 case Expr::InitListExprClass
: {
16002 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
16003 // form "T x = { a };" is equivalent to "T x = a;".
16004 // Unless we're initializing a reference, T is a scalar as it is known to be
16005 // of integral or enumeration type.
16006 if (E
->isPRValue())
16007 if (cast
<InitListExpr
>(E
)->getNumInits() == 1)
16008 return CheckICE(cast
<InitListExpr
>(E
)->getInit(0), Ctx
);
16009 return ICEDiag(IK_NotICE
, E
->getBeginLoc());
16012 case Expr::SizeOfPackExprClass
:
16013 case Expr::GNUNullExprClass
:
16014 case Expr::SourceLocExprClass
:
16017 case Expr::SubstNonTypeTemplateParmExprClass
:
16019 CheckICE(cast
<SubstNonTypeTemplateParmExpr
>(E
)->getReplacement(), Ctx
);
16021 case Expr::ConstantExprClass
:
16022 return CheckICE(cast
<ConstantExpr
>(E
)->getSubExpr(), Ctx
);
16024 case Expr::ParenExprClass
:
16025 return CheckICE(cast
<ParenExpr
>(E
)->getSubExpr(), Ctx
);
16026 case Expr::GenericSelectionExprClass
:
16027 return CheckICE(cast
<GenericSelectionExpr
>(E
)->getResultExpr(), Ctx
);
16028 case Expr::IntegerLiteralClass
:
16029 case Expr::FixedPointLiteralClass
:
16030 case Expr::CharacterLiteralClass
:
16031 case Expr::ObjCBoolLiteralExprClass
:
16032 case Expr::CXXBoolLiteralExprClass
:
16033 case Expr::CXXScalarValueInitExprClass
:
16034 case Expr::TypeTraitExprClass
:
16035 case Expr::ConceptSpecializationExprClass
:
16036 case Expr::RequiresExprClass
:
16037 case Expr::ArrayTypeTraitExprClass
:
16038 case Expr::ExpressionTraitExprClass
:
16039 case Expr::CXXNoexceptExprClass
:
16041 case Expr::CallExprClass
:
16042 case Expr::CXXOperatorCallExprClass
: {
16043 // C99 6.6/3 allows function calls within unevaluated subexpressions of
16044 // constant expressions, but they can never be ICEs because an ICE cannot
16045 // contain an operand of (pointer to) function type.
16046 const CallExpr
*CE
= cast
<CallExpr
>(E
);
16047 if (CE
->getBuiltinCallee())
16048 return CheckEvalInICE(E
, Ctx
);
16049 return ICEDiag(IK_NotICE
, E
->getBeginLoc());
16051 case Expr::CXXRewrittenBinaryOperatorClass
:
16052 return CheckICE(cast
<CXXRewrittenBinaryOperator
>(E
)->getSemanticForm(),
16054 case Expr::DeclRefExprClass
: {
16055 const NamedDecl
*D
= cast
<DeclRefExpr
>(E
)->getDecl();
16056 if (isa
<EnumConstantDecl
>(D
))
16059 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
16060 // integer variables in constant expressions:
16063 // A variable of non-volatile const-qualified integral or enumeration
16064 // type initialized by an ICE can be used in ICEs.
16066 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
16067 // that mode, use of reference variables should not be allowed.
16068 const VarDecl
*VD
= dyn_cast
<VarDecl
>(D
);
16069 if (VD
&& VD
->isUsableInConstantExpressions(Ctx
) &&
16070 !VD
->getType()->isReferenceType())
16073 return ICEDiag(IK_NotICE
, E
->getBeginLoc());
16075 case Expr::UnaryOperatorClass
: {
16076 const UnaryOperator
*Exp
= cast
<UnaryOperator
>(E
);
16077 switch (Exp
->getOpcode()) {
16085 // C99 6.6/3 allows increment and decrement within unevaluated
16086 // subexpressions of constant expressions, but they can never be ICEs
16087 // because an ICE cannot contain an lvalue operand.
16088 return ICEDiag(IK_NotICE
, E
->getBeginLoc());
16096 return CheckICE(Exp
->getSubExpr(), Ctx
);
16098 llvm_unreachable("invalid unary operator class");
16100 case Expr::OffsetOfExprClass
: {
16101 // Note that per C99, offsetof must be an ICE. And AFAIK, using
16102 // EvaluateAsRValue matches the proposed gcc behavior for cases like
16103 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
16104 // compliance: we should warn earlier for offsetof expressions with
16105 // array subscripts that aren't ICEs, and if the array subscripts
16106 // are ICEs, the value of the offsetof must be an integer constant.
16107 return CheckEvalInICE(E
, Ctx
);
16109 case Expr::UnaryExprOrTypeTraitExprClass
: {
16110 const UnaryExprOrTypeTraitExpr
*Exp
= cast
<UnaryExprOrTypeTraitExpr
>(E
);
16111 if ((Exp
->getKind() == UETT_SizeOf
) &&
16112 Exp
->getTypeOfArgument()->isVariableArrayType())
16113 return ICEDiag(IK_NotICE
, E
->getBeginLoc());
16116 case Expr::BinaryOperatorClass
: {
16117 const BinaryOperator
*Exp
= cast
<BinaryOperator
>(E
);
16118 switch (Exp
->getOpcode()) {
16132 // C99 6.6/3 allows assignments within unevaluated subexpressions of
16133 // constant expressions, but they can never be ICEs because an ICE cannot
16134 // contain an lvalue operand.
16135 return ICEDiag(IK_NotICE
, E
->getBeginLoc());
16155 ICEDiag LHSResult
= CheckICE(Exp
->getLHS(), Ctx
);
16156 ICEDiag RHSResult
= CheckICE(Exp
->getRHS(), Ctx
);
16157 if (Exp
->getOpcode() == BO_Div
||
16158 Exp
->getOpcode() == BO_Rem
) {
16159 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
16160 // we don't evaluate one.
16161 if (LHSResult
.Kind
== IK_ICE
&& RHSResult
.Kind
== IK_ICE
) {
16162 llvm::APSInt REval
= Exp
->getRHS()->EvaluateKnownConstInt(Ctx
);
16164 return ICEDiag(IK_ICEIfUnevaluated
, E
->getBeginLoc());
16165 if (REval
.isSigned() && REval
.isAllOnes()) {
16166 llvm::APSInt LEval
= Exp
->getLHS()->EvaluateKnownConstInt(Ctx
);
16167 if (LEval
.isMinSignedValue())
16168 return ICEDiag(IK_ICEIfUnevaluated
, E
->getBeginLoc());
16172 if (Exp
->getOpcode() == BO_Comma
) {
16173 if (Ctx
.getLangOpts().C99
) {
16174 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
16175 // if it isn't evaluated.
16176 if (LHSResult
.Kind
== IK_ICE
&& RHSResult
.Kind
== IK_ICE
)
16177 return ICEDiag(IK_ICEIfUnevaluated
, E
->getBeginLoc());
16179 // In both C89 and C++, commas in ICEs are illegal.
16180 return ICEDiag(IK_NotICE
, E
->getBeginLoc());
16183 return Worst(LHSResult
, RHSResult
);
16187 ICEDiag LHSResult
= CheckICE(Exp
->getLHS(), Ctx
);
16188 ICEDiag RHSResult
= CheckICE(Exp
->getRHS(), Ctx
);
16189 if (LHSResult
.Kind
== IK_ICE
&& RHSResult
.Kind
== IK_ICEIfUnevaluated
) {
16190 // Rare case where the RHS has a comma "side-effect"; we need
16191 // to actually check the condition to see whether the side
16192 // with the comma is evaluated.
16193 if ((Exp
->getOpcode() == BO_LAnd
) !=
16194 (Exp
->getLHS()->EvaluateKnownConstInt(Ctx
) == 0))
16199 return Worst(LHSResult
, RHSResult
);
16202 llvm_unreachable("invalid binary operator kind");
16204 case Expr::ImplicitCastExprClass
:
16205 case Expr::CStyleCastExprClass
:
16206 case Expr::CXXFunctionalCastExprClass
:
16207 case Expr::CXXStaticCastExprClass
:
16208 case Expr::CXXReinterpretCastExprClass
:
16209 case Expr::CXXConstCastExprClass
:
16210 case Expr::ObjCBridgedCastExprClass
: {
16211 const Expr
*SubExpr
= cast
<CastExpr
>(E
)->getSubExpr();
16212 if (isa
<ExplicitCastExpr
>(E
)) {
16213 if (const FloatingLiteral
*FL
16214 = dyn_cast
<FloatingLiteral
>(SubExpr
->IgnoreParenImpCasts())) {
16215 unsigned DestWidth
= Ctx
.getIntWidth(E
->getType());
16216 bool DestSigned
= E
->getType()->isSignedIntegerOrEnumerationType();
16217 APSInt
IgnoredVal(DestWidth
, !DestSigned
);
16219 // If the value does not fit in the destination type, the behavior is
16220 // undefined, so we are not required to treat it as a constant
16222 if (FL
->getValue().convertToInteger(IgnoredVal
,
16223 llvm::APFloat::rmTowardZero
,
16224 &Ignored
) & APFloat::opInvalidOp
)
16225 return ICEDiag(IK_NotICE
, E
->getBeginLoc());
16229 switch (cast
<CastExpr
>(E
)->getCastKind()) {
16230 case CK_LValueToRValue
:
16231 case CK_AtomicToNonAtomic
:
16232 case CK_NonAtomicToAtomic
:
16234 case CK_IntegralToBoolean
:
16235 case CK_IntegralCast
:
16236 return CheckICE(SubExpr
, Ctx
);
16238 return ICEDiag(IK_NotICE
, E
->getBeginLoc());
16241 case Expr::BinaryConditionalOperatorClass
: {
16242 const BinaryConditionalOperator
*Exp
= cast
<BinaryConditionalOperator
>(E
);
16243 ICEDiag CommonResult
= CheckICE(Exp
->getCommon(), Ctx
);
16244 if (CommonResult
.Kind
== IK_NotICE
) return CommonResult
;
16245 ICEDiag FalseResult
= CheckICE(Exp
->getFalseExpr(), Ctx
);
16246 if (FalseResult
.Kind
== IK_NotICE
) return FalseResult
;
16247 if (CommonResult
.Kind
== IK_ICEIfUnevaluated
) return CommonResult
;
16248 if (FalseResult
.Kind
== IK_ICEIfUnevaluated
&&
16249 Exp
->getCommon()->EvaluateKnownConstInt(Ctx
) != 0) return NoDiag();
16250 return FalseResult
;
16252 case Expr::ConditionalOperatorClass
: {
16253 const ConditionalOperator
*Exp
= cast
<ConditionalOperator
>(E
);
16254 // If the condition (ignoring parens) is a __builtin_constant_p call,
16255 // then only the true side is actually considered in an integer constant
16256 // expression, and it is fully evaluated. This is an important GNU
16257 // extension. See GCC PR38377 for discussion.
16258 if (const CallExpr
*CallCE
16259 = dyn_cast
<CallExpr
>(Exp
->getCond()->IgnoreParenCasts()))
16260 if (CallCE
->getBuiltinCallee() == Builtin::BI__builtin_constant_p
)
16261 return CheckEvalInICE(E
, Ctx
);
16262 ICEDiag CondResult
= CheckICE(Exp
->getCond(), Ctx
);
16263 if (CondResult
.Kind
== IK_NotICE
)
16266 ICEDiag TrueResult
= CheckICE(Exp
->getTrueExpr(), Ctx
);
16267 ICEDiag FalseResult
= CheckICE(Exp
->getFalseExpr(), Ctx
);
16269 if (TrueResult
.Kind
== IK_NotICE
)
16271 if (FalseResult
.Kind
== IK_NotICE
)
16272 return FalseResult
;
16273 if (CondResult
.Kind
== IK_ICEIfUnevaluated
)
16275 if (TrueResult
.Kind
== IK_ICE
&& FalseResult
.Kind
== IK_ICE
)
16277 // Rare case where the diagnostics depend on which side is evaluated
16278 // Note that if we get here, CondResult is 0, and at least one of
16279 // TrueResult and FalseResult is non-zero.
16280 if (Exp
->getCond()->EvaluateKnownConstInt(Ctx
) == 0)
16281 return FalseResult
;
16284 case Expr::CXXDefaultArgExprClass
:
16285 return CheckICE(cast
<CXXDefaultArgExpr
>(E
)->getExpr(), Ctx
);
16286 case Expr::CXXDefaultInitExprClass
:
16287 return CheckICE(cast
<CXXDefaultInitExpr
>(E
)->getExpr(), Ctx
);
16288 case Expr::ChooseExprClass
: {
16289 return CheckICE(cast
<ChooseExpr
>(E
)->getChosenSubExpr(), Ctx
);
16291 case Expr::BuiltinBitCastExprClass
: {
16292 if (!checkBitCastConstexprEligibility(nullptr, Ctx
, cast
<CastExpr
>(E
)))
16293 return ICEDiag(IK_NotICE
, E
->getBeginLoc());
16294 return CheckICE(cast
<CastExpr
>(E
)->getSubExpr(), Ctx
);
16298 llvm_unreachable("Invalid StmtClass!");
16301 /// Evaluate an expression as a C++11 integral constant expression.
16302 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext
&Ctx
,
16304 llvm::APSInt
*Value
,
16305 SourceLocation
*Loc
) {
16306 if (!E
->getType()->isIntegralOrUnscopedEnumerationType()) {
16307 if (Loc
) *Loc
= E
->getExprLoc();
16312 if (!E
->isCXX11ConstantExpr(Ctx
, &Result
, Loc
))
16315 if (!Result
.isInt()) {
16316 if (Loc
) *Loc
= E
->getExprLoc();
16320 if (Value
) *Value
= Result
.getInt();
16324 bool Expr::isIntegerConstantExpr(const ASTContext
&Ctx
,
16325 SourceLocation
*Loc
) const {
16326 assert(!isValueDependent() &&
16327 "Expression evaluator can't be called on a dependent expression.");
16329 ExprTimeTraceScope
TimeScope(this, Ctx
, "isIntegerConstantExpr");
16331 if (Ctx
.getLangOpts().CPlusPlus11
)
16332 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx
, this, nullptr, Loc
);
16334 ICEDiag D
= CheckICE(this, Ctx
);
16335 if (D
.Kind
!= IK_ICE
) {
16336 if (Loc
) *Loc
= D
.Loc
;
16342 std::optional
<llvm::APSInt
>
16343 Expr::getIntegerConstantExpr(const ASTContext
&Ctx
, SourceLocation
*Loc
) const {
16344 if (isValueDependent()) {
16345 // Expression evaluator can't succeed on a dependent expression.
16346 return std::nullopt
;
16351 if (Ctx
.getLangOpts().CPlusPlus11
) {
16352 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx
, this, &Value
, Loc
))
16354 return std::nullopt
;
16357 if (!isIntegerConstantExpr(Ctx
, Loc
))
16358 return std::nullopt
;
16360 // The only possible side-effects here are due to UB discovered in the
16361 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
16362 // required to treat the expression as an ICE, so we produce the folded
16364 EvalResult ExprResult
;
16365 Expr::EvalStatus Status
;
16366 EvalInfo
Info(Ctx
, Status
, EvalInfo::EM_IgnoreSideEffects
);
16367 Info
.InConstantContext
= true;
16369 if (!::EvaluateAsInt(this, ExprResult
, Ctx
, SE_AllowSideEffects
, Info
))
16370 llvm_unreachable("ICE cannot be evaluated!");
16372 return ExprResult
.Val
.getInt();
16375 bool Expr::isCXX98IntegralConstantExpr(const ASTContext
&Ctx
) const {
16376 assert(!isValueDependent() &&
16377 "Expression evaluator can't be called on a dependent expression.");
16379 return CheckICE(this, Ctx
).Kind
== IK_ICE
;
16382 bool Expr::isCXX11ConstantExpr(const ASTContext
&Ctx
, APValue
*Result
,
16383 SourceLocation
*Loc
) const {
16384 assert(!isValueDependent() &&
16385 "Expression evaluator can't be called on a dependent expression.");
16387 // We support this checking in C++98 mode in order to diagnose compatibility
16389 assert(Ctx
.getLangOpts().CPlusPlus
);
16391 // Build evaluation settings.
16392 Expr::EvalStatus Status
;
16393 SmallVector
<PartialDiagnosticAt
, 8> Diags
;
16394 Status
.Diag
= &Diags
;
16395 EvalInfo
Info(Ctx
, Status
, EvalInfo::EM_ConstantExpression
);
16399 ::EvaluateAsRValue(Info
, this, Result
? *Result
: Scratch
) &&
16400 // FIXME: We don't produce a diagnostic for this, but the callers that
16401 // call us on arbitrary full-expressions should generally not care.
16402 Info
.discardCleanups() && !Status
.HasSideEffects
;
16404 if (!Diags
.empty()) {
16405 IsConstExpr
= false;
16406 if (Loc
) *Loc
= Diags
[0].first
;
16407 } else if (!IsConstExpr
) {
16408 // FIXME: This shouldn't happen.
16409 if (Loc
) *Loc
= getExprLoc();
16412 return IsConstExpr
;
16415 bool Expr::EvaluateWithSubstitution(APValue
&Value
, ASTContext
&Ctx
,
16416 const FunctionDecl
*Callee
,
16417 ArrayRef
<const Expr
*> Args
,
16418 const Expr
*This
) const {
16419 assert(!isValueDependent() &&
16420 "Expression evaluator can't be called on a dependent expression.");
16422 llvm::TimeTraceScope
TimeScope("EvaluateWithSubstitution", [&] {
16424 llvm::raw_string_ostream
OS(Name
);
16425 Callee
->getNameForDiagnostic(OS
, Ctx
.getPrintingPolicy(),
16426 /*Qualified=*/true);
16430 Expr::EvalStatus Status
;
16431 EvalInfo
Info(Ctx
, Status
, EvalInfo::EM_ConstantExpressionUnevaluated
);
16432 Info
.InConstantContext
= true;
16435 const LValue
*ThisPtr
= nullptr;
16438 auto *MD
= dyn_cast
<CXXMethodDecl
>(Callee
);
16439 assert(MD
&& "Don't provide `this` for non-methods.");
16440 assert(MD
->isImplicitObjectMemberFunction() &&
16441 "Don't provide `this` for methods without an implicit object.");
16443 if (!This
->isValueDependent() &&
16444 EvaluateObjectArgument(Info
, This
, ThisVal
) &&
16445 !Info
.EvalStatus
.HasSideEffects
)
16446 ThisPtr
= &ThisVal
;
16448 // Ignore any side-effects from a failed evaluation. This is safe because
16449 // they can't interfere with any other argument evaluation.
16450 Info
.EvalStatus
.HasSideEffects
= false;
16453 CallRef Call
= Info
.CurrentCall
->createCall(Callee
);
16454 for (ArrayRef
<const Expr
*>::iterator I
= Args
.begin(), E
= Args
.end();
16456 unsigned Idx
= I
- Args
.begin();
16457 if (Idx
>= Callee
->getNumParams())
16459 const ParmVarDecl
*PVD
= Callee
->getParamDecl(Idx
);
16460 if ((*I
)->isValueDependent() ||
16461 !EvaluateCallArg(PVD
, *I
, Call
, Info
) ||
16462 Info
.EvalStatus
.HasSideEffects
) {
16463 // If evaluation fails, throw away the argument entirely.
16464 if (APValue
*Slot
= Info
.getParamSlot(Call
, PVD
))
16468 // Ignore any side-effects from a failed evaluation. This is safe because
16469 // they can't interfere with any other argument evaluation.
16470 Info
.EvalStatus
.HasSideEffects
= false;
16473 // Parameter cleanups happen in the caller and are not part of this
16475 Info
.discardCleanups();
16476 Info
.EvalStatus
.HasSideEffects
= false;
16478 // Build fake call to Callee.
16479 CallStackFrame
Frame(Info
, Callee
->getLocation(), Callee
, ThisPtr
, This
,
16481 // FIXME: Missing ExprWithCleanups in enable_if conditions?
16482 FullExpressionRAII
Scope(Info
);
16483 return Evaluate(Value
, Info
, this) && Scope
.destroy() &&
16484 !Info
.EvalStatus
.HasSideEffects
;
16487 bool Expr::isPotentialConstantExpr(const FunctionDecl
*FD
,
16489 PartialDiagnosticAt
> &Diags
) {
16490 // FIXME: It would be useful to check constexpr function templates, but at the
16491 // moment the constant expression evaluator cannot cope with the non-rigorous
16492 // ASTs which we build for dependent expressions.
16493 if (FD
->isDependentContext())
16496 llvm::TimeTraceScope
TimeScope("isPotentialConstantExpr", [&] {
16498 llvm::raw_string_ostream
OS(Name
);
16499 FD
->getNameForDiagnostic(OS
, FD
->getASTContext().getPrintingPolicy(),
16500 /*Qualified=*/true);
16504 Expr::EvalStatus Status
;
16505 Status
.Diag
= &Diags
;
16507 EvalInfo
Info(FD
->getASTContext(), Status
, EvalInfo::EM_ConstantExpression
);
16508 Info
.InConstantContext
= true;
16509 Info
.CheckingPotentialConstantExpression
= true;
16511 // The constexpr VM attempts to compile all methods to bytecode here.
16512 if (Info
.EnableNewConstInterp
) {
16513 Info
.Ctx
.getInterpContext().isPotentialConstantExpr(Info
, FD
);
16514 return Diags
.empty();
16517 const CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(FD
);
16518 const CXXRecordDecl
*RD
= MD
? MD
->getParent()->getCanonicalDecl() : nullptr;
16520 // Fabricate an arbitrary expression on the stack and pretend that it
16521 // is a temporary being used as the 'this' pointer.
16523 ImplicitValueInitExpr
VIE(RD
? Info
.Ctx
.getRecordType(RD
) : Info
.Ctx
.IntTy
);
16524 This
.set({&VIE
, Info
.CurrentCall
->Index
});
16526 ArrayRef
<const Expr
*> Args
;
16529 if (const CXXConstructorDecl
*CD
= dyn_cast
<CXXConstructorDecl
>(FD
)) {
16530 // Evaluate the call as a constant initializer, to allow the construction
16531 // of objects of non-literal types.
16532 Info
.setEvaluatingDecl(This
.getLValueBase(), Scratch
);
16533 HandleConstructorCall(&VIE
, This
, Args
, CD
, Info
, Scratch
);
16535 SourceLocation Loc
= FD
->getLocation();
16536 HandleFunctionCall(
16537 Loc
, FD
, (MD
&& MD
->isImplicitObjectMemberFunction()) ? &This
: nullptr,
16538 &VIE
, Args
, CallRef(), FD
->getBody(), Info
, Scratch
,
16539 /*ResultSlot=*/nullptr);
16542 return Diags
.empty();
16545 bool Expr::isPotentialConstantExprUnevaluated(Expr
*E
,
16546 const FunctionDecl
*FD
,
16548 PartialDiagnosticAt
> &Diags
) {
16549 assert(!E
->isValueDependent() &&
16550 "Expression evaluator can't be called on a dependent expression.");
16552 Expr::EvalStatus Status
;
16553 Status
.Diag
= &Diags
;
16555 EvalInfo
Info(FD
->getASTContext(), Status
,
16556 EvalInfo::EM_ConstantExpressionUnevaluated
);
16557 Info
.InConstantContext
= true;
16558 Info
.CheckingPotentialConstantExpression
= true;
16560 // Fabricate a call stack frame to give the arguments a plausible cover story.
16561 CallStackFrame
Frame(Info
, SourceLocation(), FD
, /*This=*/nullptr,
16562 /*CallExpr=*/nullptr, CallRef());
16564 APValue ResultScratch
;
16565 Evaluate(ResultScratch
, Info
, E
);
16566 return Diags
.empty();
16569 bool Expr::tryEvaluateObjectSize(uint64_t &Result
, ASTContext
&Ctx
,
16570 unsigned Type
) const {
16571 if (!getType()->isPointerType())
16574 Expr::EvalStatus Status
;
16575 EvalInfo
Info(Ctx
, Status
, EvalInfo::EM_ConstantFold
);
16576 return tryEvaluateBuiltinObjectSize(this, Type
, Info
, Result
);
16579 static bool EvaluateBuiltinStrLen(const Expr
*E
, uint64_t &Result
,
16581 if (!E
->getType()->hasPointerRepresentation() || !E
->isPRValue())
16586 if (!EvaluatePointer(E
, String
, Info
))
16589 QualType CharTy
= E
->getType()->getPointeeType();
16591 // Fast path: if it's a string literal, search the string value.
16592 if (const StringLiteral
*S
= dyn_cast_or_null
<StringLiteral
>(
16593 String
.getLValueBase().dyn_cast
<const Expr
*>())) {
16594 StringRef Str
= S
->getBytes();
16595 int64_t Off
= String
.Offset
.getQuantity();
16596 if (Off
>= 0 && (uint64_t)Off
<= (uint64_t)Str
.size() &&
16597 S
->getCharByteWidth() == 1 &&
16598 // FIXME: Add fast-path for wchar_t too.
16599 Info
.Ctx
.hasSameUnqualifiedType(CharTy
, Info
.Ctx
.CharTy
)) {
16600 Str
= Str
.substr(Off
);
16602 StringRef::size_type Pos
= Str
.find(0);
16603 if (Pos
!= StringRef::npos
)
16604 Str
= Str
.substr(0, Pos
);
16606 Result
= Str
.size();
16610 // Fall through to slow path.
16613 // Slow path: scan the bytes of the string looking for the terminating 0.
16614 for (uint64_t Strlen
= 0; /**/; ++Strlen
) {
16616 if (!handleLValueToRValueConversion(Info
, E
, CharTy
, String
, Char
) ||
16619 if (!Char
.getInt()) {
16623 if (!HandleLValueArrayAdjustment(Info
, E
, String
, CharTy
, 1))
16628 bool Expr::EvaluateCharRangeAsString(std::string
&Result
,
16629 const Expr
*SizeExpression
,
16630 const Expr
*PtrExpression
, ASTContext
&Ctx
,
16631 EvalResult
&Status
) const {
16633 EvalInfo
Info(Ctx
, Status
, EvalInfo::EM_ConstantExpression
);
16634 Info
.InConstantContext
= true;
16636 FullExpressionRAII
Scope(Info
);
16638 if (!::EvaluateInteger(SizeExpression
, SizeValue
, Info
))
16641 int64_t Size
= SizeValue
.getExtValue();
16643 if (!::EvaluatePointer(PtrExpression
, String
, Info
))
16646 QualType CharTy
= PtrExpression
->getType()->getPointeeType();
16647 for (int64_t I
= 0; I
< Size
; ++I
) {
16649 if (!handleLValueToRValueConversion(Info
, PtrExpression
, CharTy
, String
,
16653 APSInt C
= Char
.getInt();
16654 Result
.push_back(static_cast<char>(C
.getExtValue()));
16655 if (!HandleLValueArrayAdjustment(Info
, PtrExpression
, String
, CharTy
, 1))
16658 if (!Scope
.destroy())
16661 if (!CheckMemoryLeaks(Info
))
16667 bool Expr::tryEvaluateStrLen(uint64_t &Result
, ASTContext
&Ctx
) const {
16668 Expr::EvalStatus Status
;
16669 EvalInfo
Info(Ctx
, Status
, EvalInfo::EM_ConstantFold
);
16670 return EvaluateBuiltinStrLen(this, Result
, Info
);